Java swing GUI error - java

my GUI program is about writing a psychology quiz for my class. It uses swing but I am getting two errors on terminal and I'm not sure what the problem is. Can I know what my error is?
MyGuiProject.java:78: error: ';' expected
int JLabel scoreK = new JLabel("Your score is " + score + ".");
^
MyGuiProject.java:78: error: <identifier> expected
int JLabel scoreK = new JLabel("Your score is " + score + ".");
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyGuiProject
extends JFrame implements ActionListener
{
//instance variables
//JFrame
private JFrame frame1 = new JFrame("Psychology Quiz");
private JFrame frame2 = new JFrame("Solutions");
//JPanel (p1 = panel 1)
private JPanel p1 = new JPanel();
private JPanel p2 = new JPanel();
private JPanel p3 = new JPanel();
//Fonts (f1 = font 1)
private Font f1 = new Font("Times New Roman", Font.BOLD, 30);
private Font f2 = new Font("Arial", Font.ITALIC, 30);
//Description (d1 = description)
private JLabel d1 = new JLabel("Psychology - Classical Conditioning");
//questions (q1 = question 1)
private JLabel q1 = new JLabel("Any behavior or action is...");
private JLabel q2 = new JLabel(
"All mental process associated with thinking, knowing, and remembering is...");
private JLabel q3 = new JLabel("American psychologist and founder of behaviorism is...");
//answers (a1 = answer 1)
private JButton a1 = new JButton("response");
private JButton a2 = new JButton("reaction");
private JButton a3 = new JButton("stimulus");
private JButton b1 = new JButton("recognition");
private JButton b2 = new JButton("cognition");
private JButton b3 = new JButton("classical conditioning");
private JButton c1 = new JButton("John B. Watson");
private JButton c2 = new JButton("Mr. Morgan");
private JButton c3 = new JButton("Mr. Ansari");
//Images
private ImageIcon image1 = new ImageIcon("ang.jpg");
private ImageIcon image2 = new ImageIcon("psych.jpg");
//JMenu
private JMenuBar ppap = new JMenuBar();
private JMenu menu1 = new JMenu("Questions");
private JMenuItem item1 = new JMenuItem("1");
private JMenuItem item2 = new JMenuItem("2");
private JMenuItem item3 = new JMenuItem("3");
//Solutions (s1 = solution 1)
private JLabel s1 = new JLabel(
"Answers: 1) response || 2) cognition || 3) John B. Watson (unfortunately)");
//Another program for adding points and label for adding points
int score = 0;
int JLabel scoreK = new JLabel("Your score is " + score + ".");
ScoreKeeper ang1 = new ScoreKeeper();
public void angWindow()
{
//setting frame
frame1.setBounds(0, 0, 300, 400);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//addActionListener for JButton and JMenuItem
a1.addActionListener(this);
a2.addActionListener(this);
a3.addActionListener(this);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c1.addActionListener(this);
c2.addActionListener(this);
c3.addActionListener(this);
item1.addActionListener(this);
item2.addActionListener(this);
item3.addActionListener(this);
//setting font
d1.setFont(f1);
scoreK.setFont(f2);
//JPanel for questions
p1.add(a1);
p1.add(a2);
p1.add(a3);
p2.add(b1);
p2.add(b2);
p2.add(b3);
p3.add(c1);
p3.add(c2);
p3.add(c3);
//JMenu on JMenuBar
ppap.add(menu1);
//setting frame again
frame1.setJMenuBar(ppap);
frame1.add(q1, BorderLayout.SOUTH);
frame1.add(p1, BorderLayout.NORTH);
frame1.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String command = e.getActionCommand();
if(command.equals("response"))
{
frame1.add(q2, BorderLayout.NORTH);
frame1.remove(q1);
frame1.remove(p1);
frame1.add(p2, BorderLayout.SOUTH);
score = ang1.trackScore(score);
frame1.validate();
frame1.repaint();
}
if(command.equals("reaction"))
{
frame1.remove(p1);
frame1.remove(q1);
frame1.add(p2, BorderLayout.NORTH);
frame1.add(q2, BorderLayout.SOUTH);
score = ang1.trackScore(score);
frame1.validate();
frame1.repaint();
}
if(command.equals("stimulus"))
{
frame1.remove(p1);
frame1.remove(q1);
frame1.add(p2, BorderLayout.NORTH);
frame1.add(q2, BorderLayout.SOUTH);
score = ang1.trackScore(score);
frame1.validate();
frame1.repaint();
}
if(command.equals("recognition"))
{
frame1.add(q2, BorderLayout.NORTH);
frame1.remove(q2);
frame1.remove(p2);
frame1.add(p3, BorderLayout.SOUTH);
score = ang1.trackScore(score);
frame1.validate();
frame1.repaint();
}
if(command.equals("cognition"))
{
frame1.add(q3, BorderLayout.NORTH);
frame1.remove(q2);
frame1.add(p3, BorderLayout.SOUTH);
frame1.validate();
frame1.repaint();
}
if(command.equals("classical conditioning"))
{
frame1.add(q2, BorderLayout.NORTH);
frame1.remove(q2);
frame1.remove(p2);
frame1.add(p3, BorderLayout.SOUTH);
score = ang1.trackScore(score);
frame1.validate();
frame1.repaint();
}
if(command.equals("John B. Watson"))
{
frame1.remove(q3);
frame1.remove(p3);
score = ang1.trackScore(score);
frame1.validate();
frame1.repaint();
frame2.setVisible(true);
}
if(command.equals("..."))
{
frame1.remove(p3);
frame1.remove(q3);
frame1.validate();
frame1.repaint();
score = ang1.trackScore(score);
frame2.setVisible(true);
}
if(command.equals("..."))
{
frame1.remove(p3);
frame1.remove(q3);
frame1.validate();
frame1.repaint();
score = ang1.trackScore(score);
frame2.setVisible(true);
}
frame1.remove(scoreK);
scoreK.setText("Your score is " + score + ".");
frame1.add(scoreK, BorderLayout.CENTER);
}
public static void main(String[] args)
{
MyGuiProject angBaby = new MyGuiProject();
angBaby.setWindow();
}
}
public class ScoreKeeper
{
public int trackScore(int score)
{
score = score + 2;
return score;
}
}

