How to make my JButton connect with my JFrame? - java

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.

Related

Java swing GUI error

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 + ".");

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

JLabel not appearing on panel

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));
}

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;
}
}

java beginner calculator not compiling

I am a java beginner and I've just made my first calculator but it is not compiling. It is showing some problems during compilation, at frame.setPreferredSize(new Dimension(200, 250)); and frame.setDefaultCloserOperation(JFrame.EXIT_ON_CLOSE):
These errors are being shown as <identifier> expected and illegal start of expression. What is the problem?
import java.sql.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.awt.*;
public class Cal extends JFrame implements ActionListener
{
JFrame frame = new JFrame();
frame.setPreferredSize(new Dimension(200, 250));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
public Cal(){
Button btn_1 = new Button("1");
btn_1.setSize(5, 5);
Button btn_2 = new Button("2");
btn_2.setSize(5, 5);
Button btn_3 = new Button("3");
btn_3.setSize(5, 5);
Button btn_4 = new Button("4");
btn_4.setSize(5, 5);
Button btn_5 = new Button("5");
btn_5.setSize(5, 5);
Button btn_6 = new Button("6");
btn_6.setSize(5, 5);
Button btn_7 = new Button("7");
btn_7.setSize(5, 5);
Button btn_8 = new Button("8");
btn_8.setSize(5, 5);
Button btn_9 = new Button("9");
btn_9.setSize(5, 5);
Button btn_0 = new Button("0");
btn_0.setSize(5, 5);
Button btn_dot = new Button(".");
btn_dot.setSize(5, 5);
Button btn_div = new Button("/");
btn_div.setSize(5, 5);
Button btn_mult = new Button("*");
btn_mult.setSize(5, 5);
Button btn_sub = new Button("-");
btn_sub.setSize(5, 5);
Button btn_addd = new Button("+");
btn_addd.setSize(5, 5);
Button btn_equ = new Button("=");
btn_equ.setSize(5, 5);
JTextField jt = new JTextField();
jt.setHorizontalAlignment(JTextField.RIGHT);
jt.setEditable(false);
double fnum, snum, total;
String op = null;
JPanel players = new JPanel();
players.setLayout(new GridLayout(1, 1));
players.add(jt, BorderLayout.NORTH);
players.setPreferredSize(new Dimension(10, 50));
JPanel players1 = new JPanel(new GridLayout(4, 3)); // adding buttons
players1.add(btn_7);
players1.add(btn_8);
players1.add(btn_9);
players1.add(btn_div);
players1.add(btn_4);
players1.add(btn_5);
players1.add(btn_6);
players1.add(btn_mult);
players1.add(btn_1);
players1.add(btn_2);
players1.add(btn_3);
players1.add(btn_sub);
players1.add(btn_0);
players1.add(btn_dot);
players1.add(btn_equ);
players1.add(btn_addd);
players1.setPreferredSize(new Dimension(150, 150));
//applying actionlistener
btn_1.addActionListener(this);
btn_2.addActionListener(this);
btn_3.addActionListener(this);
btn_4.addActionListener(this);
btn_5.addActionListener(this);
btn_6.addActionListener(this);
btn_7.addActionListener(this);
btn_8.addActionListener(this);
btn_9.addActionListener(this);
btn_0.addActionListener(this);
btn_dot.addActionListener(this);
btn_addd.addActionListener(this);
btn_mult.addActionListener(this);
btn_div.addActionListener(this);
btn_sub.addActionListener(this);
btn_equ.addActionListener(this);
//setting contents to be available
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
frame.setContentPane(content);
content.add(players, BorderLayout.NORTH);
content.add(players1, BorderLayout.SOUTH);
frame.setTitle("Calculator");
frame.pack();
frame.setVisible(true);
}
//applying actions to be performed
public void actionPerformed(ActionListener e){
String input = jt.getText();
if(e.getSource()==btn_1)
{jt.setText(input + "1");}
else if(e.getSource()==btn_2)
{jt.setText(input + "2");}
else if(e.getSource()==btn_3)
{jt.setText(input + "3");}
else if(e.getSource()==btn_4)
{jt.setText(input + "4");}
else if(e.getSource()==btn_5)
{jt.setText(input + "5");}
else if(e.getSource()==btn_6)
{jt.setText(input + "6");}
else if(e.getSource()==btn_7)
{jt.setText(input + "7");}
else if(e.getSource()==btn_8)
{jt.setText(input + "8");}
else if(e.getSource()==btn_9)
{jt.setText(input + "9");}
else if(e.getSource()==btn_0)
{jt.setText(input + "0");}
else if(e.getSource()==btn_dot)
{jt.setText(input + ".");}
else if(e.getSource()==btn_addd)
{
fnum = Double.parseDouble(jt.getText());
op = "+";
jt.setText(" ");
}
else if(e.getSource()==btn_sub)
{
fnum = Double.parseDouble(jt.getText());
op = "-";
jt.setText(" ");
}
else if(e.getSource()==btn_div)
{
fnum = Double.parseDouble(jt.getText());
op = "/";
jt.setText(" ");
}
else if(e.getSource()==btn_equ)
{
snum = Double.parseDouble(jt.getText());
if(op.equ("+"))
{
total = fnum + snum;
}
if(op.equ("-"))
{
total = fnum - snum;
}
if(op.equ("*"))
{
total = fnum * snum;
}
if(op.equ("/"))
{
total = fnum / snum;
}
jt.setText(" " + total);
}
}
public static void main(String args[]){
Cal obj = new Cal(); }
}
i think you need to put
frame.setPreferredSize(new Dimension(200, 250));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
inside the Cal() constructor
and about Button and other variables , define it outside the constructor ,Like that:
class Cal extends JFrame implements ActionListener {
JFrame frame = new JFrame();
JTextField jt = new JTextField();
Button btn_1 = new Button("1");
Button btn_2 = new Button("2");
.....
JPanel players1 = new JPanel(new GridLayout(4, 3)); // adding buttons
....
and e is ActionEvent not ActionListener Like this :
public void actionPerformed(ActionEvent e) {...}
and there is no equ method in String class it should be if (op.equals("+")) {}
You are trying to make modifications or execute statements out side of the context of an executable context.
You can only make declarations and assign default values to variables out side of methods and constructors
Move
frame.setPreferredSize(new Dimension(200, 250));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
To within the context of the classes constructor
public Cal(){
frame.setPreferredSize(new Dimension(200, 250));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Updated
You are having a number of reference issues. You are define objects within the constructor that you are then wanting to access else where in you code. There is no context for these variables out side of the constructor. Instead, you should be declaring them at the class level, so that they are visible to the whole class.
public class Cal extends JFrame implements ActionListener
{
private JFrame frame = new JFrame();
private Button btn_1 = new Button("1");
private Button btn_2 = new Button("2");
private Button btn_3 = new Button("3");
private Button btn_4 = new Button("4");
private Button btn_5 = new Button("5");
private Button btn_6 = new Button("6");
private Button btn_7 = new Button("7");
private Button btn_8 = new Button("8");
private Button btn_9 = new Button("9");
private Button btn_0 = new Button("0");
private Button btn_dot = new Button(".");
private Button btn_div = new Button("/");
private Button btn_mult = new Button("*");
private Button btn_sub = new Button("-");
private Button btn_addd = new Button("+");
private Button btn_equ = new Button("=");
private JTextField jt = new JTextField();
public Cal(){
frame.setPreferredSize(new Dimension(200, 250));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// This is a bad idea, the layout manager will make these calls redudent...
btn_1.setSize(5, 5);
btn_2.setSize(5, 5);
btn_3.setSize(5, 5);
btn_4.setSize(5, 5);
btn_5.setSize(5, 5);
btn_6.setSize(5, 5);
btn_7.setSize(5, 5);
btn_8.setSize(5, 5);
btn_9.setSize(5, 5);
btn_0.setSize(5, 5);
btn_dot.setSize(5, 5);
btn_div.setSize(5, 5);
btn_mult.setSize(5, 5);
btn_sub.setSize(5, 5);
btn_addd.setSize(5, 5);
btn_equ.setSize(5, 5);
jt.setHorizontalAlignment(JTextField.RIGHT);
jt.setEditable(false);
double fnum, snum, total;
String op = null;
JPanel players = new JPanel();
players.setLayout(new GridLayout(1, 1));
players.add(jt, BorderLayout.NORTH);
players.setPreferredSize(new Dimension(10, 50));
JPanel players1 = new JPanel(new GridLayout(4, 3)); // adding buttons
players1.add(btn_7);
players1.add(btn_8);
players1.add(btn_9);
players1.add(btn_div);
players1.add(btn_4);
players1.add(btn_5);
players1.add(btn_6);
players1.add(btn_mult);
players1.add(btn_1);
players1.add(btn_2);
players1.add(btn_3);
players1.add(btn_sub);
players1.add(btn_0);
players1.add(btn_dot);
players1.add(btn_equ);
players1.add(btn_addd);
players1.setPreferredSize(new Dimension(150, 150));
You are also mixing heavy and light weight components, this is never a good idea. Use JButton instead of Button
I think frame.setPreferredSize(new Dimension(200, 250)); and frame.setDefaultCloserOperation(JFrame.EXIT_ON_CLOSE): need to be inside a method. Commands always need to be inside of methods.

Categories

Resources