how to use pos in MigLayout? - miglayout

This is my code:
public class InfoPanel extends JPanel{
... ... ...
... ... ...
public InfoPanel(){
... ... ...
... ... ...
MigLayout lManager = new MigLayout();
setLayout(lManager);
add(lblName,new CC().pos("50", "80"));
add(txtName, new CC().pos("90","80").width("170").wrap().gap("r"));
add(lblOccupation,"pos 20 100");
add(txtOccupation,"pos 91 100,w 170,wrap,gap r");
and it has the right output.
but I want to use any built in code for calculate pos() for txtName, txtOccupation.
can anybody help me to do that.

From the image as template:
public class MigLayoutTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MigLayoutTest().start();
}
});
}
private void start() {
JFrame frame = new JFrame();
Container contentPane = frame.getContentPane();
contentPane.setLayout(new MigLayout("wrap 4, debug", "[][fill, grow 1][][fill, grow 4]", ""));
//Declaration
JLabel nameLabel, employmenLabel, ssnLabel, taxIDLabel;
JTextField nameField, ssnField, taxIDField;
JComboBox<String> employmentBox;
JCheckBox checkbox;
JButton save, cancel, upload;
JPanel imagePlaceholder;
//Initialization
nameLabel = new JLabel("Name");
employmenLabel = new JLabel("Employment");
ssnLabel = new JLabel("Social Security Number");
taxIDLabel = new JLabel("tax ID");
nameField = new JTextField();
ssnField = new JTextField();
taxIDField = new JTextField();
save = new JButton("Save");
cancel = new JButton("Cancel");
upload = new JButton("Upload");
checkbox = new JCheckBox("Checkbox");
imagePlaceholder = new JPanel();
employmentBox = new JComboBox<String>();
//Some editing
imagePlaceholder.setBackground(Color.GREEN);
employmentBox.addItem("Some");
employmentBox.addItem("items");
employmentBox.addItem("to");
employmentBox.addItem("fill");
employmentBox.addItem("this");
//Adding to contentPane
contentPane.add(nameLabel, "alignx right");
contentPane.add(nameField, "");
contentPane.add(ssnLabel, "alignx right");
contentPane.add(ssnField, "");
contentPane.add(employmenLabel, "alignx right");
contentPane.add(employmentBox, "");
contentPane.add(upload, "");
contentPane.add(imagePlaceholder, "spany 3, grow");
contentPane.add(checkbox, "split 2");
contentPane.add(taxIDLabel, "");
contentPane.add(taxIDField, "wrap");
contentPane.add(save, "");
contentPane.add(cancel, "growx 0, wrap");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

Related

ChromiumWebBrowser flash black after hiding without disabling WebGL

I am trying to hide my ChromiumWebBrowser behind images, video, etc... But every time it changes from a ChromiumWebBrowser to anything else than a blank panel or another ChromiumWebBrowser it flashes black for a few frames.
Exemple of my problem
hardware:
i7-8559U
intel IRI plus Graphics 655
CefSharp Version 79.1.350 for a Winform Program
Here is what I tried:
BringToFront other PictureBox
SendToback the ChromiumWebBrowser
Panel visibility
Panel doubleBuffed
I also enable Cef.EnableHighDPISupport(); but to no success.
The only thing that worked so far is to ADD
SetOffScreenRenderingBestPerformanceArgs();
But unfortunately, it disables WebGL implementation :/ and I would like to keep it for later purposes.
static class Program
{
/// <summary>
/// Point d'entrée principal de l'application.
/// </summary>
[STAThread]
static void Main()
{
Cef.EnableHighDPISupport();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
public partial class Form1 : Form
{
private static ChromiumWebBrowser chrome;
private PictureBox ImageBox = new PictureBox();
private Panel pPictureBox = new Panel();
private Panel pChromium = new Panel();
Timer timer = new Timer();
public Form1()
{
InitializeComponent();
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
ImageBox.Image = Properties.Resources._3080;
ImageBox.SizeMode = PictureBoxSizeMode.StretchImage;
pPictureBox.Controls.Add(ImageBox);
ImageBox.Dock = DockStyle.Fill;
pPictureBox.Dock = DockStyle.Fill;
pPictureBox.Size = this.Size;
this.Controls.Add(pPictureBox);
pPictureBox.BringToFront();
InitializeChromium();
timer.Interval = 7000;
timer.Start();
timer.Tick += Timer_Tick;
}
private void Timer_Tick(object sender, EventArgs e)
{
if (pChromium.Visible)
{
pChromium.Hide();
}
else
{
pChromium.Show();
}
}
private void InitializeChromium()
{
pChromium.Dock = DockStyle.Fill;
pChromium.Size = this.Size;
CefSettings settings = new CefSettings();
//Work but disable WebGL
//settings.SetOffScreenRenderingBestPerformanceArgs();
//settings.DisableGpuAcceleration();
Cef.Initialize(settings);
chrome = new ChromiumWebBrowser("https://www.apple.com/ca/airpods-pro/");
pChromium.Controls.Add(chrome);
this.Controls.Add(pChromium);
chrome.Dock = DockStyle.Fill;
pChromium.BringToFront();
}
private void InitializeComponent()
{
this.SuspendLayout();
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(1904, 1041);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Cef.Shutdown();
}
}
Do you guys have any solution?
Here is my final code for any one interested
Links of the command recommanded by #amaitland
https://peter.sh/experiments/chromium-command-line-switches/#use-angle
https://peter.sh/experiments/chromium-command-line-switches/#in-process-gpu
both command works individualy
Cef.EnableHighDPISupport(); is not required but is recommanded
static void Main()
{
Cef.EnableHighDPISupport();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
public partial class Form1 : Form
{
private static ChromiumWebBrowser chrome;
private PictureBox ImageBox = new PictureBox();
private Panel pPictureBox = new Panel();
private Panel pChromium = new Panel();
Timer timer = new Timer();
public Form1()
{
InitializeComponent();
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
//any image here
ImageBox.Image = Properties.Resources._3080;
ImageBox.SizeMode = PictureBoxSizeMode.StretchImage;
pPictureBox.Controls.Add(ImageBox);
ImageBox.Dock = DockStyle.Fill;
pPictureBox.Dock = DockStyle.Fill;
pPictureBox.Size = this.Size;
this.Controls.Add(pPictureBox);
pPictureBox.BringToFront();
InitializeChromium();
timer.Interval = 7000;
timer.Start();
timer.Tick += Timer_Tick;
}
private void Timer_Tick(object sender, EventArgs e)
{
if (pChromium.Visible)
{
pChromium.Hide();
}
else
{
pChromium.Show();
}
}
private void InitializeChromium()
{
pChromium.Dock = DockStyle.Fill;
pChromium.Size = this.Size;
CefSettings settings = new CefSettings();
//-------------------------------------------------------------------------
settings.CefCommandLineArgs.Add("in-process-gpu");
//got best FPS with this renderer on "my machine"
settings.CefCommandLineArgs.Add("use-angle", "gl");
//-------------------------------------------------------------------------
//Work but disable WebGL
//settings.SetOffScreenRenderingBestPerformanceArgs();
//settings.DisableGpuAcceleration();
Cef.Initialize(settings);
chrome = new ChromiumWebBrowser("https://alteredqualia.com/three/examples/webgl_pasta.html");
pChromium.Controls.Add(chrome);
this.Controls.Add(pChromium);
chrome.Dock = DockStyle.Fill;
pChromium.BringToFront();
}
private void InitializeComponent()
{
this.SuspendLayout();
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(1904, 1041);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Cef.Shutdown();
}
}

iOS save to storage issue

I've an issue while trying to save an image to the Storage in iOS. Image is downloaded but not saved.
The code is:
Form hi = new Form("Toolbar", new BoxLayout(BoxLayout.Y_AXIS));
TreeModel tm = new TreeModel() {
#Override
public Vector getChildren(Object parent) {
String[] files;
if (parent == null) {
files = FileSystemStorage.getInstance().getRoots();
return new Vector<Object>(Arrays.asList(files));
} else {
try {
files = FileSystemStorage.getInstance().listFiles((String) parent);
} catch (IOException err) {
Log.e(err);
files = new String[0];
}
}
String p = (String) parent;
Vector result = new Vector();
for (String s : files) {
result.add(p + s);
}
return result;
}
#Override
public boolean isLeaf(Object node) {
return !FileSystemStorage.getInstance().isDirectory((String) node);
}
};
Command tree = new Command("Show tree") {
#Override
public void actionPerformed(ActionEvent evt) {
Form treeForm = new Form("Tree", new BorderLayout());
Tree t = new Tree(tm) {
#Override
protected String childToDisplayLabel(Object child) {
String n = (String) child;
int pos = n.lastIndexOf("/");
if (pos < 0) {
return n;
}
return n.substring(pos);
}
};
treeForm.add(BorderLayout.CENTER, t);
Command back = new Command("Back") {
#Override
public void actionPerformed(ActionEvent evt) {
hi.showBack();
}
};
Button backButton = new Button(back);
treeForm.add(BorderLayout.SOUTH, backButton);
treeForm.show();
}
};
hi.getToolbar().addCommandToOverflowMenu(tree);
EncodedImage placeholder = EncodedImage.createFromImage(Image.createImage(hi.getWidth(), hi.getWidth() / 5, 0xffff0000), true);
String photoURL = "https://awoiaf.westeros.org/images/thumb/9/93/AGameOfThrones.jpg/400px-AGameOfThrones.jpg";
StringBuilder fsPath = new StringBuilder(FileSystemStorage.getInstance().getAppHomePath());
fsPath.append("400px-AGameOfThrones.jpg");
URLImage background = URLImage.createToStorage(placeholder, fsPath.toString(), photoURL);
background.fetch();
Style stitle = hi.getToolbar().getTitleComponent().getUnselectedStyle();
stitle.setBgImage(background);
stitle.setBackgroundType(Style.BACKGROUND_IMAGE_SCALED_FILL);
stitle.setPaddingUnit(Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS);
stitle.setPaddingTop(15);
SpanButton credit = new SpanButton("Link");
credit.addActionListener((e) -> Display.getInstance().execute("https://awoiaf.westeros.org/index.php/A_Game_of_Thrones"));
hi.add(new SpanLabel("A")).
add(new Label("B", "Heading")).
add(credit);
ComponentAnimation title = hi.getToolbar().getTitleComponent().createStyleAnimation("Title", 200);
hi.getAnimationManager().onTitleScrollAnimation(title);
hi.show();
Which was taken from https://www.codenameone.com/javadoc/com/codename1/ui/URLImage.html
The tree is only to see if the image was saved in the Storage.
You are mixing Storage & FileSystemStorage which are very different things see this.
You can use storage which is a flat set of "files" and that's what URLImage.createToStorage does. But then you need to use the Storage API to work with that and it might not be visible in the FileSystemStorage API.
Alternatively you might be looking for URLImage.createToFileSystem().

iOS Issue : IndexOutOfBoundsException

I'm facing an issue with iOS.
I have an App who works perfectly on Android. I build it for Android Debug and when i try to show my form, i got an IndexOutOfBoundsException
Here is my code :
package com.idenovia.calendovia.form;
public class FichePro extends Form {
public static Site site;
public static Boolean isFavorite = false;
public static List<Performance> performances = new ArrayList<Performance>();
public static Long canContactTakeEvent;
public FichePro(final int idPro,final String searchWho, final List<Site> savedSites){
try {
Dialog ip = new InfiniteProgress().showInifiniteBlocking();
ip.getContentPane().getStyle().setBgTransparency(0, true);
ip.getContentPane().getComponentAt(0).getStyle().setBgTransparency(0, true);
Map<String,Object> result;
if(CalendoviaApp.isConnected ==1 && CalendoviaApp.customer.getId() != 0)
result = AccessSite.getSiteFromId(idPro,CalendoviaApp.customer.getId());
else
result = AccessSite.getSiteFromId(idPro,0);
if(result.containsKey("sites")){
site = (Site) result.get("sites");
}else{
site = null;
}
if(result.containsKey("performances")){
performances = (List<Performance>) result.get("performances");
}else{
performances = null;
}
if(result.containsKey("canContactTakeEvent")){
canContactTakeEvent = (Long) result.get("canContactTakeEvent");
}else{
canContactTakeEvent = null;
}
ip.dispose();
} catch (Exception e1) {
e1.printStackTrace();
}
/*
* Form theming and configuring
*/
if(site != null)
setTitle("Dr. "+site.getSiteYou().getShowname());
else{
SearchList searchList = new SearchList(searchWho,"",savedSites);
searchList.show();
}
Container content = new Container(new BoxLayout(BoxLayout.Y_AXIS));
content.setUIID("ctrContent");
setLayout(new BorderLayout());
setTransitionInAnimator(CommonTransitions.createFade(200));
final Font fnt = Font.createTrueTypeFont("CALENDOVIA_APP", "CALENDOVIA_APP.ttf");
Container ctrPhoto = new Container(new BorderLayout());
ctrPhoto.setUIID("ctrPhoto");
// try {
Image image = CalendoviaApp.res.getImage("placeholderProvider").scaled((int)(Display.getInstance().getDisplayWidth()*0.25),(int)(Display.getInstance().getDisplayWidth()*0.25));
for (Site favoris : CalendoviaApp.favorites) {
if(favoris.getId().equals(site.getId())){
isFavorite = true;
}
}
final CheckBox favButton2 = new CheckBox();
final Button favButton = new Button();
if(isFavorite){
favButton.setIcon(FontImage.createFixed("\ue900", fnt, 0x2995d0,(int)(Display.getInstance().getDisplayWidth()*0.2), (int)(Display.getInstance().getDisplayWidth()*0.2)));
}else{
favButton.setIcon(FontImage.createFixed("\ue931", fnt, 0x2995d0,(int)(Display.getInstance().getDisplayWidth()*0.2), (int)(Display.getInstance().getDisplayWidth()*0.2)));
}
favButton.setTextPosition(Component.BOTTOM);
favButton.getStyle().setBgTransparency(0,true);
favButton.getPressedStyle().setBgTransparency(0,true);
favButton.getDisabledStyle().setBgTransparency(0,true);
favButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(isFavorite){
do some stuff like seticon or network access
}else{
do some stuff too
}
}
});
ctrPhoto.add(BorderLayout.WEST, image);
ctrPhoto.add(BorderLayout.EAST, favButton);
Container ctrglobalInfosFichePro = new Container(new BoxLayout(BoxLayout.Y_AXIS));
ctrglobalInfosFichePro.setScrollVisible(false);
ctrglobalInfosFichePro.setScrollableY(true);
ctrglobalInfosFichePro.setUIID("ctrglobalInfosFichePro");
//First Part
Container ctrglobalInfosFirstPart = new Container(new BoxLayout(BoxLayout.Y_AXIS));
ctrglobalInfosFirstPart.setScrollableY(false);
ctrglobalInfosFirstPart.setUIID("ctrglobalInfosFirstPart");
Label lblProviderName = new Label("Dr "+site.getSiteYou().getShowname());
lblProviderName.setUIID("lblNameProvider");
ctrglobalInfosFichePro.add(lblProviderName);
try{
Label lblProviderSpe = new Label(new SectorConvert().getValue(site.getSiteYou().getSectorfirst().intValue()).toString());
lblProviderSpe.setUIID("lblSpeProvider");
ctrglobalInfosFichePro.add(lblProviderSpe);
}catch(Exception e){
} if(site.getSiteOption().getCbcard()||site.getSiteOption().getCheckp()||site.getSiteOption().getSpecies()){
Label lblPaiement = new Label("MOYENS DE PAIEMENT");
lblPaiement.setUIID("lblTitleForSpanLabel");
lblPaiement.setVerticalAlignment(Component.CENTER);
String acceptedPaiement ="";
if(site.getSiteOption().getCbcard()){
acceptedPaiement+=" CB /";
}
Label lblAcceptedPaiement = new Label(acceptedPaiement);
ctrglobalInfosFirstPart.add(lblPaiement);
ctrglobalInfosFirstPart.add(lblAcceptedPaiement);
}
//Second Part
Container ctrglobalInfosSecondPart= new Container(new BorderLayout());
if(site.getSiteYou().getPhonepro().trim().length() != 0){
ctrglobalInfosSecondPart.setUIID("ctrglobalInfosFirstPart");
Button btnAppeler = new Button("Appeler");
btnAppeler.setUIID("btnAppelerFichePro");
btnAppeler.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
Display.getInstance().dial(site.getSiteYou().getPhonepro());
}
});
ctrglobalInfosSecondPart.add(BorderLayout.EAST,btnAppeler);
}
ctrglobalInfosFichePro.add(ctrglobalInfosFirstPart);
ctrglobalInfosFichePro.add(ctrglobalInfosSecondPart);
content.add(ctrglobalInfosFichePro);
/*
* Building Form
*/
if(site.getCanaccess()){
Button btnTakeAppointement = new Button("");
btnTakeAppointement.setUIID("");
btnTakeAppointement.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
if(site.getNewcontactblocked()){
if(canContactTakeEvent != null && CalendoviaApp.isConnected==1 && CalendoviaApp.customer.getId() != 0){
switch(canContactTakeEvent.intValue()){
case 0:
FicheProCannotTakeEvent ficheProCannotTakeEvent = new FicheProCannotTakeEvent(site, canContactTakeEvent, savedSites, searchWho,true);
ficheProCannotTakeEvent.show();
break;
case 1:
FicheProRdvSelect ficheProRdvSelect = new FicheProRdvSelect(performances,site, savedSites, searchWho, null);
ficheProRdvSelect.show();
break;
[...]
default:
FicheProCannotTakeEvent ficheProCannotTakeEvent4 = new FicheProCannotTakeEvent(site, new Long(4), savedSites, searchWho,true);
ficheProCannotTakeEvent4.show();
break;
}
}else{
FicheProCannotTakeEvent ficheProCannotTakeEvent = new FicheProCannotTakeEvent(site, new Long(0), savedSites, searchWho,false);
ficheProCannotTakeEvent.show();
}
}
else{
FicheProRdvSelect ficheProRdvSelect = new FicheProRdvSelect(performances,site, savedSites, searchWho, null);
ficheProRdvSelect.show();
}
}
});
addComponent(BorderLayout.SOUTH,btnTakeAppointement);
}else{
Button btnParrainage = new Button("");
btnParrainage.setUIID("btnTakeRdvBig");
btnParrainage.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
Parrainage parrainage = new Parrainage(site, getComponentForm());
parrainage.show();
}
});
addComponent(BorderLayout.SOUTH,btnParrainage);
}
addComponent(BorderLayout.NORTH, ctrPhoto);
addComponent(BorderLayout.CENTER, content);
}
}
I can't find the error where it happens and why...
Thanks for your help