Is this an int or a JLabel ?
int JLabel scoreK = new JLabel("Your score is " + score + ".");
try
JLabel scoreK = new JLabel("Your score is " + score + ".");

Related

How to make my JButton connect with my JFrame?

This is a BMI calculator. I have to separete classes Lab 4 and Lab5 (which is an extension of lab 4) However, I'm trying to get the JFrame(frame1) to show once I click the calculation button (CalculateBMI), after tryin and changing it a couple of times nothing is working and i'm hoping maybe someone here can help me.
**LAB4**
import java.awt.*;
import javax.swing.*;
public class Lab4 extends JApplet
{
JButton calculateBMI, clear, resetapplet, displaystats, clearstats;
Image img1, img2, img3;
JLabel title, logo1, logo2, logo3, explain, showpic, empty1, empty2, welcome, BMIresult, genderOutput, height, weight, BMI, healthy, thanks;
JPanel north, west, center, east, south, west1, center1, south1, north2, west2, center2, east2, south2, center1_1;
JComboBox gender, feet, inches;
JFrame frame1 = new JFrame("BMI Calculation ");
JFrame frame2 = new JFrame ("BMI Calcuylation: User Story");
JTextArea txt1;
JTextField txtfield1, txtfield2;
Color violet = new Color(132, 28, 164);
Color darkRed = new Color(148, 15, 15);
Color lightRed = new Color(162, 101, 101);
public void init ()
{
setLayout( new BorderLayout());
doNorth();
doWest();
doCenter();
doEast();
doSouth();
frame1();
frame2();
setSize (975,500);
}
public void frame1()
{
frame1.setBounds(0, 250, 400, 300);
doWest1();
doCenter1();
doSouth1();
frame1.setVisible(false);
}
public void doWest1()
{
JPanel west1_1 = new JPanel(new FlowLayout());
img3 = getImage(getCodeBase(), "HealthyMale.png");
logo3 = new JLabel(new ImageIcon(img3));
west1_1.add(logo3);
frame1.add(west1_1, BorderLayout.WEST);
}
public void doCenter1()
{
center1_1 = new JPanel(new GridLayout(12,1));
empty1 = new JLabel("");
empty2 = new JLabel("");
welcome = new JLabel("Welcome Sally Jones");
BMIresult = new JLabel("Your BMI results are:");
genderOutput = new JLabel("You are: Female");
height = new JLabel("Your Height is: 5 feet and 3 inches");
weight = new JLabel("Your weight is: 122lbs");
BMI = new JLabel("Your Body Mass Index (BMI) is: 21.61");
healthy = new JLabel("You are: Healthy = BMI between 18.5-24.9");
thanks = new JLabel("Thank you for using our Java Applet");
center1_1.add(empty1);
center1_1.add(welcome);
center1_1.add(BMIresult);
center1_1.add(genderOutput);
center1_1.add(height);
center1_1.add(weight);
center1_1.add(BMI);
center1_1.add(empty2);
center1_1.add(healthy);
center1_1.add(thanks);
frame1.add(center1_1, BorderLayout.CENTER);
}
public void doSouth1()
{
south1 = new JPanel(new FlowLayout());
JButton exitFrame = new JButton("Exit Frame");
JButton storeResults = new JButton("Store Results");
south1.add(storeResults);
south1.add(exitFrame);
south1.setBackground(darkRed);
frame1.add(south1, BorderLayout.SOUTH);
}
public void frame2()
{
frame2.setBounds(450, 250, 525, 300);
doNorth2();
doCenter2();
doSouth2();
doEast2();
doWest2();
frame2.setVisible(false);
}
public void doNorth2()
{
north2 = new JPanel(new FlowLayout());
JLabel history2 = new JLabel ("BMI's Caltulated and Stored since the last 'Clear Stats'");
north2.add(history2);
north2.setBackground(lightRed);
frame2.add(north2, BorderLayout.NORTH);
}
public void doCenter2()
{
center2 = new JPanel(new GridLayout(6,1));
JPanel center2_1 = new JPanel(new FlowLayout());
JPanel center2_2 = new JPanel(new GridLayout(1,3));
JPanel center2_3 = new JPanel(new GridLayout(1,3));
JLabel username = new JLabel("User Name");
JLabel gender = new JLabel ("Gender");
JLabel BMIcalculation = new JLabel("BMI Calculation");
JLabel name = new JLabel("Sally Jones");
JLabel female = new JLabel ("Female");
JLabel calculation = new JLabel ("21.61");
center2_2.add(username);
center2_2.add(gender);
center2_2.add(BMIcalculation);
center2_1.add(center2_2);
center2.add(center2_1);
center2_3.add(name);
center2_3.add(female);
center2_3.add(calculation);
center2.add(center2_3);
center2.setBackground(lightRed);
center2_1.setBackground(lightRed);
center2_2.setBackground(lightRed);
center2.setBorder(BorderFactory.createLineBorder(Color.darkGray, 1));
center2_1.setBorder(BorderFactory.createLineBorder(Color.darkGray, 2));
frame2.add(center2, BorderLayout.CENTER);
}
public void doEast2()
{
JPanel east2 = new JPanel (new FlowLayout());
east2.setBackground(lightRed);
east2.setPreferredSize(new Dimension(10,20));
frame2.add(east2,BorderLayout.EAST);
}
public void doWest2()
{
JPanel west2 = new JPanel (new FlowLayout());
west2.setBackground(lightRed);
west2.setPreferredSize(new Dimension(10,20));
frame2.add(west2,BorderLayout.WEST);
}
public void doSouth2()
{
south2 = new JPanel(new FlowLayout());
JButton exitFrame = new JButton("Exit Frame");
south2.add(exitFrame);
south2.setBackground(darkRed);
frame2.add(south2, BorderLayout.SOUTH);
}
public void doNorth()
{
north = new JPanel(new FlowLayout());
img1 = getImage(getCodeBase(), "BMI2.png");
logo1 = new JLabel (new ImageIcon(img1));
//explanation part
JPanel flow = new JPanel(new GridLayout(2,1));
JPanel flow1 = new JPanel (new FlowLayout());
JPanel flow2 = new JPanel (new FlowLayout());
JLabel title = new JLabel("Let's Calculate Your Body Mass Index (BMI)");
title.setFont(new Font("MonoSpaced", Font.BOLD, 22));
title.setForeground(Color.RED);
flow.setBackground(Color.GRAY);
JTextArea subtitle = new JTextArea("The Body Mass Index (BMI) measures the weight status of your body in relation \n"
+ " to the fat. It is a simple tool that helps to calculate the amont of excess \n"
+ " body fat and the associated risk of carrying this extra weight. It can be aplied \n "
+ "to both men and women. ");
subtitle.setForeground(Color.BLACK);
subtitle.setEnabled(false);
subtitle.setDisabledTextColor(Color.BLACK);
flow1.add(title);
flow2.add(subtitle);
flow.add(flow1);
flow.add(flow2);
flow.getBackground();
img2 = getImage(getCodeBase(), "BMI1.jpeg");
logo2 = new JLabel (new ImageIcon(img2));
north.add(logo1);
north.add(flow);
north.add(logo2);
north.setBackground(violet);
add(north,BorderLayout.NORTH);
}
public void doWest()
{
JPanel west = new JPanel (new FlowLayout());
west.setBackground(violet);
west.setPreferredSize(new Dimension(150,100));
add(west,BorderLayout.WEST);
}
public void doEast()
{
JPanel east = new JPanel (new FlowLayout());
east.setBackground(violet);
east.setPreferredSize(new Dimension(150,100));
add(east,BorderLayout.EAST);
}
public void doCenter()
{
center = new JPanel(new GridLayout(5,1));
//third row (3-rd)
JPanel third = new JPanel(new FlowLayout());
JTextField select = new JTextField("Select to Show Pictures or not:");
select.setEnabled(false);
select.setFont(new Font("MonoSpaced", Font.BOLD, 15 ));
select.setDisabledTextColor(Color.BLACK);
third.add(select);
JRadioButton radio = new JRadioButton("On");
third.add(radio);
radio.setEnabled(true);
JRadioButton radio1 = new JRadioButton("Off");
third.add(radio1);
radio1.setEnabled(true);
JCheckBox box = new JCheckBox("Sounds On");
third.add(box);
box.setEnabled(true);
third.setBackground(violet);
//fourth row(4-th)
JPanel txt3 = new JPanel(new FlowLayout());
JLabel logo3 = new JLabel("Press 'Calculate BMI' or 'CLEAR'", Font.ITALIC);
logo3.setFont(new Font("Monospaced", Font.BOLD, 18));
logo3.setForeground(Color.RED);
txt3.add(logo3);
center.add(third);
center.add(txt3);
//Fifth row
JPanel fifth = new JPanel(new FlowLayout());
JLabel name = new JLabel("Your Name:");
txtfield1 = new JTextField(20);
txtfield1.setEnabled(true);
gender = new JComboBox();
gender.addItem("Select");
gender.addItem("Male");
gender.addItem("Female");
gender.setEnabled(true);
//Adding Component Together
fifth.add(name);
fifth.add(txtfield1);
fifth.add(gender);
center.add(fifth);
//Sixth Row
JPanel sixth = new JPanel(new FlowLayout());
feet = new JComboBox();
feet.addItem("Select Feet");
feet.addItem(1);
feet.addItem(2);
feet.addItem(3);
feet.addItem(4);
feet.addItem(5);
feet.addItem(6);
feet.addItem(7);
feet.addItem(8);
feet.setEnabled(true);
inches = new JComboBox();
inches.addItem("Select Inches");
inches.addItem(1);
inches.addItem(2);
inches.addItem(3);
inches.addItem(4);
inches.addItem(5);
inches.addItem(6);
inches.addItem(7);
inches.addItem(8);
inches.addItem(9);
inches.addItem(10);
inches.addItem(11);
inches.setEnabled(true);
JLabel weight = new JLabel("Your Weight:");
txtfield2 = new JTextField(5);
txtfield2.setEnabled(true);
sixth.add(feet);
sixth.add(inches);
sixth.add(weight);
sixth.add(txtfield2);
center.add(sixth);
//seventh row
JPanel seventh = new JPanel(new FlowLayout());
calculateBMI = new JButton ("Calculate BMI");
JButton clear = new JButton ("Clear");
seventh.add(calculateBMI);
seventh.add(clear);
center.add(seventh);
center.setBorder(BorderFactory.createLineBorder(Color.darkGray, 5));
center.setSize(500,300);
center.setBackground(violet);
add(center,BorderLayout.CENTER);
}
public void doSouth()
{
south = new JPanel(new FlowLayout());
//eighth row
JButton reset = new JButton("Reset Applet");
JButton display = new JButton("Display Stats");
JButton stats = new JButton("Clear Stats");
south.add(reset);
south.add(display);
south.add(stats);
south.setBackground(violet);
south.setPreferredSize(new Dimension(800,100));
add(south,BorderLayout.SOUTH);
}
}
**LAB5**
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.EventObject;
public class Lab_5 extends Lab4 implements ActionListener
{
double H1, H2, W1, BMI1;
String Height, Height2, Weight1, BMIndex;
Image healthymale, healthyfemale, obesefemale, obesemale, overweightmale, overweightfemale, underweightmale, underweightfemale;
public void init()
{
super.init();
healthy();
obese();
overWeight();
underWeight();
images();
JLabel BMIText = new JLabel("Your Body Mass Index (BMI) is:" + BMIndex );
Height = (String) feet.getSelectedItem();
H1 = Double.parseDouble(Height);
H1 = H1 * 12;
Height2 = (String) inches.getSelectedItem();
H2 = Double.parseDouble(Height2);
H2 = H1 + H2 ;
Weight1 = (String) txtfield2.getText();
W1 = Double.parseDouble(Weight1);
W1 = W1 *703;
BMI1 = W1/H2;
BMIndex = String.valueOf(BMI);
calculateBMI.addActionListener(this);
calculateBMI.setEnabled(true);
}
public void images()
{
healthymale = getImage(getCodeBase(), "HealthyMale.png");
obesemale = getImage(getCodeBase(), "ObeseMale.png");
overweightmale = getImage(getCodeBase(), "OverweightMale.png");
underweightmale = getImage(getCodeBase(), "UnderweightMale.png");
healthyfemale = getImage(getCodeBase(), "HealthyFemale.png");
obesefemale = getImage(getCodeBase(),"ObeseFemale.png");
overweightfemale = getImage(getCodeBase(),"OverweightFemale.png");
underweightfemale = getImage(getCodeBase(),"UnderWeightFemale.png");
}
public void healthy()
{
welcome = new JLabel ("welcome" + txtfield1);
genderOutput = new JLabel("You are:"+ gender);
height = new JLabel("Your Height is:" + feet + "Feet" + inches + "Inches" );
weight = new JLabel("Your weight is:" + txtfield2 +"lbs");
BMI = new JLabel("Your Body Mass Index (BMI) is:"+BMIndex);
healthy = new JLabel("You are: Healthy = BMI between 18.5-24.9");
}
public void obese()
{
welcome = new JLabel ("welcome" + txtfield1);
genderOutput = new JLabel("You are:"+ gender);
height = new JLabel("Your Height is:" + feet + "Feet" + inches + "Inches" );
weight = new JLabel("Your weight is:" + txtfield2 +"lbs");
BMI = new JLabel("Your Body Mass Index (BMI) is:"+BMIndex);
healthy = new JLabel("You are: Obese = BMI of 30 or Greater");
}
public void overWeight()
{
welcome = new JLabel ("welcome" + txtfield1);
genderOutput = new JLabel("You are:"+ gender);
height = new JLabel("Your Height is:" + feet + "Feet" + inches + "Inches" );
weight = new JLabel("Your weight is:" + txtfield2 +"lbs");
BMI = new JLabel("Your Body Mass Index (BMI) is:"+BMIndex);
healthy = new JLabel("You are: Over Weight = BMI between 25 - 29.9");
}
public void underWeight()
{
welcome = new JLabel ("welcome" + txtfield1);
genderOutput = new JLabel("You are:"+ gender);
height = new JLabel("Your Height is:" + feet + "Feet" + inches + "Inches" );
weight = new JLabel("Your weight is:" + txtfield2 +"lbs");
BMI = new JLabel("Your Body Mass Index (BMI) is:"+BMIndex);
healthy = new JLabel("You are: Under Weight = BMI lower than 18.5");
}
#Override
public void actionPerformed(ActionEvent arg0)
{
if
(BMI1 <= 18.5)
underWeight();
else if
(BMI1 > 18.5 && BMI1 <=24.9)
healthy();
else if
(BMI1 > 25 && BMI1 <= 29.9)
overWeight();
else if
(BMI1 > 30 )
obese();
Object obj = arg0.getSource();
if (obj == calculateBMI);
calculateBMI.getActionCommand();
frame1.setVisible(true);
// TODO Auto-generated method stub
}
}
If all you want to do is to display frame1 from within the calculateBMI button's press, then in your Lab5, add an ActionListener to the button that does your calculations, and that then displays the JFrame. Something as simple as:
import java.awt.event.ActionEvent;
#SuppressWarnings("serial")
public class Lab5b extends Lab4 {
#Override
public void init() {
super.init();
// add an ActionListener to the button
calculateBMI.addActionListener(e -> {calcBmiAction(e);});
}
private void calcBmiAction(ActionEvent e) {
// TODO calculations for BMI here. I'll leave this for you to do.
// frame1 displayed:
frame1.setVisible(true); // that's all that's needed
}
}
And you probably shouldn't create all those components that you're doing in your Lab5 class, but rather should change the state of existing components.
But also understand that this is bad program design that your instructor is having you do.

