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.
I've written a so called 'error less' code but I'm facing certain problems whilst using the application.
Here's my code:
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Login implements ActionListener {
Connection conn1 = null;
Statement stmt1 = null;
Connection conn2 = null;
Statement stmt2 = null;
Connection conn3 = null;
Statement stmt3 = null;
JFrame frame = new JFrame("Login Window");
JPanel startPanel = new JPanel();
JPanel adminPanel = new JPanel();
JPanel engineerPanel = new JPanel();
JButton adminLogin = new JButton("Admin Login");
JButton engineerLogin = new JButton("Engineer Login");
JTextField adminUsername = new JTextField();
JPasswordField adminPassword = new JPasswordField();
JButton adminLog = new JButton("Login");
JButton adminBack = new JButton("Go Back");
JComboBox engineerUsername = new JComboBox();
JPasswordField engineerPassword = new JPasswordField();
JButton engineerLog = new JButton("Login");
JButton engineerBack = new JButton("Go Back");
public Login(){
//Establishing connection with database
conn1 = sqliteConnection.dbConnector();
frame.setLayout(new GridLayout(1, 1));
/*
Setting up the startPanel
*/
startPanel.setLayout(new GridLayout(3, 3, 15, 15));
// Row 1
startPanel.add(new JLabel(" "));
JLabel loginType = new JLabel(" SELECT LOGIN TYPE");
loginType.setFont(new Font("Tahoma", Font.BOLD, 12));
startPanel.add(loginType);
startPanel.add(new JLabel(" "));
// Row 2
startPanel.add(new JLabel(" "));
startPanel.add(adminLogin);
startPanel.add(new JLabel(" "));
// Row 3
startPanel.add(new JLabel(" "));
startPanel.add(engineerLogin);
startPanel.add(new JLabel(" "));
adminLogin.addActionListener(this);
engineerLogin.addActionListener(this);
/*
Setting up adminPanel
*/
adminPanel.setLayout(new GridLayout(4, 2, 15, 15));
// Row 1
adminPanel.add(new JLabel("Admin Login"));
adminPanel.add(new JLabel(" "));
// Row 2
adminPanel.add(new JLabel("Username"));
adminPanel.add(adminUsername);
// Row 3
adminPanel.add(new JLabel("Password"));
adminPanel.add(adminPassword);
// Row 4
adminPanel.add(adminLog);
adminPanel.add(adminBack);
adminLog.addActionListener(this);
adminBack.addActionListener(this);
//Initial Visibility False
adminPanel.setVisible(false);
/*
Setting up engineerPanel
*/
engineerPanel.setLayout(new GridLayout(4, 2, 15, 15));
// Row 1
engineerPanel.add(new JLabel("Engineer Login"));
engineerPanel.add(new JLabel(" "));
// Row 2
try{
Class.forName("org.sqlite.JDBC");
conn1.setAutoCommit(false);
stmt1 = conn1.createStatement();
ResultSet rs1 = stmt1.executeQuery( "SELECT * FROM EngineerData;" );
List<String> engineerNamesList = new ArrayList<String>();
while ( rs1.next() ){
String name = rs1.getString("Name");
engineerNamesList.add(name);
}
// Converting array list to array
String[] engineerNames = new String[engineerNamesList.size()];
engineerNamesList.toArray(engineerNames);
// Adding array into combo-box
for (String en : engineerNames){
engineerUsername.addItem(en);
}
rs1.close();
stmt1.close();
conn1.close();
}
catch ( Exception e1 ) {
JOptionPane.showMessageDialog(null, e1);
}
engineerPanel.add(new JLabel("Engineer Name"));
engineerPanel.add(engineerUsername);
// Row 3
engineerPanel.add(new JLabel("Password"));
engineerPanel.add(engineerPassword);
// Row 4
engineerPanel.add(engineerLog);
engineerPanel.add(engineerBack);
engineerLog.addActionListener(this);
engineerBack.addActionListener(this);
//Initial Visibility False
engineerPanel.setVisible(false);
frame.setSize(500, 200);
frame.setResizable(false);
frame.add(startPanel);
frame.setVisible(true);
}
//Method to convert integar array list to integar array
public int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
for (int i=0; i < ret.length; i++)
{
ret[i] = integers.get(i).intValue();
}
return ret;
}
//Admin login method
public void adminLogin(){
String adminUser = adminUsername.getText();
String adminPass = adminPassword.getText();
String adminUserDB = null;
String adminPassDB = null;
conn2 = sqliteConnection.dbConnector();
try{
Class.forName("org.sqlite.JDBC");
conn2.setAutoCommit(false);
stmt2 = conn2.createStatement();
ResultSet rs2 = stmt2.executeQuery( "SELECT * FROM AdminData;" );
adminUserDB = rs2.getString("Username");
adminPassDB = rs2.getString("Password");
conn2.close();
stmt2.close();
rs2.close();
}
catch (Exception e2){
}
if (adminUser.equals(adminUserDB) && adminPass.equals(adminPassDB)){
AdminClass ac = new AdminClass();
frame.dispose();
}
else if (adminUser.equals(adminUserDB) && adminPass != adminPassDB){
JOptionPane.showMessageDialog(null, "Incorrect Password.\nPlease enter again.");
}
else if (adminUser != adminUserDB && adminPass.equals(adminPassDB)){
JOptionPane.showMessageDialog(null, "Incorrect Username.\nPlease enter again.");
}
else if (adminUser != adminUserDB && adminPass != adminPassDB){
JOptionPane.showMessageDialog(null, "Incorrect Username and Password.\nPlease enter again.");
}
}
//Engineer login method
public void engineerLogin(){
String engineerUser = engineerUsername.getSelectedItem().toString();
String engineerPass = engineerPassword.getText();
List<String> engineerNamesList = new ArrayList<String>();
List<String> engineerPasswordsList = new ArrayList<String>();
ArrayList<Integer> uniqueIDList = new ArrayList<Integer>();
conn3 = sqliteConnection.dbConnector();
try{
Class.forName("org.sqlite.JDBC");
conn3.setAutoCommit(false);
stmt3 = conn3.createStatement();
ResultSet rs3 = stmt3.executeQuery( "SELECT * FROM EngineerData;" );
while ( rs3.next() ){
int uniqueId = rs3.getInt("UniqueId");
String engineerUserDB = rs3.getString("Name");
String engineerPassDB = rs3.getString("Password");
//Adding data from database to variables that exist in our code
engineerNamesList.add(engineerUserDB);
engineerPasswordsList.add(engineerPassDB);
uniqueIDList.add(uniqueId);
}
conn3.close();
stmt3.close();
rs3.close();
}
catch (Exception e3){
}
// Creating usable arrays from array lists
String[] engineerNames = new String[engineerNamesList.size()];
engineerNamesList.toArray(engineerNames);
String[] engineerPasswords = new String[engineerPasswordsList.size()];
engineerPasswordsList.toArray(engineerPasswords);
int[] uniqueIDs = convertIntegers(uniqueIDList);
for (int i = 0; i < engineerNames.length; i++){
boolean condition = (engineerUser.equals(engineerNames[i]) && engineerPass.equals(engineerPasswords[i]));
if (condition){
frame.dispose();
EngineerPanel ep = new EngineerPanel();
//This ID is the identifier of the engineer
//This will be used to generate data only for his particular project
ep.setUniqueID(uniqueIDs[i]);
break;
}
else if (i>= 1 && condition != true){
JOptionPane.showMessageDialog(null, "Incorrect Password");
continue;
}
}
}
public void actionPerformed(ActionEvent e){
if (e.getSource() == adminLogin){
startPanel.setVisible(false);
frame.remove(startPanel);
frame.add(adminPanel);
adminPanel.setVisible(true);
}
if (e.getSource() == engineerLogin){
startPanel.setVisible(false);
frame.remove(startPanel);
frame.add(engineerPanel);
engineerPanel.setVisible(true);
}
if (e.getSource() == adminBack){
adminUsername.setText(null);
adminPassword.setText(null);
adminPanel.setVisible(false);
frame.remove(adminPanel);
frame.add(startPanel);
startPanel.setVisible(true);
}
if (e.getSource() == engineerBack){
engineerPassword.setText(null);
engineerPanel.setVisible(false);
frame.remove(engineerPanel);
frame.add(startPanel);
startPanel.setVisible(true);
}
if (e.getSource() == adminLog){
adminLogin();
}
if (e.getSource() == engineerLog){
engineerLogin();
}
}
}
So here as you can see I'm using sqlite data base. Authorisation for the engineer only works for the first engineer but now for all of them. Even if the data is right, it shows that user data is incorrect. The JOptionPane keeps on popping up even though after I keep clicking ok. After several clicks it just takes the use to the next JFrame although it said password was incorrect.
Please help!
Your logic is flawed, if I understand your problem. You do:
for (int i = 0; i < engineerNames.length; i++){
boolean condition = ...
if (condition){
// OK
} else {
// show error
}
}
So you show the error as soon as you found a mismatch between the entered information and a database row. So everything is fine for the first object, since the first row will match. But for the second object, it will show the error, since you've entered the data for the second row, and the first row will not match. And then you "continue" so you never get to the second database row.
Your logic should be:
boolean ok=false;
for (int i = 0; i < engineerNames.length; i++){
boolean condition = ...
ok |= condition;
}
if (ok){
// OK
} else {
// show error
}
The ok |= condition is a OR operator: you want to see if any row matches. Of course if ok is true, you can have a continue to avoid looking at others matches.
But really why don't you use a query with the provided name and password?
SELECT * FROM EngineerData where Name=? and Password=?
And see if you get any result.
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.
I'm preparing a simple system as my assignment, And I'm facing a problem where I dont know how to getText the value of String. I know how to do it with integer, but not with string.
I use Integer.parseInt(t2.getText()); in my code if i want to get an integer value
I have added my code into this.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class tollRate extends JFrame implements ActionListener {
JLabel L1 = new JLabel("Please insert your origin (in capital letter)");
JTextField t1 = new JTextField(20);
JLabel L2 = new JLabel("Please insert your destination (in capital letter)");
JTextField t2 = new JTextField(20);
JLabel L3 = new JLabel("Your vehicle class");
JTextField t3 = new JTextField(1);
JButton b1 = new JButton("Calculate");
JButton b2 = new JButton("Exit");
JLabel L4 = new JLabel("Class 0 : Motorcycles, bicycles, or vehicles with "
+ "2 or less wheels" + "\nClass 1 : Vehicles wit 2 axles and 3 "
+ "or 4 wheels excluding taxis" + "\nClass 2 : Vehicles with 2 "
+ "axles and 5 or 6 wheels excluding busses" + "\n Class 3 : "
+ "Vehicles with 3 or more axles" + "\nClass 4 : Taxis"
+ "\nClass 5 : Buses");
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
JPanel p4 = new JPanel();
JPanel p5 = new JPanel();
String i, j, k;
tollRate() {
JFrame a = new JFrame();
setTitle("Highway Toll Rates System");
setSize(600, 400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(5, 2));
p1.setLayout(new GridLayout(1, 2));
p1.add(L1);
p1.add(t1);
p2.setLayout(new GridLayout(1, 2));
p2.add(L2);
p2.add(t2);
p3.setLayout(new GridLayout(1, 2));
p3.add(L3);
p3.add(t3);
p4.setLayout(new FlowLayout());
p4.add(b1);
p4.add(b2);
p5.setLayout(new FlowLayout());
p5.add(L4);
add(p1);
add(p2);
add(p3);
add(p4);
add(p5);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent a) {
Object source = a.getSource();
if (source == b2) {
this.dispose();
} else if (source == b1) {
i = Integer.parseInt(t1.getText());
j = Integer.parseInt(t2.getText());
k = Integer.parseInt(t3.getText());
}
}
public static void main(String[] args) {
tollRate a = new tollRate();
}
}
First of all String i, j, k;
i = Integer.parseInt(t1.getText());
j = Integer.parseInt(t2.getText());
k = Integer.parseInt(t3.getText());
This is wrong. You are assigning String for int. Correct them first. and if you want int values it is better to use
int i, j, k; and use trim() to avoid additional spaces.
i = Integer.parseInt(t1.getText().trim());
j = Integer.parseInt(t2.getText().trim());
k = Integer.parseInt(t3.getText().trim());
In your case use as follows
i = t1.getText();
j = t2.getText();
k = t3.getText();
to assign a string to a string all you need to do is
i = t1.getText();
j = t2.getText();
k = t3.getText();
as you have created them as strings already