Issue populating JComboBox with array

I've been working on this for a while but I can't seem to fix the one line that is giving me all the problems. This line "list = new JComboBox(measure);" underneath the array, seems to be giving me the error. I can suppress the error and it runs except the JComboBox does not work properly and gives the error
"Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JComboBox cannot be cast to javax.swing.JButton
at cube.actionPerformed(cube.java:132)"
Any help will be greatly appreciated!
import java.util.Scanner;
import javax.swing.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
//#SuppressWarnings("unchecked")
public class cube extends JFrame implements ActionListener{
public static JComboBox list;
public static JTextField a;
public static JTextField b;
public static JTextField c;
public static JTextField d;
public static String measureFinal;
public static String measurement;
//public static String [] measurement = {"Inches" , "Meters", "Feet" , "Centimeters" , "Millimeters" , "Yards" };
public static JFrame main = new JFrame("Volume of Cube");
public static JPanel myPanel = new JPanel(new GridLayout (0,1));
public static void main(String args[]){
cube object = new cube();
}
cube(){
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myPanel.setPreferredSize(new Dimension(400,350));
main.add(myPanel);
a = new JTextField(3);
b = new JTextField(3);
c = new JTextField(3);
d = new JTextField(3);
JButton button1 = new JButton("Solve!");
JButton button2 = new JButton("Back to shape selector");
myPanel.add(new JLabel ("Select the unit of measurement"));
String measure[] = {"Inches" , "Meters", "Feet" , "Centimeters" , "Millimeters" , "Yards" };
list = new JComboBox(measure);
list.setSelectedIndex(0);
list.addActionListener(this);
myPanel.add(list);
myPanel.add(new JLabel ("Enter the height of the box"));
myPanel.add(a);
myPanel.add(new JLabel ("Enter the width of the box"));
myPanel.add(b);
myPanel.add(new JLabel ("Enter the length of the box"));
myPanel.add(c);
myPanel.add(button1);
button1.addActionListener(this);
myPanel.add(button2);
button2.addActionListener(this);
main.pack();
main.setLocation(600,200);
main.setVisible(true);
//tring [] measurement = {"Inches" , "Meters", "Feet"};
//double volume = height * width * length;
//String answer = "The volume of the box is " +volume+ measurement;
}
public void CBSelect(ActionEvent e){
int temp = 0;
temp = list.getSelectedIndex();
//Object temp = e.getSource();
/*
if (e.getSource() == list){
temp = list.getSelectedIndex();
switch(temp){
case 0:
measurement = "Inches";
break;
case 1:
measurement = "Meters";
break;
case 2:
measurement = "Feet";
break;
case 3:
measurement = "Centimeters";
break;
case 4:
measurement = "Millimeters";
break;
case 5:
measurement = "Yards";
break;
}
}
*/
if (temp == 0){
measurement = "Inches";
} else if (temp == 1){
measurement = "Meters";
}else if (temp == 2){
measurement = "Feet";
}else if (temp == 3){
measurement = "Centimeters";
}else if (temp == 4){
measurement = "Millimeters";
}else if (temp == 5){
measurement = "Yards";
}
}
public void actionPerformed(ActionEvent e) {
String actionCommand = ((JButton) e.getSource()).getActionCommand();
//JComboBox cb = ((JComboBox) e.getSource());
//measureFinal = (String)cb.getSelectedItem();
if (actionCommand == "Solve!"){
double height = Double.parseDouble(a.getText());
double width = Double.parseDouble(b.getText());
double length = Double.parseDouble(c.getText());
double volume = height * width * length;
try{
final ImageIcon icon = new ImageIcon(new URL("http://wiki.fantasticcontraption.com/w/images/0/06/Solved.png"));
JOptionPane.showMessageDialog(this, ("The volume of the box is " +volume+" "+ measurement),"Volume", JOptionPane.PLAIN_MESSAGE, icon);
} catch (MalformedURLException ex){
System.out.println("Image Not Found!");
}
}
if (actionCommand == "Back to shape selector"){
main.dispose();
main.setVisible(false);
}
}
}
UPDATE: Looking back at it I'm now thinking the problem lies within the CBSelect Action Listener.
The thing is, since you do:
list.addActionListener(this);
// some other stuff...
button1.addActionListener(this);
button2.addActionListener(this);
Then source of the events passed to your method cube#actionPerformed can be list, button1 or button2.
So, you have you check the type of the source before casting it to anything and access its properties in the body of your actionPerformed method. You could do it like this:
final Object source = e.getSource();
String actionCommand = null;
if(source instanceof JButton) {
actionCommand = ((JButton) e.getSource()).getActionCommand();
} else if(source instanceof JComboBox<?>) {
actionCommand = ((JComboBox) e.getSource()).getSelectedItem().toString();
}
Cheers!
See if this works like you wanted:
import java.util.Scanner;
import javax.swing.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
//#SuppressWarnings("unchecked")
public class cube extends JFrame implements ActionListener{
public static JComboBox list;
public static JTextField a;
public static JTextField b;
public static JTextField c;
public static JTextField d;
public static String measureFinal;
public static String [] measurement = {"Inches" , "Meters", "Feet" , "Centimeters" , "Millimeters" , "Yards" };
public static JFrame main = new JFrame("Volume of Cube");
public static JPanel myPanel = new JPanel(new GridLayout (0,1));
public static void main(String args[]){
cube object = new cube();
}
cube(){
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myPanel.setPreferredSize(new Dimension(400,350));
main.add(myPanel);
a = new JTextField(3);
b = new JTextField(3);
c = new JTextField(3);
d = new JTextField(3);
JButton button1 = new JButton("Solve!");
JButton button2 = new JButton("Back to shape selector");
myPanel.add(new JLabel ("Select the unit of measurement"));
String measure[] = {"Inches" , "Meters", "Feet" , "Centimeters" , "Millimeters" , "Yards" };
list = new JComboBox(measure);
list.setSelectedIndex(0);
list.addActionListener(this);
myPanel.add(list);
myPanel.add(new JLabel ("Enter the height of the box"));
myPanel.add(a);
myPanel.add(new JLabel ("Enter the width of the box"));
myPanel.add(b);
myPanel.add(new JLabel ("Enter the length of the box"));
myPanel.add(c);
myPanel.add(button1);
button1.addActionListener(this);
myPanel.add(button2);
button2.addActionListener(this);
main.pack();
main.setLocation(600,200);
main.setVisible(true);
}
public void CBSelect(ActionEvent e){
int temp = 0;
temp = list.getSelectedIndex();
}
public void actionPerformed(ActionEvent e) {
String actionCommand = ((JButton) e.getSource()).getActionCommand();
measureFinal = (String)list.getSelectedItem();
if (actionCommand == "Solve!"){
double height = Double.parseDouble(a.getText());
double width = Double.parseDouble(b.getText());
double length = Double.parseDouble(c.getText());
double volume = height * width * length;
try{
final ImageIcon icon = new ImageIcon(new URL("http://wiki.fantasticcontraption.com/w/images/0/06/Solved.png"));
JOptionPane.showMessageDialog(this, ("The volume of the box is " +volume+" "+ measureFinal),"Volume", JOptionPane.PLAIN_MESSAGE, icon);
} catch (MalformedURLException ex){
System.out.println("Image Not Found!");
}
}
if (actionCommand == "Back to shape selector"){
main.dispose();
main.setVisible(false);
}
}
}