How to declare variable to hold value of JTextField?

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

Car buying program - need to calculate the final price with a JButton

I have values set for each of the car buying options but when I click the button I keep getting 0. I can't get fP to update after I declare it. Here is my code:
public class CarOptions extends JFrame {
//All the Buttons needed
private JComboBox colorOptions;
private JRadioButton leatherInt;
private JRadioButton touchScreen;
private JRadioButton premiumSound;
private JRadioButton bodyKit;
//Car prices
int cP = 1000;
int eng1 = 6000;
int eng2 = 8000;
int eng3 = 12000;
int acc1 = 600;
int acc2 = 800;
int acc3 = 3000;
int acc4 = 1200;
int fP;
public CarOptions(){
createControlPanel();
}
public void createControlPanel(){
//Panel for all the options
JPanel colorOptions1 = createComboBox();
JPanel sportsOptions = createCheckBoxes();
JPanel accOptions = createRadioButtons();
JPanel finalPrice1 = createButton();
//Line up the panels
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new GridLayout(4,1));
controlPanel.add(colorOptions1);
controlPanel.add(sportsOptions);
controlPanel.add(accOptions);
controlPanel.add(finalPrice1);
add(controlPanel, BorderLayout.SOUTH);
}
public JPanel createComboBox(){
colorOptions = new JComboBox();
colorOptions.addItem("Black");
colorOptions.addItem("Yellow");
colorOptions.addItem("Blue");
colorOptions.addItem("Red");
JPanel panel = new JPanel();
panel.add(colorOptions);
return panel;
}
public JPanel createCheckBoxes(){
ButtonGroup group = new ButtonGroup();
AbstractButton hybrid = new JCheckBox("Hybrid");
AbstractButton base = new JCheckBox("Base Model");
AbstractButton sport = new JCheckBox("Sport");
group.add(hybrid);
group.add(base);
group.add(sport);
if (hybrid.isSelected()){
fP = fP + eng1;
}
else if (base.isSelected()){
fP = fP + eng2;
}
else if (sport.isSelected()){
fP = fP + eng3;
}
JPanel panel = new JPanel();
panel.add(hybrid);
panel.add(base);
panel.add(sport);
panel.setBorder(new TitledBorder(new EtchedBorder(), "Engine Package"));
return panel;
}
public JPanel createRadioButtons(){
leatherInt = new JRadioButton("Leather Interior");
touchScreen = new JRadioButton("Touchscreen Radio");
premiumSound = new JRadioButton("Premium Sound System");
bodyKit = new JRadioButton("Body Kit");
if (leatherInt.isSelected()){
fP = cP + acc1;
}
else if (touchScreen.isSelected()){
fP = cP + acc2;
}
else if (premiumSound.isSelected()){
fP = cP + acc3;
}
else if (bodyKit.isSelected()){
fP = cP + acc4;
}
JPanel panel = new JPanel();
panel.add(leatherInt);
panel.add(touchScreen);
panel.add(premiumSound);
panel.add(bodyKit);
panel.setBorder(new TitledBorder(new EtchedBorder(), "Accesories"));
return panel;
}
public JPanel createButton(){
JButton finalPrice = new JButton("Final Price");
finalPrice.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JFrame fPFrame = new JFrame();
fPFrame.setSize(200,100);
fPFrame.setTitle("Final Price");
fPFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
fPFrame.setVisible(true);
JLabel fPLabel = new JLabel("Your final price is: $" + fP);
JPanel fPPanel = new JPanel();
fPPanel.add(fPLabel);
fPFrame.add(fPPanel);
}
});
JPanel panel = new JPanel();
panel.add(finalPrice);
return panel;
}
}
You get 0, because to don't calculate the price "when the button is clicked".
You are trying to calculate the price when you create the buttons. The problem is the user hasn't done anything yet. The price can only be calculated in response to an event.
So all your price calculation code needs to be moved to the ActionListener
You did the calculation only once, based on empty controls Here's a fix:
//All the Buttons needed
private JComboBox<String> colorOptions;
private JRadioButton leatherInt;
private JRadioButton touchScreen;
private JRadioButton premiumSound;
private JRadioButton bodyKit;
//Car prices
int cP = 1000;
int eng1 = 6000;
int eng2 = 8000;
int eng3 = 12000;
int acc1 = 600;
int acc2 = 800;
int acc3 = 3000;
int acc4 = 1200;
int fP;
public CarOptions(){
createControlPanel();
}
public void createControlPanel(){
//Panel for all the options
JPanel colorOptions1 = createComboBox();
JPanel sportsOptions = createCheckBoxes();
JPanel accOptions = createRadioButtons();
JPanel finalPrice1 = createButton();
//Line up the panels
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new GridLayout(4,1));
controlPanel.add(colorOptions1);
controlPanel.add(sportsOptions);
controlPanel.add(accOptions);
controlPanel.add(finalPrice1);
add(controlPanel, BorderLayout.SOUTH);
}
public JPanel createComboBox(){
colorOptions = new JComboBox<>();
colorOptions.addItem("Black");
colorOptions.addItem("Yellow");
colorOptions.addItem("Blue");
colorOptions.addItem("Red");
JPanel panel = new JPanel();
panel.add(colorOptions);
return panel;
}
public JPanel createCheckBoxes(){
ButtonGroup group = new ButtonGroup();
AbstractButton hybrid = new JCheckBox("Hybrid");
AbstractButton base = new JCheckBox("Base Model");
AbstractButton sport = new JCheckBox("Sport");
group.add(hybrid);
group.add(base);
group.add(sport);
if (hybrid.isSelected()){
fP = fP + eng1;
}
else if (base.isSelected()){
fP = fP + eng2;
}
else if (sport.isSelected()){
fP = fP + eng3;
}
JPanel panel = new JPanel();
panel.add(hybrid);
panel.add(base);
panel.add(sport);
panel.setBorder(new TitledBorder(new EtchedBorder(), "Engine Package"));
return panel;
}
public JPanel createRadioButtons(){
leatherInt = new JRadioButton("Leather Interior");
touchScreen = new JRadioButton("Touchscreen Radio");
premiumSound = new JRadioButton("Premium Sound System");
bodyKit = new JRadioButton("Body Kit");
recalculate();
JPanel panel = new JPanel();
panel.add(leatherInt);
panel.add(touchScreen);
panel.add(premiumSound);
panel.add(bodyKit);
panel.setBorder(new TitledBorder(new EtchedBorder(), "Accesories"));
return panel;
}
public JPanel createButton(){
JButton finalPrice = new JButton("Final Price");
finalPrice.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
recalculate();
JFrame fPFrame = new JFrame();
fPFrame.setSize(200,100);
fPFrame.setTitle("Final Price");
fPFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
fPFrame.setVisible(true);
JLabel fPLabel = new JLabel("Your final price is: $" + fP);
JPanel fPPanel = new JPanel();
fPPanel.add(fPLabel);
fPFrame.add(fPPanel);
}
});
JPanel panel = new JPanel();
panel.add(finalPrice);
return panel;
}
private void recalculate() {
if (leatherInt.isSelected()){
fP = cP + acc1;
}
else if (touchScreen.isSelected()){
fP = cP + acc2;
}
else if (premiumSound.isSelected()){
fP = cP + acc3;
}
else if (bodyKit.isSelected()){
fP = cP + acc4;
}
}

