For class I'm supposed to be creating an application that first lets you choose which value you'd like to calculate, then asks to enter the appropriate info. Then when you click "calculate", it SHOULD display the answer. For some reason my JLabel that should be displaying the answer isn't showing up. I've been searching for a solution, but every thing I do, nothing appears after you click "calculate". I am a novice, please help :(
package decay.application;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DecayApplication implements ActionListener {
JFrame frame;
JPanel content;
JLabel prompt1, prompt2, prompt3, prompt4, displayFinal, displayIntitial, displayConstant, choose;
JTextField enterFinal, enterInitial, enterConstant, enterElapsed;
JButton finButton, inButton, conButton, calculate1, calculate2, calculate3;
public DecayApplication(){
frame = new JFrame("Decay Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
content = new JPanel();
content.setLayout(new GridLayout(0, 2, 10, 5));
content.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
choose = new JLabel("Which would you like to calculate?");
content.add(choose);
finButton = new JButton("Final Amount");
finButton.setActionCommand("finalAmount");
finButton.addActionListener(this);
content.add(finButton);
inButton = new JButton("Initial Amount");
inButton.setActionCommand("initialAmount");
inButton.addActionListener(this);
content.add(inButton);
conButton = new JButton("Constant");
conButton.setActionCommand("constant");
conButton.addActionListener(this);
content.add(conButton);
frame.setContentPane(content);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args){new DecayApplication();}
public void actionPerformed(ActionEvent event) {
String clicked1 = event.getActionCommand();
String clicked2 = event.getActionCommand();
if (clicked1.equals("finalAmount")) {
prompt1 = new JLabel("Enter the initial amount:");
content.add(prompt1);
enterInitial = new JTextField(10);
content.add(enterInitial);
prompt2 = new JLabel("What's the constant?:");
content.add(prompt2);
enterConstant = new JTextField(10);
content.add(enterConstant);
prompt3 = new JLabel("How many years have elapsed?:");
content.add(prompt3);
enterElapsed = new JTextField(10);
content.add(enterElapsed);
calculate1 = new JButton("Calculate");
calculate1.setActionCommand("Calculate");
calculate1.addActionListener(this);
content.add(calculate1);
displayFinal = new JLabel(" ");
displayFinal.setForeground(Color.red);
content.add(displayFinal);
frame.pack();
if (clicked2.equals("Calculate")){
double finalAmount;
String e1 = enterInitial.getText();
String e2 = enterConstant.getText();
String e3 = enterElapsed.getText();
finalAmount = (Double.parseDouble(e1) + 2.0);
displayFinal.setText(Double.toString(finalAmount));
}
}
}
private static void runGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
DecayApplication decay = new DecayApplication();
}
}
Here's your method actionPerformed:
public void actionPerformed(ActionEvent event) {
String clicked1 = event.getActionCommand();
String clicked2 = event.getActionCommand();
if (clicked1.equals("finalAmount")) {
prompt1 = new JLabel("Enter the initial amount:");
content.add(prompt1);
enterInitial = new JTextField(10);
content.add(enterInitial);
prompt2 = new JLabel("What's the constant?:");
content.add(prompt2);
enterConstant = new JTextField(10);
content.add(enterConstant);
prompt3 = new JLabel("How many years have elapsed?:");
content.add(prompt3);
enterElapsed = new JTextField(10);
content.add(enterElapsed);
calculate1 = new JButton("Calculate");
calculate1.setActionCommand("Calculate");
calculate1.addActionListener(this);
content.add(calculate1);
displayFinal = new JLabel(" ");
displayFinal.setForeground(Color.red);
content.add(displayFinal);
frame.pack();
//here should the if-loop end, because here is the end of instructions which should be called after clicking on the button
}
//and here the second if-loop
if (clicked2.equals("Calculate")){
double finalAmount;
String e1 = enterInitial.getText();
String e2 = enterConstant.getText();
String e3 = enterElapsed.getText();
finalAmount = (Double.parseDouble(e1) + 2.0);
displayFinal.setText(Double.toString(finalAmount));
}
Related
I have a register button where when i press register it should write the values to details.txt that was typed in the textfield. When i register for the first time it works but if the file contains some values it will freeze if i try to register the second time. Anyone can help to debug this pls?
Main Class
package assignment;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Assignment
{
JFrame mainFrame;
JPanel framePanel,leftPnl,topPnl,btmPnl;
JLabel welcomeLabel,studId,passwd;
JTextField studField,passField;
JButton logBtn,signBtn;
Color btnClr,btnTxtClr,backgroundClr,lblClr;
Font mainFont,labelFont;
public void mainPage()
{
mainFrame = new JFrame("CGPA Calculator");
framePanel = new JPanel();
//-------------------Creating Components/Setting Fonts/Color----------------
-------------------------------------------
//Color
btnClr = new Color(0, 179, 60);
btnTxtClr = new Color(255,255,255);
backgroundClr = new Color(26, 26, 26);
lblClr = new Color(255,255,255);
//Fonts
mainFont = new Font("Verdana",Font.PLAIN,40);
labelFont = new Font("Verdana",Font.PLAIN,20);
//Button
logBtn = new JButton("<html><font face=\"Verdana\">Login</font></html>");//Source from:https://stackoverflow.com/questions/21046164/jbutton-text-with-different-font-family-in-different-words
logBtn.setFocusPainted(false);
logBtn.setBackground(btnClr);
logBtn.setForeground(btnTxtClr);
signBtn = new JButton("<html><font face=\"Verdana\">Register</font></html>");
signBtn.setFocusPainted(false);
signBtn.setBackground(btnClr);
signBtn.setForeground(btnTxtClr);
//Label
welcomeLabel = new JLabel("CGPA Calculator");
welcomeLabel.setForeground(lblClr);
studId = new JLabel("Student ID :");
studId.setForeground(lblClr);
passwd = new JLabel("Password :");
passwd.setForeground(lblClr);
//TextField
studField = new JTextField(8);
studField.setBorder(javax.swing.BorderFactory.createEmptyBorder());//Sourced From:https://stackoverflow.com/questions/2281937/swing-jtextfield-how-to-remove-the-border
passField = new JTextField(8);
passField.setBorder(BorderFactory.createEmptyBorder());
//Adding Fonts to Components
welcomeLabel.setFont(mainFont);
studId.setFont(labelFont);
passwd.setFont(labelFont);
//Panel
leftPnl = new JPanel();
topPnl = new JPanel();
btmPnl = new JPanel();
//----------------------Adding of panels/layout/components--------------------------------------------------------
//Seting up layouts to panel
leftPnl.setLayout(new FlowLayout());
btmPnl.setLayout(new BoxLayout(btmPnl,BoxLayout.X_AXIS));
//TOPPANEL(Adjustments)
topPnl.setBackground(backgroundClr);
topPnl.add(welcomeLabel);
topPnl.add(Box.createRigidArea(new Dimension(0,150)));
//LEFTPANEL(Adjustements)
leftPnl.setBackground(backgroundClr);
leftPnl.add(Box.createRigidArea(new Dimension(0,70)));
leftPnl.add(studId);
leftPnl.add(studField);
leftPnl.add(passwd);
leftPnl.add(passField);
//BOTTOMPANEL
btmPnl.setBackground(backgroundClr);
btmPnl.add(Box.createRigidArea(new Dimension(130,0)));
btmPnl.add(logBtn);
btmPnl.add(Box.createRigidArea(new Dimension(40,0)));
btmPnl.add(signBtn);
btmPnl.add(Box.createRigidArea(new Dimension(200,200)));
//Action Listeners(lambda expression)
signBtn.addActionListener((ActionEvent e) -> {
SignUpPage sign = new SignUpPage();
sign.SecondPage();
sign.getFrame().setVisible(true);
//mainFrame.setVisible(false);
});
mainFrame.getContentPane().setBackground(backgroundClr);
mainFrame.add(topPnl,BorderLayout.NORTH);
mainFrame.add(leftPnl,BorderLayout.WEST);
mainFrame.add(btmPnl,BorderLayout.SOUTH);
mainFrame.setVisible(true);
mainFrame.setSize(450,450);
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
Assignment display = new Assignment();
display.mainPage();
new SignUpPage();
}
}
register class
package assignment;
import javax.swing.*;
import java.awt.*;
import java.lang.*;
import java.awt.event.*;
import java.io.*;
public class SignUpPage
{
private JFrame signFrame;
JTextField idField,passwdField;
JButton registerBtn,cancelBtn,resetBtn;
JLabel studIdLbl,passwdLbl,schoolLbl,label;
JComboBox schoolBox;
String [] school = {"School Of Computing & Creative Media","School Of
Communication & Creative Arts","School Of Engineering","School Of Business"
,"School of Hospiality Tourism & Culinary Arts"};
Font labelFont;
Color btnClr,btnTxtClr,lblClr,backgroundClr;
String selectSchool;
BufferedReader validateFile;
String details;
String detailsArray[];
int detailsExists = 0;
public void SecondPage()
{
//ComboBox(Class)
label = new JLabel("");
//Color
btnClr = new Color(0, 179, 60);
btnTxtClr = new Color(255,255,255);
backgroundClr = new Color(26, 26, 26);
lblClr = new Color(255,255,255);
//Font
labelFont = new Font("Verdana",Font.PLAIN,13);
//JTextField
idField = new JTextField("Student ID",4);
idField.setMinimumSize(new Dimension(300,30));
idField.setMaximumSize(new Dimension(300,30));
idField.setBorder(javax.swing.BorderFactory.createEmptyBorder());
passwdField = new JTextField("Password",4);
passwdField.setMinimumSize(new Dimension(300,30));
passwdField.setMaximumSize(new Dimension(300,30));
passwdField.setBorder(javax.swing.BorderFactory.createEmptyBorder());
//JComboBox
schoolBox = new JComboBox(school);
schoolBox.setFont(labelFont);
schoolBox.setMinimumSize(new Dimension(300,30));
schoolBox.setMaximumSize(new Dimension(300,30));
schoolBox.addActionListener((ActionEvent e)->{
JComboBox <String> schoolCombo = (JComboBox<String>) e.getSource();
selectSchool = (String) schoolCombo.getSelectedItem();
});
//Panel
JPanel fieldPnl = new JPanel();
JPanel btnPnl = new JPanel();
//Button
registerBtn = new JButton("<html><font face=\"Verdana\">Register</font></html>");
registerBtn.setBackground(btnClr);
registerBtn.setForeground(lblClr);
cancelBtn = new JButton("<html><font face=\"Verdana\">Cancel</font></html>");
cancelBtn.setBackground(btnClr);
cancelBtn.setForeground(lblClr);
resetBtn = new JButton("<html><font face=\"Verdana\">Reset</font></html>");
resetBtn.setBackground(btnClr);
resetBtn.setForeground(lblClr);
//Label
studIdLbl = new JLabel("Student ID:");
passwdLbl = new JLabel("Password");
schoolLbl = new JLabel("School:");
//Adding Components to Panel
fieldPnl.add(Box.createRigidArea(new Dimension(0,100)));
fieldPnl.setBackground(backgroundClr);
fieldPnl.add(idField);
fieldPnl.add(Box.createRigidArea(new Dimension(0,10)));
fieldPnl.add(passwdField);
fieldPnl.add(Box.createRigidArea(new Dimension(0,10)));
fieldPnl.add(schoolBox);
fieldPnl.add(Box.createRigidArea(new Dimension(0,50)));
btnPnl.setBackground(backgroundClr);
btnPnl.add(registerBtn);
btnPnl.add(cancelBtn);
btnPnl.add(resetBtn);
btnPnl.add(label);
btnPnl.add(Box.createRigidArea(new Dimension(0,190)));
//Layout
fieldPnl.setLayout(new BoxLayout(fieldPnl,BoxLayout.Y_AXIS));
//Action Listener
registerBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
BufferedWriter toFile;
try {
signUpValidation();
if(detailsExists==0)
{
toFile = new BufferedWriter(new FileWriter("details.txt",true));
toFile.write(idField.getText() + "," + passwdField.getText() + ","+selectSchool);
toFile.newLine();
toFile.flush();
}
else if(detailsExists==1)
{
//same values exists in file
}
} catch(FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
signFrame = new JFrame("Sign Up");
signFrame.add(btnPnl,BorderLayout.SOUTH);
signFrame.add(fieldPnl,BorderLayout.CENTER);
signFrame.setVisible(true);
signFrame.setSize(450,450);
signFrame.setResizable(false);
signFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
}
public Frame getFrame()
{
return signFrame;
}
public int signUpValidation() throws IOException
{
validateFile = new BufferedReader(new FileReader("details.txt"));
details = validateFile.readLine();
while(details!=null)
{
detailsArray=details.split(",");
if(idField.equals(detailsArray[0]) || passwdField.equals(detailsArray[1]))
{
detailsExists = 1;
}
else
detailsExists = 0;
}
return detailsExists;
}
}
while(details!=null) prevents the loop from ever exiting, because details is not updated with in the loop's context - it never becomes null
Something like...
String details = null;
while((details = validateFile.readLine()) !=null) {...
might be safer. But based on your code, you're only expecting a single line, so getting rid of the loop altogether might be a better solution
I'm doing coding for Food Ordering GUI. I would like to ask few questions. I would like to ask that how should I declare variable to hold value for tfPrice1, tfPrice2, tfPrice3? What should I do to make the "Place Order" button so that when it is pressed it will sum up the values contained in the JTextFields? Below is my code.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FoodOrder1 extends JFrame
{
JButton riceBtn,noodleBtn,soupBtn;
JTextField display,total,tfPrice1,tfPrice2,tfPrice3;
JPanel mp,p1,p2,p3,p4,p5,p6,p7,p8;
JLabel dsp,ttl,rLbl,nLbl,sLbl,prc1,prc2,prc3;
int rice=3 , noodle=3 , soup=4;
int Total , price1=Integer.parseInt(tfPrice1), price2=Integer.parseInt(tfPrice2) , price3=Integer.parseInt(tfPrice3);
public FoodOrder1()
{
Container pane = getContentPane();
mp = new JPanel();
mp.setLayout(new GridLayout(14,1));
pane.add(mp);
p1 = new JPanel();
p1.setLayout(new GridLayout(1,1));
rLbl = new JLabel("Rice");
rLbl.setFont(new Font("Myraid Pro",Font.BOLD,14));
riceBtn = new JButton("Fried Rice " + "RM3");
p1.add(riceBtn);
riceBtn.addActionListener(new MyAction());
p1.add(rLbl);
p1.add(riceBtn);
p2 = new JPanel();
p2.setLayout(new GridLayout(1,2));
nLbl = new JLabel("Noodle");
nLbl.setFont(new Font("Myraid Pro",Font.BOLD,14));
noodleBtn = new JButton("Tomato Noodle " + "RM3");
noodleBtn.addActionListener(new MyAction());
p2.add(nLbl);
p2.add(noodleBtn);
p3 = new JPanel();
p3.setLayout(new GridLayout(1,2));
sLbl = new JLabel("Soup");
sLbl.setFont(new Font("Myraid Pro",Font.BOLD,14));
soupBtn = new JButton("Tomyam Soup " + "RM4");
soupBtn.addActionListener(new MyAction());
p3.add(sLbl);
p3.add(soupBtn);
p4 = new JPanel();
p4.setLayout(new GridLayout(1,2));
prc1 = new JLabel("Price of Fried Rice");
prc1.setFont(new Font("Myraid Pro",Font.BOLD,14));
tfPrice1 = new JTextField(10);
p4.add(prc1);
p4.add(tfPrice1);
tfPrice1.setEditable(false);
p5 = new JPanel();
p5.setLayout(new GridLayout(1,2));
prc2 = new JLabel("Price of Tomato Noodle");
prc2.setFont(new Font("Myraid Pro",Font.BOLD,14));
tfPrice2 = new JTextField(10);
p5.add(prc2);
p5.add(tfPrice2);
tfPrice2.setEditable(false);
p6 = new JPanel();
p6.setLayout(new GridLayout(1,2));
prc3 = new JLabel("Price of Tomyam Soup");
prc3.setFont(new Font("Myraid Pro",Font.BOLD,14));
tfPrice3 = new JTextField(10);
p6.add(prc3);
p6.add(tfPrice3);
tfPrice3.setEditable(false);
p7 = new JPanel();
p7.setLayout(new FlowLayout());
poBtn = new JButton("Place Order");
poBtn.setFont(new Font("Myraid Pro",Font.PLAIN,14));
poBtn.addActionListener(new MyAction2());
rstBtn = new JButton("Reset");
rstBtn.setFont(new Font("Myraid Pro",Font.PLAIN,14));
rstBtn.addActionListener(new MyAction3());
p7.add(poBtn);
p7.add(rstBtn);
p8 = new JPanel();
p8.setLayout(new GridLayout(1,2));
ttl = new JLabel("Total (RM)");
ttl.setFont(new Font("Myraid Pro",Font.BOLD,14));
total = new JTextField(10);
p8.add(ttl);
p8.add(total);
total.setEditable(false);
mp.add(p1);
mp.add(p2);
mp.add(p3);
mp.add(p4);
mp.add(p5);
mp.add(p6);
mp.add(p7);
mp.add(p8);
}
public class MyAction implements ActionListener
{
int counter=0;
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == riceBtn)
{
counter++;
tfPrice1.setText("RM" + String.valueOf(counter*rice));
}
if (e.getSource() == noodleBtn)
{
counter++;
tfPrice2.setText("RM" + String.valueOf(counter*noodle));
}
if (e.getSource() == soupBtn)
{
counter++;
tfPrice3.setText("RM" + String.valueOf(counter*soup));
}
}
}
public class MyAction2 implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
price1.setText(String.valueOf(tfPrice1));
price2.setText(String.valueOf(tfPrice2));
price3.setText(String.valueOf(tfPrice3));
Total = price1+price2+price3;
total.setText(String.valueOf(Total));
}
}
public class MyAction3 implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == rstBtn)
{
tfPrice1.setText("");
tfPrice2.setText("");
tfPrice3.setText("");
total.setText("");
}
}
}
public static void main(String [] args)
{
FoodOrder1 f = new FoodOrder1();
f.setVisible(true);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(1000,800);
}
}
You don't need a variable to hold the value. Just extract the text from the text boxes whenever you need the value.
double totalPrice = 0.0;
totalPrice += Double.parseDouble(tfPrice1.getText());
totalPrice += Double.parseDouble(tfPrice2.getText());
totalPrice += Double.parseDouble(tfPrice3.getText());
total.setText(String.valueOf(totalPrice));
here is code to hold textfield value to some string
String data = txtdata.getText();
Take data entered to txtdata jTextField into data which is of string datatype
I have been trying to run this code which takes the user's assessed home value, the county and school taxes and then outputs them to a text field. This code compiles and runs but there is a logical error somewhere that doesn't let it output any text. I'm just starting with Java so any help would be appreciated.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PropertyTax3 extends JFrame
{
// set parameters to define extent of the window
private static final int WIDTH = 500, HEIGHT = 300;
private ExitHandler ebHandler;
private CalculateHandler cbHandler;
private JTextField assessTF, schoolRateTF, countyRateTF, schoolTaxTF, countyTaxTF, totalTaxTF;
public PropertyTax3()
{
// set title, size and visibility aspects of window
setTitle("Calculation of Property Taxes");
//Label Definitions
JLabel assessL = new JLabel("Assesment Home Value:", SwingConstants.RIGHT);
JLabel schoolRateL = new JLabel("Decimal Value of School Tax Rate:", SwingConstants.RIGHT);
JLabel countyRateL = new JLabel("Decimal Value of County Tax Rate:", SwingConstants.RIGHT);
JLabel schoolTaxL = new JLabel("School Taxes:", SwingConstants.RIGHT);
JLabel countyTaxL = new JLabel("County Taxes:", SwingConstants.RIGHT);
JLabel totalTaxL = new JLabel("Total Taxes:", SwingConstants.RIGHT);
//Text Field Definitions
JTextField assessTF = new JTextField(10);
JTextField schoolRateTF = new JTextField(10);
JTextField countyRateTF = new JTextField(10);
JTextField schoolTaxTF = new JTextField(10);
JTextField countyTaxTF = new JTextField(10);
JTextField totalTaxTF = new JTextField(10);
//Exit Button
JButton exit = new JButton("Exit");
ebHandler = new ExitHandler();
exit.addActionListener(ebHandler);
//Calculate Button
JButton calculate = new JButton("Calculate");
cbHandler = new CalculateHandler();
calculate.addActionListener(cbHandler);
//Container format
Container pane = getContentPane();
pane.setLayout(new GridLayout(7,2));
pane.add(assessL);
pane.add(assessTF);
pane.add(schoolRateL);
pane.add(schoolRateTF);
pane.add(countyRateL);
pane.add(countyRateTF);
pane.add(schoolTaxL);
pane.add(schoolTaxTF);
pane.add(countyTaxL);
pane.add(countyTaxTF);
pane.add(totalTaxL);
pane.add(totalTaxTF);
pane.add(exit);
pane.add(calculate);
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private class ExitHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
private class CalculateHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double countyRate, schoolRate, assessment, schoolTax, countyTax, totalTax;
assessment = Double.parseDouble(assessTF.getText());
schoolRate = Double.parseDouble(schoolRateTF.getText());
countyRate = Double.parseDouble(countyRateTF.getText());
schoolTax = assessment * schoolRate * .01;
countyTax = assessment * countyRate * .01;
totalTax = schoolTax + countyTax;
schoolTaxTF.setText(""+ String.format("%.2f", schoolTax));
countyTaxTF.setText(""+ String.format("%.2f", countyTax));
totalTaxTF.setText(""+ String.format("%.2f", totalTax));
}
}
public static void main(String[] args)
{
// main program to invoke constructor
PropertyTax3 proptax = new PropertyTax3();
}
}
Change this
JTextField assessTF = new JTextField(10);
JTextField schoolRateTF = new JTextField(10);
JTextField countyRateTF = new JTextField(10);
JTextField schoolTaxTF = new JTextField(10);
JTextField countyTaxTF = new JTextField(10);
JTextField totalTaxTF = new JTextField(10);
to this
assessTF = new JTextField(10);
schoolRateTF = new JTextField(10);
countyRateTF = new JTextField(10);
schoolTaxTF = new JTextField(10);
countyTaxTF = new JTextField(10);
totalTaxTF = new JTextField(10);
That way, you aren't using the variables you defined as a class field, but creating new ones. And that's why you couldn't access them later with getText and setText.
That's because there are no values for the program to run with...
[Now working!] I have this code that should calculate percents (With some GUI). But the calculating part is not working... Maybe some of you know the answer? I think the problem is when I concert it from a string do a double. I'm from Sweden so I have a very crappy english. And all variable names were in swedish so I just translated them with googles translate.
package Java;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class java {
public static void main (String []args){
int frameSizeX = 500;
int frameSizeY = 135;
JPanel p = new JPanel();
p.setPreferredSize( new Dimension(frameSizeX,frameSizeY) );
JFrame f = new JFrame ("Percentage");
f.setSize(frameSizeX,frameSizeY);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.getContentPane().add(p);
JLabel cardiNum = new JLabel ("Cardinal number");
JTextField cardiNumField = new JTextField();
cardiNumField.setPreferredSize( new Dimension( 500, 24 ) );
final String talValue = (cardiNumField.getText());
JLabel perc = new JLabel("Percentage");
JTextField percField = new JTextField();
percField.setPreferredSize( new Dimension( 500, 24 ) );
final String proValue = (percField.getText());
double D = 0;
final JLabel answer = new JLabel("The answer is = " + D);
JButton butt = new JButton("Calculate");
butt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
double A = Double.parseDouble(talValue);
double B = Double.parseDouble(proValue);
double C = A/100;
double D = C*B;
answer.setText("The answer is" + D);
}
});
p.add(cardiNum, BorderLayout.AFTER_LINE_ENDS);
p.add(cardiNumField, BorderLayout.AFTER_LINE_ENDS);
p.add(perc, BorderLayout.AFTER_LINE_ENDS);
p.add(percField, BorderLayout.AFTER_LINE_ENDS);
p.add(butt);
p.add(answer);
f.pack();
f.setVisible(true);
}
}
You're getting the NullPointerException because you need to set those two strings only once the JButton has been clicked, inside the ActionListener.
Put these two lines:
final String talValue = (cardiNumField.getText());
final String proValue = (percField.getText());
inside the ActionListener for the JButton and make the cardiNumField and percField final and it should work. Alternatively, you can just remove those two variables and have:
double A = Double.parseDouble(cardiNumField.getText());
double B = Double.parseDouble(percField.getText());
As Martin Dinov mentions, the problem is that you were reading the contents of the text boxes before the user was able to write in them and click the button. That leads to a NumberFormatException, because you're trying to convert the empty String "" to a double. Therefore, you need to put that code inside the button click event handler. An extra change to fix this is that you need to make your text fields final. i.e.
final JTextField cardiNumField = new JTextField();
final JTextField percField = new JTextField();
That's because the button click handler is an anonymous inner class, so it can only read from final variables.
The following code fixes the problem I think you have been seeing.
public static void main(String[] args) {
int frameSizeX = 500;
int frameSizeY = 135;
JPanel p = new JPanel();
p.setPreferredSize(new Dimension(frameSizeX, frameSizeY));
JFrame f = new JFrame("Percentage");
f.setSize(frameSizeX, frameSizeY);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.getContentPane().add(p);
JLabel cardiNum = new JLabel("Cardinal number");
final JTextField cardiNumField = new JTextField();
cardiNumField.setPreferredSize(new Dimension(500, 24));
JLabel perc = new JLabel("Percentage");
final JTextField percField = new JTextField();
percField.setPreferredSize(new Dimension(500, 24));
double D = 0;
final JLabel answer = new JLabel("The answer is = " + D);
JButton butt = new JButton("Calculate");
butt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
double cardinal = Double.parseDouble(cardiNumField.getText());
double percentage = Double.parseDouble(percField.getText());
double C = cardinal / 100;
double D = C * percentage;
answer.setText("The answer is " + D);
}
});
p.add(cardiNum, BorderLayout.AFTER_LINE_ENDS);
p.add(cardiNumField, BorderLayout.AFTER_LINE_ENDS);
p.add(perc, BorderLayout.AFTER_LINE_ENDS);
p.add(percField, BorderLayout.AFTER_LINE_ENDS);
p.add(butt);
p.add(answer);
f.pack();
f.setVisible(true);
}
Good luck with learning Java. You're obviously very new to it! :)
This question already has answers here:
Why are only final variables accessible in anonymous class?
(15 answers)
Closed 9 years ago.
I am having trouble making a button that closes this swing and returns to the previous swing menu. I have tried the following...
btnBack = new JButton("Back");
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MainMenu gui = new MainMenu(uname);
gui.setVisible(true);
gui.pack();
gui.setLocationRelativeTo(null);
frame.setVisible(false);
frame.dispose();
}
});
When I try this, it's giving me the error
Local variable frame is accessed from within inner class: needs to be declared final
I have trimmed my code removing my JDBC
public class newImageViewer implements ActionListener {
JLabel lblInstru, lblInstruVal, lblInstrumentID, lblImgnameVal, lblImgtagVal, lblImgsizeVal, lblDateVal, lblImgpathVal, lblTakenbyVal, lblNoteVal, lblImgpath, lblTakenby, lblSalary, lblImgsize, lblDate, lblS,
lblSVal, lblNote, lblImgtag, lblImgname, imagel;
JTextField txtDate, txtImgpath, txtTakenby, txtImgname, txtImgtag, txtImgsize, txtNote, txtInstrumentID;
JButton btnAdd, btnUpdate, btnDelete, btnPrev, btnNext, btnBack;
ResultSet rs;
private ImageIcon image1;
String imagepath, uname;
static final String DATABASE_URL = "jdbc:mysql://localhost:3306/mysql";
static final String USERNAME = "root";
static final String PASSWORD = "root";
public static void main(String[] args) {
newImageViewer obj = new newImageViewer();
obj.createUI();
}
private void createUI() {
JFrame frame = new JFrame("Image Details");
JPanel pnlInput = new JPanel(new GridLayout(4, 2));
lblImgname = new JLabel(" Image Name : ");
txtImgname = new JTextField();
lblImgtag = new JLabel(" ImageTag : ");
txtImgtag = new JTextField();
lblDate = new JLabel(" Date Stamp : ");
txtDate = new JTextField(15);
lblImgpath = new JLabel(" Image Path : ");
txtImgpath = new JTextField();
lblTakenby = new JLabel(" Taken By : ");
txtTakenby = new JTextField();
lblImgsize = new JLabel(" Image Size : ");
txtImgsize = new JTextField();
lblNote = new JLabel(" Note : ");
txtNote = new JTextField();
lblInstrumentID = new JLabel(" Instrument ID : ");
txtInstrumentID = new JTextField();
pnlInput.add(lblImgname);
pnlInput.add(txtImgname);
pnlInput.add(lblImgtag);
pnlInput.add(txtImgtag);
pnlInput.add(lblImgsize);
pnlInput.add(txtImgsize);
pnlInput.add(lblNote);
pnlInput.add(txtNote);
pnlInput.add(lblDate);
pnlInput.add(txtDate);
pnlInput.add(lblImgpath);
pnlInput.add(txtImgpath);
pnlInput.add(lblTakenby);
pnlInput.add(txtTakenby);
pnlInput.add(lblNote);
pnlInput.add(txtNote);
pnlInput.add(lblInstrumentID);
pnlInput.add(txtInstrumentID);
JPanel pnlButton = new JPanel(new GridLayout(1, 3));
btnAdd = new JButton("Add");
btnAdd.addActionListener(this);
btnUpdate = new JButton("Update");
btnUpdate.addActionListener(this);
btnDelete = new JButton("Delete");
btnDelete.addActionListener(this);
btnBack = new JButton("Back");
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MainMenu gui = new MainMenu(uname);
gui.setVisible(true);
gui.pack();
gui.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
pnlButton.add(btnAdd);
pnlButton.add(btnUpdate);
pnlButton.add(btnBack);
pnlButton.add(btnDelete);
JPanel pnlNavigate = new JPanel(new GridLayout(1, 2));
btnPrev = new JButton(" << ");
btnPrev.setActionCommand("Prev");
btnPrev.addActionListener(this);
btnNext = new JButton(" >> ");
btnNext.setActionCommand("Next");
btnNext.addActionListener(this);
pnlNavigate.add(btnPrev);
pnlNavigate.add(btnNext);
JPanel pnlNavAns = new JPanel(new GridLayout(4, 2));
lblImgname = new JLabel(" Image Name : ");
lblImgnameVal = new JLabel("Val");
lblImgtag = new JLabel(" Image Tag : ");
lblImgtagVal = new JLabel("Val");
lblImgsize = new JLabel(" Image Size : ");
lblImgsizeVal = new JLabel("Val");
lblDate = new JLabel(" Date Stamp : ");
lblDateVal = new JLabel("Val");
lblImgpath = new JLabel(" Image Path : ");
lblImgpathVal = new JLabel("Val");
lblTakenby = new JLabel(" Taken By : ");
lblTakenbyVal = new JLabel("Val");
lblNote = new JLabel(" Note : ");
lblNoteVal = new JLabel("Val");
lblInstru = new JLabel(" Instrument ID : ");
lblInstruVal = new JLabel("Val");
pnlNavAns.add(lblImgname);
pnlNavAns.add(lblImgnameVal);
pnlNavAns.add(lblImgtag);
pnlNavAns.add(lblImgtagVal);
pnlNavAns.add(lblImgsize);
pnlNavAns.add(lblImgsizeVal);
pnlNavAns.add(lblDate);
pnlNavAns.add(lblDateVal);
pnlNavAns.add(lblImgpath);
pnlNavAns.add(lblImgpathVal);
pnlNavAns.add(lblTakenby);
pnlNavAns.add(lblTakenbyVal);
pnlNavAns.add(lblNote);
pnlNavAns.add(lblNoteVal);
pnlNavAns.add(lblInstru);
pnlNavAns.add(lblInstruVal);
final Container cn = frame.getContentPane();
cn.setLayout(new BoxLayout(cn, BoxLayout.Y_AXIS));
frame.add(pnlInput);
frame.add(pnlButton);
frame.add(pnlNavAns);
frame.add(pnlNavigate);
//If this will not be written, the only frame will be closed
// but the application will be active.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent evt) {
String action = evt.getActionCommand();
if (action.equals("Add")) {
addOperation();
} else if (action.equals("Update")) {
updateOperation();
} else if (action.equals("Delete")) {
deleteOperation();
} else if (action.equals("Prev")) {
preNavigation();
} else if (action.equals("Next")) {
nextNavigation();
}
}
private void addOperation()
private void updateOperation()
private void deleteOperation()
private void preNavigation()
private void nextNavigation()
private void populateValue()
}
As noted, all you need to do is listen to your compiler and simply make the frame variable final:
final JFrame frame = new JFrame("Image Details");
An alternative solution is to make frame a non-static class field.
The reason for the problem is that you're trying to use a local variable in an anonymous inner class, and since these classes make copies of these variables, if the variable is not marked final, there's a chance that the two frame variables, the local one and the copy inside the anonymous class's object, might hold different values.
Edit
As per my comment, your question is a very common one. For details on the problem please see this possible duplicate question: Why are only final variables accessible in anonymous class?. I'm going to vote to close this question as a duplicate and encourage others to to the same so that the comments to the accepted answer get read. The comments to the answer are where the real answer is.