ImageDownloadServices in codenameone

I am trying below mention code for download image from server but it's not working and not giving me any error. Please suggest if any thing wrong which i used.When i am accessing URL from browser it's displaying image to me.
int pos;
public void DisplayContent()
{
f = (Form)createContainer(GlobalVariables.Theme, "ContentPageWise");
body = (Container) findByName("Containerbody", f);
Display_Image = new Image[Page_Details.size()];
for(int i=0;i<Page_Details.size();i++)
{
Hashtable<String,String> hash_page = Page_Details.get(i);
Log.p("imagepath:"+hash_page.get("imgPage"));
pos=i;
GetImagesFromserver(hash_page.get("imgPage"));
Container Cpage = new Container(new BoxLayout(BoxLayout.Y_AXIS));
Label pic = new Label();
pic.setIcon(Display_Image[i]);
Cpage.addComponent(pic);
body.addComponent(Cpage);
}
}
void GetImagesFromserver(String Imagepath)
{
//eg. url like this: http://lmsasr.gizmosupport.com/presentation/tele/internet.jpg
ImageDownloadService imageDownloadService =
new ImageDownloadService(Imagepath, actionListener);
InfiniteProgress ip = new InfiniteProgress();
imageDownloadService.setDisposeOnCompletion(ip.showInifiniteBlocking());
NetworkManager.getInstance().addToQueue(imageDownloadService);
}
ActionListener actionListener = new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
NetworkEvent n = (NetworkEvent) evt;
Display_Image[pos] = ((Image)n.getMetaData());
}
};

Resources