Can anyone tell me why my change QTY button isnt changing the QTY?

Can anyone tell me why my change QTY button isnt changing the QTY?
The buttonlistener2 is supposed to change the number of items in arrayCount[x]
to the number in the count JTextfield, but its not, could use a new set of eyes.
thanks all
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class ProduceInventory extends JFrame
{
ArrayList<String> arrayName = new ArrayList<String>();
ArrayList<Integer> arrayCount = new ArrayList<Integer>();
// declares panels and items
private final int WINDOW_WIDTH = 450;
private final int WINDOW_HEIGHT = 350;
private JPanel panel1;
private JPanel panel2;
private JPanel panel3;
private JLabel messageLabel1;
private JLabel messageLabel2;
private JTextField name;
private JTextField count;
private JTextArea output;
private JButton add;
private JButton changeQTY;
private JButton delete;
private JButton clear;
private JButton report;
private JButton save;
private JButton load;
public ProduceInventory()
{
//creates Jframe
setTitle("Produce Inventory");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
panel1(); //build panels
panel2();
panel3();
add(panel1, BorderLayout.NORTH); //add panels
add(panel2, BorderLayout.SOUTH);
add(panel3, BorderLayout.CENTER);
setVisible(true);
}
private void panel1() //builds panel 1
{
messageLabel1 = new JLabel("Name");
messageLabel2 = new JLabel("Count");
name = new JTextField(20);
count = new JTextField(5);
panel1 = new JPanel();
panel1.add(messageLabel1);
panel1.add(name);
panel1.add(messageLabel2);
panel1.add(count);
}
private void panel2() //builds panel 2
{
add = new JButton("Add");
changeQTY = new JButton("CHANGE QTY");
delete = new JButton("Delete");
clear = new JButton("Clear");
report = new JButton("Report");
save = new JButton("Save File");
load = new JButton("Load File");
add.addActionListener(new ButtonListener());
changeQTY.addActionListener(new ButtonListener2());
panel2 = new JPanel();
panel2.setLayout(new GridLayout(2,4));
panel2.add(add);
panel2.add(changeQTY);
panel2.add(delete);
panel2.add(clear);
panel2.add(report);
panel2.add(save);
panel2.add(load);
}
private void panel3() //builds panel 3
{
output = new JTextArea(10,30);
panel3 = new JPanel();
panel3.add(output);
}
private class ButtonListener implements ActionListener //add listener
{
String nameIn;
String countIn;
int number;
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
if (actionCommand.equals("Add"))
{
nameIn = name.getText();
arrayName.add(name.getText());
countIn = count.getText();
number = Integer.parseInt(countIn);
arrayCount.add(number);
output.setText(name.getText() + " " + count.getText() + " Item Added");
for(int x = 0; x <= arrayName.size() - 1; x++)
{
System.out.print((x+1)+ ". " + arrayName.get(x) + " " + arrayCount.get(x) + "\n");
}
}
}
}
private class ButtonListener2 implements ActionListener //add listener
{
public void actionPerformed(ActionEvent e)
{
String nameIn;
String countIn;
int number;
String actionCommand = e.getActionCommand();
if (actionCommand.equals("CHANGE QTY"))
{
nameIn = name.getText();
countIn = count.getText();
number = Integer.parseInt(countIn);
for(int x = 0; x <= arrayName.size() - 1; x++)
{
if(arrayName.get(x) == nameIn)
{
arrayCount.set(x, number);
}
}
output.setText("Qty is updated to: " + number);
for(int x = 0; x <= arrayName.size() - 1; x++)
{
System.out.print((x+1)+ ". " + arrayName.get(x) + " " + arrayCount.get(x) + "\n");
}
}
}
}
public static void main(String[] args)
{
new ProduceInventory(); //runs program
}
}
In the action listener, on the line
if(arrayName.get(x) == nameIn)
you are checking if the two variables refer to the same object. Instead of that you have to check if the objects they refer to are equal:
if(nameIn.equals(arrayName.get(x)))

