java.lang.numberformatexception empty string java awt - java
public class CustomCalculator extends Frame implements ActionListener{
Panel jp1 = new Panel();
Panel jp2 = new Panel();
Panel jp3 = new Panel();
Panel jp4 = new Panel();
Panel jp5 = new Panel();
Panel center_merge = new Panel();
Label l2 = new Label("Quantity : ");
TextField l2a = new TextField(20);
Label l3 = new Label("Invoice Value : ");
TextField l3a = new TextField(20);
Label l4 = new Label("Exchange Rate : ");
TextField l4a = new TextField(20);
Label l5 = new Label("Costing(A) : ");
TextField l5a = new TextField();
Label l6 = new Label("(A + 1%)(B) : ");
Label l6a = new Label();
Label l7 = new Label("BCD (C) : ");
Label l7a = new Label("");
Label l8 = new Label("CVD (D) : ");
Label l8a = new Label("");
Label l9 = new Label("Custom Education Cess (E) : ");
Label l9a = new Label("");
Label l10 = new Label("Custom Sec & Higher Edu.Cess (F) : ");
Label l10a = new Label("");
Label l11 = new Label("Additional Duty Imports (G) : ");
Label l11a = new Label("");
Label l12 = new Label("Total (H) : ");
Label l12a = new Label("");
Label l13 = new Label("Costing+Total (I) : ");
Label l13a = new Label("");
Label l14 = new Label("(H/Quantity) (J) : ");
Label l14a = new Label("");
Label l15 = new Label("4% SAD (G/Quantity) (K) : ");
Label l15a = new Label("");
Label l16 = new Label("Net Costing (L) : ");
Label l16a = new Label("");
Label l17 = new Label("Transportation (M) : ");
TextField l17a = new TextField(5);
Label l18 = new Label("Godown Rate (N) : ");
TextField l18a = new TextField(5);
Label l19 = new Label("Brokerage (O) : ");
TextField l19a = new TextField(5);
Label l20 = new Label("Actual Costing (P) : ");
Label l20a = new Label("");
Label l21 = new Label("Small Gatepass (Q) : ");
Label l21a = new Label("");
Label l22 = new Label("Big Gatepass (R) : ");
Label l22a = new Label("");
Button l2b = new Button("reset");
Button l3b = new Button("reset");
Button l4b = new Button("reset");
Button master_reset = new Button("reset all");
Button calc = new Button("Calculate");
public CustomCalculator()
{
super("Custom Calculator");
this.setSize(800,700);
jp1.setLayout(new FlowLayout());
//jp1.setBorder(BorderFactory.createLineBorder(Color.GRAY));
jp1.add(l2);
jp1.add(l2a);
jp1.add(l2b);
jp1.add(l3);
jp1.add(l3a);
jp1.add(l3b);
jp1.add(l4);
jp1.add(l4a);
jp1.add(l4b);
jp2.setLayout(new GridLayout(6,2));
//jp2.setBorder(BorderFactory.createLineBorder(Color.GRAY));
jp2.add(l5);
jp2.add(l5a);
jp2.add(l6);
jp2.add(l6a);
jp2.add(l7);
jp2.add(l7a);
jp2.add(l8);
jp2.add(l8a);
jp2.add(l9);
jp2.add(l9a);
jp2.add(l10);
jp2.add(l10a);
jp3.setLayout(new GridLayout(6,2));
//jp3.setBorder(BorderFactory.createLineBorder(Color.GRAY));
jp3.add(l11);
jp3.add(l11a);
jp3.add(l12);
jp3.add(l12a);
jp3.add(l13);
jp3.add(l13a);
jp3.add(l14);
jp3.add(l14a);
jp3.add(l15);
jp3.add(l15a);
jp3.add(l16);
jp3.add(l16a);
jp4.setLayout(new GridLayout(6,2));
//jp4.setBorder(BorderFactory.createLineBorder(Color.GRAY));
jp4.add(l17);
jp4.add(l17a);
jp4.add(l18);
jp4.add(l18a);
jp4.add(l19);
jp4.add(l19a);
jp4.add(l20);
jp4.add(l20a);
jp4.add(l21);
jp4.add(l21a);
jp4.add(l22);
jp4.add(l22a);
center_merge.setLayout(new GridLayout(1,3));
//center_merge.setBorder(BorderFactory.createLineBorder(Color.GRAY));
center_merge.add(jp2);
center_merge.add(jp3);
center_merge.add(jp4);
jp5.setLayout(new FlowLayout());
//jp5.setBorder(BorderFactory.createLineBorder(Color.GRAY));
jp5.add(calc);
jp5.add(master_reset);
this.setLayout(new BorderLayout());
this.add(jp1,BorderLayout.NORTH);
this.add(center_merge,BorderLayout.CENTER);
this.add(jp5,BorderLayout.SOUTH);
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
l2b.addActionListener(this);
l3b.addActionListener(this);
l4b.addActionListener(this);
calc.addActionListener(this);
master_reset.addActionListener(this);
this.setVisible(true);
}
public static void main(String[] args) {
new CustomCalculator();
}
#Override
public void actionPerformed(ActionEvent ae) {
double quantity = 0;
double invoice_value = 0;
double exchange_rate = 0;
double A=0;
double B=0;
double C=0;
double D=0;
double E=0;
double F=0;
double G=0;
double H=0;
double I=0;
double J=0;
double K=0;
double L=0;
double M = 0;
double N = 0;
double O=0;
double P=0;
double Q=0;
double R=0;
try
{
quantity = Double.parseDouble(l2a.getText());
invoice_value = Double.parseDouble(l3a.getText());
exchange_rate = Double.parseDouble(l4a.getText());
M = Double.parseDouble(l17a.getText());
N = Double.parseDouble(l18a.getText());
O = Double.parseDouble(l19a.getText());
A = invoice_value*exchange_rate;
B = A+(0.01*A);
C = 0.075*B;
D = 0.12*(B+C);
E = 0.02*(C+D);
F = 0.01*(C+D);
G = 0.04*(B+C+D+E+F);
H = C+D+E+F+G;
I = A+H;
J = H/quantity;
K = G/quantity;
L = J-K;
P = L+M+N+O;
Q = (0.12*B)/quantity;
R = Q+K;
if(ae.getActionCommand().equals("calc"))
{
l5a.setText(String.valueOf(A));
l6a.setText(String.valueOf(B));
l7a.setText(String.valueOf(C));
l8a.setText(String.valueOf(D));
l9a.setText(String.valueOf(E));
l10a.setText(String.valueOf(F));
l11a.setText(String.valueOf(G));
l12a.setText(String.valueOf(H));
l13a.setText(String.valueOf(I));
l14a.setText(String.valueOf(J));
l15a.setText(String.valueOf(K));
l16a.setText(String.valueOf(L));
l20a.setText(String.valueOf(P));
l21a.setText(String.valueOf(Q));
l22a.setText(String.valueOf(R));
}
else if(ae.getActionCommand().equals("master_reset"))
{
l5a.setText("");
l2a.setText("");
l3a.setText("");
l4a.setText("");
}
}
catch (Exception ex)
{
l5a.setText(ex.toString());
// l3a.setText(ex.toString());
}
}
}
After I click the Calculate button (button calc) the calculated values do not appear in the respective labels and an exception is shown saying java.lang.NumberFormatException: Empty string. I am not able to figure out the solution. please help.
the line exchange_rate = Double.parseDouble(l4a.getText()); gives you this exception, because there is no value in l4a and you are trying to parse it into a double value,
try printing the exception in the catch clause.
It's probably a relatively safe bet to say that it is happening here at the beginning of your function, though you should provide the actual exception and line number for us.
quantity = Double.parseDouble(l2a.getText());
invoice_value = Double.parseDouble(l3a.getText());
exchange_rate = Double.parseDouble(l4a.getText());
M = Double.parseDouble(l17a.getText());
N = Double.parseDouble(l18a.getText());
O = Double.parseDouble(l19a.getText());
Make sure that each of these fields actually has numeric text in it. I would recommend putting a logging line or an alert line to state their values before this is executed. Better yet, you can catch the first line in a debugger and look at the the values of all of the items you're calling getText() on. I bet one has an empty string.
Related
Java AWT controls issue
I'd like to create a calculator using Java AWT library, however I'm having problems putting a label and a textfield on the same row. Also, everything is mixing up. When I run the program, at first it shows 2 labels and 2 textfields on the same row, but if I resize it, the labels, buttons & textfields are one on top of another. Could you please help me? import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class Calculator extends Frame { public static void main(String[] args) { Frame frame= new Frame(); frame.setTitle("Mini Calculator App"); frame.setVisible(true); frame.setSize(300,300); LayoutManager gridBagLayout = new GridBagLayout(); frame.setLayout(gridBagLayout); Label firstNumber = new Label("Add a number"); frame.add(firstNumber); TextField numar1 = new TextField(); frame.add(numar1); Label secondNumber = new Label("Add another number"); frame.add(secondNumber); TextField numar2 = new TextField(); frame.add(numar2); Choice operatie = new Choice(); operatie.add("+"); operatie.add("-"); operatie.add("*"); operatie.add("/"); frame.add(operatie); Button calcul = new Button("Calculate"); frame.add(calcul); Label result = new Label("Result is"); frame.add(result); GridBagConstraints afisare; afisare = new GridBagConstraints(); afisare.gridx = 0; afisare.gridy = 0; frame.add(firstNumber, afisare); afisare = new GridBagConstraints(); afisare.gridx = 0; afisare.gridy = 1; afisare.gridwidth = 10; afisare.gridheight = 10; frame.add(numar1, afisare); afisare = new GridBagConstraints(); afisare.gridx = 1; afisare.gridy = 0; frame.add(secondNumber, afisare); afisare = new GridBagConstraints(); afisare.gridx = 1; afisare.gridy = 1; frame.add(numar2, afisare); afisare = new GridBagConstraints(); afisare.gridx = 2; afisare.gridy = 1; frame.add(operatie, afisare); afisare = new GridBagConstraints(); afisare.gridx = 4; afisare.gridy = 0; frame.add(result, afisare); frame.addWindowListener(new WindowAdapter() { #Override public void windowClosing(WindowEvent e) { System.exit(0); } }); } } enter image description here enter image description here
Creating a new JFrame inside actionPerformed() method , and then how can i perform action with this JFrame's JButton
I'm very new to java.My question is,is it possible to use JButton v,v1 ? Inside this actionPerformed() method ? If it is possible,then how ? Thanks in advance . PlaceOrder.java import javax.swing.*; import java.awt.*; import java.awt.event.*; class PlaceOrder extends JFrame implements ActionListener { JButton confirm,cancel,logOut; JRadioButton rb1,rb2,rb3,rb4,rb5,rb6,rb7,rb8; JTextField r1,r2,r3,r4,r5,r6,r7,r8; JLabel Item,Quantity; Food f[] = new Food[10]; double total = 0; public PlaceOrder() { f[0] = new Food("Chicken Burger",120); f[1] = new Food("Chicken BBQ Burger",150); f[2] = new Food("Chicken BBQ Cheese Burger",170); f[3] = new Food("Beef Burger",130); f[4] = new Food("Beef BBQ Burger",160); f[5] = new Food("Pizza",180); f[6] = new Food("Coffee",80); f[7] = new Food("Soft Drinks(Can)",35); setSize(700,700); setVisible(true); setLayout(null); rb1 = new JRadioButton("Chicken Burger"); rb2 = new JRadioButton("Chicken BBQ Burger"); rb3 = new JRadioButton("Chicken BBQ Cheese Burger"); rb4 = new JRadioButton("Beef Burger"); rb5 = new JRadioButton("Beef BBQ Burger"); rb6 = new JRadioButton("Pizza"); rb7 = new JRadioButton("Coffee"); rb8 = new JRadioButton("Soft Drinks(Can)"); rb1.setBounds(150,100,150,30); add(rb1); rb2.setBounds(150,130,150,30); add(rb2); rb3.setBounds(150,160,150,30); add(rb3); rb4.setBounds(150,190,150,30); add(rb4); rb5.setBounds(150,220,150,30); add(rb5); rb6.setBounds(150,250,150,30); add(rb6); rb7.setBounds(150,280,150,30); add(rb7); rb8.setBounds(150,310,150,30); add(rb8); r1 = new JTextField(); r2 = new JTextField(); r3 = new JTextField(); r4 = new JTextField(); r5 = new JTextField(); r6 = new JTextField(); r7 = new JTextField(); r8 = new JTextField(); Item = new JLabel("Item"); Quantity = new JLabel("Quantity"); Item.setBounds(160,20,100,50); add(Item); Quantity.setBounds(360,20,100,50); add(Quantity); r1.setBounds(350,100,150,20); add(r1); r2.setBounds(350,130,150,20); add(r2); r3.setBounds(350,160,150,20); add(r3); r4.setBounds(350,190,150,20); add(r4); r5.setBounds(350,220,150,20); add(r5); r6.setBounds(350,250,150,20); add(r6); r7.setBounds(350,280,150,20); add(r7); r8.setBounds(350,310,150,20); add(r8); confirm = new JButton("Order Status"); cancel = new JButton("Cancel Order"); logOut = new JButton("LogOut"); confirm.setBounds(150,500,120,30); add(confirm); cancel.setBounds(380,500,120,30); add(cancel); logOut.setBounds(550,50,80,30); add(logOut); confirm.addActionListener(this); cancel.addActionListener(this); logOut.addActionListener(this); } public void actionPerformed(ActionEvent a) { if(a.getSource() == confirm) { JFrame YourOrder = new JFrame(); YourOrder.setSize(700,800); YourOrder.setLayout(null); YourOrder.setVisible(true); JLabel confirmation = new JLabel("Your Order"); confirmation.setBounds(250,30,150,30); YourOrder.add(confirmation); JLabel s[] = new JLabel[3]; s[0] = new JLabel("Item"); s[0].setBounds(100,100,50,30); YourOrder.add(s[0]); s[1] = new JLabel("Quantity"); s[1].setBounds(250,100,50,30); YourOrder.add(s[1]); s[2] = new JLabel("Total"); s[2].setBounds(400,100,50,30); YourOrder.add(s[2]); JLabel l,l1,l2; JLabel netTotal = new JLabel("Net Amount = "); netTotal.setBounds(400,550,100,30); YourOrder.add(netTotal); JButton v,v1; v = new JButton("Change"); v.setBounds(100,600,100,30); YourOrder.add(v); v.addActionListener(this); v1 = new JButton("Confirm Order"); v1.setBounds(400,600,120,30); YourOrder.add(v1); v1.addActionListener(this); if(rb1.isSelected() && r1.getText() != "") { total = total + ((Integer.parseInt(r1.getText()))*(f[0].getFoodPrice())); l = new JLabel(rb1.getText()); l.setBounds(100,150,100,30); YourOrder.add(l); l1 = new JLabel(r1.getText()); l1.setBounds(250,150,100,30); YourOrder.add(l1); l2 = new JLabel(String.valueOf((Integer.parseInt(r1.getText()))*(f[0].getFoodPrice()))); l2.setBounds(400,150,100,30); YourOrder.add(l2); } if(rb2.isSelected() && r2.getText() != "") { total = total + ((Integer.parseInt(r2.getText()))*(f[1].getFoodPrice())); l = new JLabel(rb2.getText()); l.setBounds(100,200,100,30); YourOrder.add(l); l1 = new JLabel(r2.getText()); l1.setBounds(250,200,100,30); YourOrder.add(l1); l2 = new JLabel(String.valueOf((Integer.parseInt(r2.getText()))*(f[1].getFoodPrice()))); l2.setBounds(400,200,100,30); YourOrder.add(l2); } if(rb3.isSelected() && r3.getText() != "") { total = total + ((Integer.parseInt(r3.getText()))*(f[2].getFoodPrice())); l = new JLabel(rb3.getText()); l.setBounds(100,250,100,30); YourOrder.add(l); l1 = new JLabel(r3.getText()); l1.setBounds(250,250,100,30); YourOrder.add(l1); l2 = new JLabel(String.valueOf((Integer.parseInt(r3.getText()))*(f[2].getFoodPrice()))); l2.setBounds(400,250,100,30); YourOrder.add(l2); } if(rb4.isSelected() && r4.getText() != "") { total = total + ((Integer.parseInt(r4.getText()))*(f[3].getFoodPrice())); l = new JLabel(rb4.getText()); l.setBounds(100,300,100,30); YourOrder.add(l); l1 = new JLabel(r4.getText()); l1.setBounds(250,300,100,30); YourOrder.add(l1); l2 = new JLabel(String.valueOf((Integer.parseInt(r4.getText()))*(f[3].getFoodPrice()))); l2.setBounds(400,300,100,30); YourOrder.add(l2); } if(rb5.isSelected() && r5.getText() != "") { total = total + ((Integer.parseInt(r5.getText()))*(f[4].getFoodPrice())); l = new JLabel(rb5.getText()); l.setBounds(100,350,100,30); YourOrder.add(l); l1 = new JLabel(r5.getText()); l1.setBounds(250,350,100,30); YourOrder.add(l1); l2 = new JLabel(String.valueOf((Integer.parseInt(r5.getText()))*(f[4].getFoodPrice()))); l2.setBounds(400,350,100,30); YourOrder.add(l2); } if(rb6.isSelected() && r6.getText() != "") { total = total + ((Integer.parseInt(r6.getText()))*(f[5].getFoodPrice())); l = new JLabel(rb6.getText()); l.setBounds(100,400,100,30); YourOrder.add(l); l1 = new JLabel(r6.getText()); l1.setBounds(250,400,100,30); YourOrder.add(l1); l2 = new JLabel(String.valueOf((Integer.parseInt(r6.getText()))*(f[5].getFoodPrice()))); l2.setBounds(400,400,100,30); YourOrder.add(l2); } if(rb7.isSelected() && r7.getText() != "") { total = total + ((Integer.parseInt(r7.getText()))*(f[6].getFoodPrice())); l = new JLabel(rb7.getText()); l.setBounds(100,450,100,30); YourOrder.add(l); l1 = new JLabel(r7.getText()); l1.setBounds(250,450,100,30); YourOrder.add(l1); l2 = new JLabel(String.valueOf((Integer.parseInt(r7.getText()))*(f[6].getFoodPrice()))); l2.setBounds(400,450,100,30); YourOrder.add(l2); } if(rb8.isSelected() && r8.getText() != "") { total = total + ((Integer.parseInt(r8.getText()))*(f[7].getFoodPrice())); l = new JLabel(rb8.getText()); l.setBounds(100,500,100,30); YourOrder.add(l); l1 = new JLabel(r8.getText()); l1.setBounds(250,500,100,30); YourOrder.add(l1); l2 = new JLabel(String.valueOf((Integer.parseInt(r8.getText()))*(f[7].getFoodPrice()))); l2.setBounds(400,500,100,30); YourOrder.add(l2); } JLabel pay = new JLabel(String.valueOf(total)); pay.setBounds(500,550,100,30); YourOrder.add(pay); if(a.getSource() == v) { YourOrder.setVisible(false); } else if(a.getSource() == v1) { JOptionPane.showMessageDialog(this,"Printing Invoice ..."); } } else if(a.getSource() == cancel) { this.setVisible(false); PlaceOrder o1 = new PlaceOrder(); } else { this.setVisible(false); } } } Food.java class Food { private String foodName; private double foodPrice; public Food(String foodName,double foodPrice) { this.foodName = foodName; this.foodPrice = foodPrice; } public String getFoodName() { return this.foodName; } public double getFoodPrice() { return this.foodPrice; } } These two classes ..
My guess: you want to be able to refer to the local variables in your code image above, v and v1, but being local to the method, their scope or "visibility" is also limited to the method. If so, then get that code out of the actionPerformed and instead into its own class, one that creates a JPanel that is set up as you desire. You can then make v and v1 fields of the class, and allow outside code access to necessary properties via getter methods. If you need more detailed help and less guesses, again please post a viable mcve. If you do this, we can work with and even sometimes help enhance your code. Other issues: avoid null layouts and setBounds since these lead to rigid and hard to enhance GUI's that look bad on most platforms other than your own. Also check out The Use of Multiple JFrames, Good/Bad Practice? Edit That confirm order window should be a modal JDialog and not a JFrame. You want the program to stop and not go forward until the user has dealt with it, which is what a modal dialog will do. Also, I would use JSpinner and not JTextFields to get the quantity information. Why? You must always assume that the user is an idiot, and using a JSpinner you would prevent the user from entering non-numeric or other incorrect information.
Trying to change image when JButton pressed
I am trying to change the Image on the panel when the any of the JButtons are pressed. I have set up an array of images and need it to change to the next image in the array once it has been pressed. Here is my code: public class SimpleGui implements ActionListener { JButton button = new JButton("Very Happy"); JButton buttonTwo = new JButton("Happy"); JButton buttonThree = new JButton("Neutral"); JButton buttonFour = new JButton("Sad"); JButton buttonFive = new JButton("Very Sad"); static int[] ButtonArray = new int[5]; private static String[] imageList = { "res/snow.jpg", "res/test-gm.jpg" }; public int i = 0; public static void main(String[] args) throws FileNotFoundException { SimpleGui gui = new SimpleGui(); gui.go(); File file = new File("out.txt"); FileOutputStream fos = new FileOutputStream(file); PrintStream ps = new PrintStream(fos); System.setOut(ps); ButtonArray[0] = 0; ButtonArray[1] = 0; ButtonArray[2] = 0; ButtonArray[3] = 0; ButtonArray[4] = 0; } public void go() { JFrame frame = new JFrame(); JPanel panel = new JPanel(); panel.setBackground(Color.darkGray); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); button.addActionListener(this); buttonTwo.addActionListener(this); buttonThree.addActionListener(this); buttonFour.addActionListener(this); buttonFive.addActionListener(this); panel.add(button); panel.add(buttonTwo); panel.add(buttonThree); panel.add(buttonFour); panel.add(buttonFive); frame.getContentPane().add(BorderLayout.EAST, panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(650, 600); frame.setVisible(true); ImageIcon image = new ImageIcon(imageList[i]); ImageIcon image1 = new ImageIcon(imageList[i + 1]); JLabel label = new JLabel("", image, JLabel.CENTER); JPanel panel2 = new JPanel(new BorderLayout()); panel2.add(label, BorderLayout.CENTER); panel2.setLayout(new BoxLayout(panel2, BoxLayout.Y_AXIS)); frame.add(panel2, BorderLayout.CENTER); frame.setVisible(true); } public void actionPerformed(ActionEvent event) { if (event.getSource() == button) { ButtonArray[0] = 1; ButtonArray[1] = 0; ButtonArray[2] = 0; ButtonArray[3] = 0; ButtonArray[4] = 0; System.out.println("Very Happy"); } // buttonTwo = (JButton) event.getSource(); if (event.getSource() == buttonTwo) { ButtonArray[0] = 0; ButtonArray[1] = 1; ButtonArray[2] = 0; ButtonArray[3] = 0; ButtonArray[4] = 0; System.out.println("Happy"); } // buttonThree = (JButton) event.getSource(); if (event.getSource() == buttonThree) { ButtonArray[0] = 0; ButtonArray[1] = 0; ButtonArray[2] = 1; ButtonArray[3] = 0; ButtonArray[4] = 0; System.out.println("Neutral"); } // buttonFour = (JButton) event.getSource(); if (event.getSource() == buttonFour) { ButtonArray[0] = 0; ButtonArray[1] = 0; ButtonArray[2] = 0; ButtonArray[3] = 1; ButtonArray[4] = 0; System.out.println("Sad"); } // buttonFive = (JButton) event.getSource(); if (event.getSource() == buttonFive) { ButtonArray[0] = 0; ButtonArray[1] = 0; ButtonArray[2] = 0; ButtonArray[3] = 0; ButtonArray[4] = 1; System.out.println("Very Sad"); } // System.out.println(Arrays.toString(ButtonArray)); // ImageIcon image = (imageList[i]); } }
I don't really see what most parts of you code are supposed to do. So instead, here's a minimal example that should do what you are asking about: One label, and two buttons setting different images to that label. ImageIcon[] images = new ImageIcon[] { new ImageIcon("foo.gif"), new ImageIcon("bar.gif"), new ImageIcon("blub.gif") }; JFrame frame = new JFrame("Test"); frame.getContentPane().setLayout(new FlowLayout()); JLabel label = new JLabel(images[0]); frame.getContentPane().add(label); JButton button1 = new JButton("Image 1"); button1.addActionListener(e -> label.setIcon(images[0])); frame.getContentPane().add(button1); JButton button2 = new JButton("Image 2"); button2.addActionListener(e -> label.setIcon(images[1])); frame.getContentPane().add(button2); frame.pack(); frame.setVisible(true); Note that this is using Lambda functions (Java 8) but you can do the same with one or more "real" ActionListener classes. The important part is that you call label.setIcon(theImage); this part seems to be missing in your code. If instead you want to cycle through a list or array of pictures, you can do like this: AtomicInteger index = new AtomicInteger(0); JButton buttonCycle = new JButton("Cycle"); buttonCycle.addActionListener(e -> label.setIcon(images[index.getAndIncrement() % images.length])); frame.getContentPane().add(buttonCycle); Here, the AtomicInteger is used so I can declare it as a local variable and use it in the lambda. You can just as well use a regular int if you make it a member variable of the surrounding class. private int c = 0; ... buttonCycle.addActionListener(e -> label.setIcon(images[c++ % images.length])); The takeaway is: Create a counter variable, increment it each time the button is called and set the label's icon to the element with that count, module the size of the array.
Random Number won't appear in a JTextField
I have a problem.I created a program that will add two random numbers. I'm trying to put a Math.random() in a JTextField but it won't appear. Here's my code by the way: public class RandomMathGame extends JFrame { public RandomMathGame(){ super("Random Math Game"); int random2; JButton lvl1 = new JButton("LEVEL 1"); JButton lvl2 = new JButton("LEVEL 2"); JButton lvl3 = new JButton("LEVEL 3"); JLabel line1 = new JLabel("Line 1: "); final JTextField jtf1 = new JTextField(10); JLabel line2 = new JLabel("Line 2: "); final JTextField jtf2 = new JTextField(10); JLabel result = new JLabel("Result: "); final JTextField jtf3 = new JTextField(10); JButton ans = new JButton("Answer"); JLabel score = new JLabel("Score: "); JTextField jtf4 = new JTextField(3); JLabel itm = new JLabel("Number of Items: "); JTextField items = new JTextField(3); FlowLayout flo = new FlowLayout(); setLayout(flo); add(lvl1); add(lvl2); add(lvl3); add(line1); add(jtf1); add(line2); add(jtf2); add(result); add(jtf3); add(ans); add(score); add(jtf4); add(itm); add(items); setSize(140,400); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); lvl1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ int i, j = 10; int i1 = Integer.valueOf(jtf1.getText()); int i2 = Integer.valueOf(jtf2.getText()); int i3 = i1 + i2; final int random1 = (int)(Math.random() * 10 + 1); for (i = 0; i <= j + 1; i++){ try{ jtf1.setText(String.valueOf(random1)); jtf2.setText(String.valueOf(random1)); jtf3.setText(String.valueOf(i3)); }catch(Exception ex){ ex.printStackTrace(); } } } }); } Never mind the lvl2 and lvl3 because it's the same in lvl1. And also, I want to loop them 10 times. I'm having difficulties on putting up those codes. Can someone help me? Thanks for your help. :)
Updating text fields in a loop won't produce the animated display that you likely want; only the last update will be seen. Instead, use a javax.swing.Timer to periodically update the fields. Related examples may be found here, here and here.
Listbox in Java
I was trying to build the Font window of Notepad using Java using the code shown below. But, I'm facing a problem in setting the size of the text as specified inside listbox. I'm trying to get the respective size corresponding to the index of the selected item but couldn't find any such method. f = new Frame("Font"); f.setLayout(new GridLayout(3, 3)); b1 = new Button("OK"); l1 = new Label("Font :"); l2 = new Label("Size :"); l3 = new Label("Font Style :"); lb1 = new List(10, false); lb2 = new List(10, false); lb3 = new List(5, false); String [] s = {"Times New Roman", "Arial", "Verdana", "Trebuchet MS", "Papyrus","Monotype Corsiva","Microsoft Sans Serif", "Courier", "Courier New"}; for(int i = 0; i < s.length; i++) { lb1.add(s[i]); } for(int i = 8; i <=72; i += 2) { lb2.add(i + ""); } String [] s1 = {"BOLD", "ITALIC", "PLAIN"}; for(int i = 0; i < s1.length; i++) { lb3.add(s1[i]); } f.add(l1); f.add(l2); f.add(l3); f.add(lb1); f.add(lb2); f.add(lb3); f.add(b1); b1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae) { if(lb3.isIndexSelected(0)) fo = new Font(lb1.getSelectedItem(), Font.BOLD, **lb2.getSelectedIndex**()); else if(lb3.isIndexSelected(1)) fo = new Font(lb1.getSelectedItem(), Font.ITALIC, lb2.getSelectedIndex()); else fo = new Font(lb1.getSelectedItem(), Font.PLAIN, lb2.getSelectedIndex()); ta1.setFont(fo); MyFrame15.f.dispose(); } }); f.setSize(300, 300); Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); int x = (int)((d.getWidth() / 2) - 200); int y = (int)((d.getHeight() / 2) - 200); f.setLocation(x, y); f.setVisible(true); }
To get the size as required by user we can use: lb2.getSelectedItem(); which returns a String but the third argument of Font constructor requires an integer.Therefore, we use parseInt() method of Integer class to convert the string received to integer.The code is as follows: Font(lb1.getSelectedItem(), Font.BOLD, Integer.parseInt(lb2.getSelectedItem()));
I would suggest you use Swing for this. You can start with the Swing tutorial on Text Component Features which already contains a working example that does what you want.