Java AWT controls issue - java

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

Related

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.

JRadioButtons before every line

I have this program that reads questions with multiple choice answers from a text file and then displays a random set of them in a JOptionPane (very question in a new Pane). In my text file the questions and the 4 options of answers are all in one line and then I divide them into new lines. Now I want to try to add JRadioButtons before every single answer. Is there someone who can help me. Thank you very much in advance. Here is my code:
Random random = new Random();
for (int i = 0; i < newRanQues; i++) {
int randIndex = random.nextInt(32) + 0;
String randomQuestion = questions.get(randIndex);
randomQuestions.add(randomQuestion);
String different = randomQuestion.replaceAll(";", "\n");
{
JOptionPane.showMessageDialog(null, different, "Question", JOptionPane.INFORMATION_MESSAGE);
JRadioButton answerA = new JRadioButton("A) " + answer[0]);
JRadioButton answerB = new JRadioButton("B) " + answer[1]);
JRadioButton answerC = new JRadioButton("C) " + answer[2]);
JRadioButton answerD = new JRadioButton("D) " + answer[3]);
ButtonGroup group = new ButtonGroup();
group.add(optionA);
group.add(optionB);
group.add(optionC);
group.add(optionD);
return;
}
This should do it:
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class RadioButtonExample {
public static void main(String[] args) {
init();
}
private static void init() {
// create the jframe
JFrame jframe = new JFrame("Question");
// create the answers
String[] answer = { "red", "green", "yellow", "blue, no, red, no... arrrrrg" };
// create the radio buttons
JRadioButton answerA = new JRadioButton("A) " + answer[0]);
JRadioButton answerB = new JRadioButton("B) " + answer[1]);
JRadioButton answerC = new JRadioButton("C) " + answer[2]);
JRadioButton answerD = new JRadioButton("D) " + answer[3]);
// create the button group
ButtonGroup group = new ButtonGroup();
group.add(answerA);
group.add(answerB);
group.add(answerC);
group.add(answerD);
// add the question to the jframe
jframe.add(new JLabel("What is your favorite colour?"), BorderLayout.NORTH);
// create gridbag layout and constraints
GridBagLayout gbl = new GridBagLayout();
// create the panel using the gbl
JPanel pan = new JPanel(gbl);
// create the constraints
GridBagConstraints cons = new GridBagConstraints();
cons.gridwidth = 1;
cons.fill = GridBagConstraints.HORIZONTAL;
// answer 1
cons.gridx = 0;
cons.gridy = 1;
pan.add(answerA, cons);
// answer 1
cons.gridx = 0;
cons.gridy = 2;
pan.add(answerB, cons);
// answer 1
cons.gridx = 0;
cons.gridy = 3;
pan.add(answerC, cons);
// answer 1
cons.gridx = 0;
cons.gridy = 4;
pan.add(answerD, cons);
// add the panel to the jframe
jframe.add(pan, BorderLayout.CENTER);
// show the jframe
jframe.setSize(400, 400);
jframe.setVisible(true);
}
}

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.

JComboBox[] loop to show on JApplet not working

public class NewAccountApplet extends JApplet implements ActionListener{
JPanel jp1, jp2, jp3, jp4, jp5, jp6;
GridLayout productLO = new GridLayout(10,4,10,10);
int qty = 5;
JComboBox<Object>[] selectQty;
if (e.getActionCommand().equals("Login")) {
if (id.equals(checkID) && pw.equals(checkPW)) {
JOptionPane.showMessageDialog(null, "Authenticated");
JPanel content = (JPanel)getContentPane();
GridBagConstraints firstCol = new GridBagConstraints();
firstCol.weightx = 1.0;
firstCol.anchor = GridBagConstraints.WEST;
firstCol.insets = new Insets(5, 20, 5, 5);
GridBagConstraints lastCol = new GridBagConstraints();
lastCol.gridwidth = GridBagConstraints.REMAINDER;
lastCol.weightx = 1.0;
lastCol.fill = GridBagConstraints.HORIZONTAL;
lastCol.insets = new Insets(5, 5, 5, 20);
selectQty = new JComboBox[qty];
jp1.setVisible(false);
jp2.setVisible(false);
jp3.setVisible(false);
jp4.setVisible(true);
jp5.setVisible(true);
jp6.setVisible(true);
String[] itemText = {"1", "2", "3", "4", "5"};
JLabel[] items = new JLabel[6];
JLabel purchasePage = new JLabel("Items for Purchase");
jp4.add(purchasePage);
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
content.add(jp4);
jp4 = new JPanel();
jp5 = new JPanel(new GridBagLayout()); //set jp5 as a new jpanel with gridbaglayout
jp6 = new JPanel();
for(int i=0; (i<items.length); i++) {
items[i] = new JLabel(); //adds items[i] as JLabel
items[i].setText(itemText[i]); //sets text of items as itemText[]
jp5.add(items[i], firstCol); //adds items to firstcol of jp5
selectQty[i] = new JComboBox<Object>(); //JComboBox selectqty[i]
selectQty[i].setPreferredSize(new Dimension(300, 20)); //sets the size
jp5.add(selectQty[i], lastCol); //sadsdasd
}
}
else JOptionPane.showMessageDialog(null, "Wrong account information");}
I have some questions regarding adding a JComboBox into a loop to display on my JApplet.
the for loop on the bottom adds my JComboBox (selectQty) to the screen. But I get an error message on eclipse where i coded as: items[i].setText(itemText[i]);.
It shows up my JPanel jp4 correctly. but the JPanel jp5 is not showing up.. I wonder what is wrong...
So to summarize, the code compiles (with other codes that are not on here), but japplet only shows jp4 jpanel, and error occrs on line: items[i].setText(itemText[i]);.
itemText has 5 elements {"1", "2", "3", "4", "5"} but JLabel[] items = new JLabel[6] items has 6.
You appear to be re-creating jp5 but neither removing the old instance or adding the new instance...
// This suggests that jp5 has already been created
jp5.setVisible(true);
//...
// But you create a new instance here
jp5 = new JPanel(new GridBagLayout());
// Then add stuff to it...
Try using jp5.removeAll() instead of jp5 = new JPanel(new GridBagLayout());
The likely cause of your error is probably IndexOutOfBoundsException caused by the fact the itemText and items have different numbers of elements
String[] itemText = {"1", "2", "3", "4", "5"};
JLabel[] items = new JLabel[6];
//...
for(int i=0; (i<items.length); i++) {
items[i] = new JLabel(); //adds items[i] as JLabel
// Error here on the last element...
items[i].setText(itemText[i]); //sets text of items as itemText[]
Instead, consider using something like...
String[] itemText = {"1", "2", "3", "4", "5"};
JLabel[] items = new JLabel[itemText.length];
And remember, magic numbers are a bad idea
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.*;
public class NewAccountApplet extends JApplet implements ActionListener{
/**
*
*/
private static final long serialVersionUID = 1L;
JLabel titlePage;
JLabel[] txt;
JTextField[] jtf;
JButton accept, decline;
JPanel jp1, jp2, jp3, jp4, jp5, jp6;
String[] accountlist = {"Select Account Type.", "Customer", "Admin"};
JComboBox<Object> textAlignment = new JComboBox<Object>(accountlist);
GridLayout productLO = new GridLayout(10,4,10,10);
int qty = 5;
JComboBox<Object>[] selectQty;
public void init(){
setSize(400,400);
JPanel content = (JPanel)getContentPane();
GridBagConstraints firstCol = new GridBagConstraints();
firstCol.weightx = 1.0;
firstCol.anchor = GridBagConstraints.WEST;
firstCol.insets = new Insets(5, 20, 5, 5);
GridBagConstraints lastCol = new GridBagConstraints();
lastCol.gridwidth = GridBagConstraints.REMAINDER;
lastCol.weightx = 1.0;
lastCol.fill = GridBagConstraints.HORIZONTAL;
lastCol.insets = new Insets(5, 5, 5, 20);
String[] labeltxt = {"Name","Account ID","Password","E-Mail","Phone","Address","","","Account Type"};
titlePage = new JLabel("Create New Account");
txt = new JLabel[9];
jtf = new JTextField[9];
accept = new JButton("Create");
decline = new JButton("Decline");
jp1 = new JPanel();
jp2 = new JPanel(new GridBagLayout());
jp3 = new JPanel();
jp4 = new JPanel();
jp5 = new JPanel();
jp6 = new JPanel();
for(int i=0; (i<9); i++) {
txt[i] = new JLabel();
txt[i].setText(labeltxt[i]);
jp2.add(txt[i], firstCol);
jtf[i] = new JTextField();
jtf[i].setPreferredSize(new Dimension(300, 20));
jp2.add(jtf[i], lastCol);
}
jp1.add(titlePage);
jp3.add(accept);
jp3.add(decline);
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
content.add(jp1);
content.add(jp2);
content.add(jp3);
String id = this.jtf[1].getText();
String pw = this.jtf[2].getText();
jtf[6].setText(id);
jtf[7].setText(pw);
jtf[6].setVisible(false);
jtf[7].setVisible(false);
jtf[8].setVisible(false);
jp2.add(textAlignment, lastCol);
decline.addActionListener(this);
accept.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
String id = jtf[1].getText();
String pw = jtf[2].getText();
String checkID = jtf[6].getText();
String checkPW = jtf[7].getText();
String accountType = "";
String correctType = "Customer";
String chosenType = (String) textAlignment.getSelectedItem();
JPasswordField pField = new JPasswordField(10);
JPanel pPanel = new JPanel();
pPanel.add(new JLabel("Please Enter Password: "));
pPanel.add(pField);
if (e.getActionCommand().equals("Create") && (chosenType.equals("Customer"))){
JOptionPane.showMessageDialog(null, "Thank you for Joining!");
id = jtf[1].getText();
pw = jtf[2].getText();
titlePage.setText("Welcome to Final Sales!");
accept.setText("Login");
decline.setText("Cancel");
txt[6].setText("UserName");
txt[7].setText("Password");
jtf[0].setText("");
jtf[3].setText("");
jtf[4].setText("");
jtf[5].setText("");
txt[0].setVisible(false);
txt[1].setVisible(false);
txt[2].setVisible(false);
txt[3].setVisible(false);
txt[4].setVisible(false);
txt[5].setVisible(false);
textAlignment.setVisible(false);
txt[8].setVisible(false);
jtf[0].setVisible(false);
jtf[1].setVisible(false);
jtf[2].setVisible(false);
jtf[3].setVisible(false);
jtf[4].setVisible(false);
jtf[5].setVisible(false);
jtf[6].setVisible(true);
jtf[7].setVisible(true);
}
if (e.getActionCommand().equals("Create") && (chosenType.equals("Admin"))) {
JOptionPane.showMessageDialog(null, pPanel);
JOptionPane.showMessageDialog(null, "Wrong Admin Password");
}
if (e.getActionCommand().equals("Create") && (chosenType.equals("Select Account Type."))) {
JOptionPane.showMessageDialog(null, "You have selected wrong account type.");
}
if (e.getActionCommand().equals("Decline"))
System.exit(0);
if (e.getActionCommand().equals("Login")) {
if (id.equals(checkID) && pw.equals(checkPW)) {
JOptionPane.showMessageDialog(null, "Authenticated");
JPanel content = (JPanel)getContentPane();
GridBagConstraints firstCol = new GridBagConstraints();
firstCol.weightx = 1.0;
firstCol.anchor = GridBagConstraints.WEST;
firstCol.insets = new Insets(5, 20, 5, 5);
GridBagConstraints lastCol = new GridBagConstraints();
lastCol.gridwidth = GridBagConstraints.REMAINDER;
lastCol.weightx = 1.0;
lastCol.fill = GridBagConstraints.HORIZONTAL;
lastCol.insets = new Insets(5, 5, 5, 20);
selectQty = new JComboBox[qty];
jp1.setVisible(false);
jp2.setVisible(false);
jp3.setVisible(false);
jp4.setVisible(true);
jp5.setVisible(true);
jp6.setVisible(true);
String[] itemText = {"White Snapback", "Silver Necklace", "Black T Shirt", "", "5"};
JLabel[] items = new JLabel[5];
JLabel purchasePage = new JLabel("Items for Purchase");
jp4.add(purchasePage);
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
content.add(jp4);
jp4 = new JPanel();
jp5.setLayout(new GridBagLayout());
jp6 = new JPanel();
for(int i=0; (i<items.length); i++) {
items[i] = new JLabel();
items[i].setText(itemText[i]);
jp5.add(items[i], firstCol);
selectQty[i] = new JComboBox<Object>();
selectQty[i].setPreferredSize(new Dimension(300, 20));
jp5.add(selectQty[i], lastCol);
}
}
else JOptionPane.showMessageDialog(null, "Wrong account information");}
if (e.getActionCommand().equals("Cancel")) {
System.exit(0);}
}
}

java.lang.numberformatexception empty string java awt

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.

Categories