How do I ask "if there is an exception, then do this" java

I wanted to ask that if an exception occurs, then display a certain String in the textfield. When I try using a try, catch IOException, it gives me an error that cannot have a catch in the same body as a try. This should probably be done in the action performed method.
GUI:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class GUI extends JFrame implements ActionListener
{
JPanel buttonPanel, topPanel, operationPanel;
JTextField display = new JTextField(20);
doMath math = new doMath();
String s = "";
String b= "";
//int counter;
JButton Num1;
JButton Num2;
JButton Num3;
JButton Num4;
JButton Num5;
JButton Num6;
JButton Num7;
JButton Num8;
JButton Num9;
JButton Num0;
JButton Add;
JButton Sub;
JButton Mult;
JButton Div;
JButton Eq;
JButton Clr;
JButton Space;
public GUI()
{
super("Calculator");
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout (2,1));
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(5, 4));
buttonPanel.add(Num1 = new JButton("1"));
buttonPanel.add(Num2 = new JButton("2"));
buttonPanel.add(Num3 = new JButton("3"));
buttonPanel.add(Num4 = new JButton("4"));
buttonPanel.add(Num5 = new JButton("5"));
buttonPanel.add(Num6 = new JButton("6"));
buttonPanel.add(Num7 = new JButton("7"));
buttonPanel.add(Num8 = new JButton("8"));
buttonPanel.add(Num9 = new JButton("9"));
buttonPanel.add(Num0 = new JButton("0"));
buttonPanel.add(Clr = new JButton("C"));
buttonPanel.add(Eq = new JButton("="));
buttonPanel.add(Add = new JButton("+"));
buttonPanel.add(Sub = new JButton("-"));
buttonPanel.add(Mult = new JButton("*"));
buttonPanel.add(Div = new JButton("/"));
buttonPanel.add(Space = new JButton("Space"));
Num1.addActionListener(this);
Num2.addActionListener(this);
Num3.addActionListener(this);
Num4.addActionListener(this);
Num5.addActionListener(this);
Num6.addActionListener(this);
Num7.addActionListener(this);
Num8.addActionListener(this);
Num9.addActionListener(this);
Num0.addActionListener(this);
Clr.addActionListener(this);
Eq.addActionListener(this);
Add.addActionListener(this);
Sub.addActionListener(this);
Mult.addActionListener(this);
Div.addActionListener(this);
Space.addActionListener(this);
topPanel = new JPanel();
topPanel.setLayout(new FlowLayout());
topPanel.add(display);
add(mainPanel);
mainPanel.add(topPanel, BorderLayout.NORTH);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
JButton source = (JButton)e.getSource();
String text = source.getText();
try{
if (text.equals("="))
{
doMath math = new doMath();
b = b.replaceAll("\\s+", " ");
int result = math.doMath1(b);
String answer = ""+result;
display.setText(answer);
}
else if(text.equals("Space"))
{
b+=" ";
display.setText(b);
}
else if (text.equals("C"))
{
b = "";
display.setText(b);
}
else if (text.equals("+") || text.equals("-") || text.equals("*") || text.equals("/"))
{
b += (" "+(text)+ " ");
display.setText(b);
}
else
{
b += (text);
display.setText(b);
}
}
catch(IOException o)
{display.setText(b);}
}
}
When I try using a try, catch IOException, it gives me an error that
cannot have a catch in the same body as a try
The error is self-explanatory. The following code is illegal:
try{
catch(Exception ex){
}
}
You want this:
try{
//stuff i need to do
} //close the try
catch(IOException ioex)
{
//log and recover
}
=UPDATE
Based on the code block below (the same that OP is talking about in case it is changed later) The actual error message that is being displayed is this:
Unreachable catch block for IOException. This exception is never
thrown from the try statement body GUI.java
The reason this occurs is that there is nothing that generates an IOException in your code, the only exception you can define without an explicit throw from one of your functions is the top level Exception.
public class GUI extends JFrame implements ActionListener
{
JPanel buttonPanel, topPanel, operationPanel;
JTextField display = new JTextField(20);
doMath math = new doMath();
String s = "";
String b= "";
//int counter;
JButton Num1;
JButton Num2;
JButton Num3;
JButton Num4;
JButton Num5;
JButton Num6;
JButton Num7;
JButton Num8;
JButton Num9;
JButton Num0;
JButton Add;
JButton Sub;
JButton Mult;
JButton Div;
JButton Eq;
JButton Clr;
JButton Space;
public GUI()
{
super("Calculator");
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout (2,1));
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(5, 4));
buttonPanel.add(Num1 = new JButton("1"));
buttonPanel.add(Num2 = new JButton("2"));
buttonPanel.add(Num3 = new JButton("3"));
buttonPanel.add(Num4 = new JButton("4"));
buttonPanel.add(Num5 = new JButton("5"));
buttonPanel.add(Num6 = new JButton("6"));
buttonPanel.add(Num7 = new JButton("7"));
buttonPanel.add(Num8 = new JButton("8"));
buttonPanel.add(Num9 = new JButton("9"));
buttonPanel.add(Num0 = new JButton("0"));
buttonPanel.add(Clr = new JButton("C"));
buttonPanel.add(Eq = new JButton("="));
buttonPanel.add(Add = new JButton("+"));
buttonPanel.add(Sub = new JButton("-"));
buttonPanel.add(Mult = new JButton("*"));
buttonPanel.add(Div = new JButton("/"));
buttonPanel.add(Space = new JButton("Space"));
Num1.addActionListener(this);
Num2.addActionListener(this);
Num3.addActionListener(this);
Num4.addActionListener(this);
Num5.addActionListener(this);
Num6.addActionListener(this);
Num7.addActionListener(this);
Num8.addActionListener(this);
Num9.addActionListener(this);
Num0.addActionListener(this);
Clr.addActionListener(this);
Eq.addActionListener(this);
Add.addActionListener(this);
Sub.addActionListener(this);
Mult.addActionListener(this);
Div.addActionListener(this);
Space.addActionListener(this);
topPanel = new JPanel();
topPanel.setLayout(new FlowLayout());
topPanel.add(display);
add(mainPanel);
mainPanel.add(topPanel, BorderLayout.NORTH);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
JButton source = (JButton)e.getSource();
String text = source.getText();
try{
if (text.equals("="))
{
doMath math = new doMath();
b = b.replaceAll("\\s+", " ");
int result = math.doMath1(b);
String answer = ""+result;
display.setText(answer);
}
else if(text.equals("Space"))
{
b+=" ";
display.setText(b);
}
else if (text.equals("C"))
{
b = "";
display.setText(b);
}
else if (text.equals("+") || text.equals("-") || text.equals("*") || text.equals("/"))
{
b += (" "+(text)+ " ");
display.setText(b);
}
else
{
b += (text);
display.setText(b);
}
}
catch(IOException o)
{display.setText(b);}
}
}

Categories

Resources