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.
Related
I'm trying to build my own calculator from scratch.
When i run my program as it is now, some of the buttons don't show up, until i hover over them with my cursor, and my bounds are all f'ed up. However when i move window.setVisible(true); to the beginning of my constructer, every bound of all the objects are placed correctly, but all my objects only show once moused-over.
package guitest;
import java.awt.Color;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import static javax.swing.JFrame.*;
public class Frame implements ActionListener{
public static int Calculator(int n1, int n2){
return n1 + n2;
}
JTextField num1,num2,ans;
JButton calculate, add, sub, pro, div;
JPanel textFields, actions;
Frame(){
//Window is being created.
JFrame window = new JFrame("Calculator");
window.setDefaultCloseOperation(EXIT_ON_CLOSE);
window.setResizable(false);
window.setSize(400, 400);
//Creating panel
textFields = new JPanel();
actions = new JPanel();
//Adjusting JPanel
textFields.setBounds(0, 0, 240, 400);
actions.setBounds(240, 0, 160, 400);
//Creating textfields.
num1 = new JTextField("Number 1");
num2 = new JTextField("Number 2");
ans = new JTextField("Answer");
ans.setEditable(false);
//Creating calculate button.
calculate = new JButton("Calclulate");
add = new JButton("+");
sub = new JButton("-");
pro = new JButton("*");
div = new JButton("/");
//adjusting TextFields to my window
num1.setBounds(30, 20, 200, 20);
num2.setBounds(30, 60, 200, 20);
ans.setBounds(30,100,200,20);
//adjusting Buttons to my window
calculate.setBounds(30, 140, 90, 30);
add.setBounds(20, 20, 50, 50);
sub.setBounds(75, 20, 50, 50);
pro.setBounds(20, 75, 50, 50);
div.setBounds(75, 75, 50, 50);
calculate.addActionListener(this);
//adding to my window
textFields.add(num1);textFields.add(num2);textFields.add(ans);textFields.add(calculate);
actions.add(add);actions.add(sub);actions.add(pro);actions.add(div);
window.add(textFields);window.add(actions);
window.setVisible(true);
//Setting everything visible
//textFields.setVisible(true);actions.setVisible(true);
//num1.setVisible(true);num2.setVisible(true);ans.setVisible(true);
//calculate.setVisible(true);add.setVisible(true);sub.setVisible(true);pro.setVisible(true);div.setVisible(true);
}
public void actionPerformed(ActionEvent e){
String n1 = num1.getText();
String n2 = num2.getText();
int a = Integer.parseInt(n1);
int b = Integer.parseInt(n2);
int c;
c = Calculator(a,b);
String result = String.valueOf(c);
ans.setText(result);
}
public static void main(String[] args) {
new Frame();
}
}
when window.setVisible(true); is in the bottom.
when window.setVisible(true); is at the top.
How it is supposed to look. (i've hovered over all my objects manually.)
I changed your code and use layouts instead of setBouds().
Swing provide different LayoutManagers and these are used to arrange components in a particular manner. following classes are used to represents the layout managers in Swing:
1) java.awt.BorderLayout
2) java.awt.FlowLayout
3) java.awt.GridLayout
4) java.awt.CardLayout
5) java.awt.GridBagLayout
6) javax.swing.BoxLayout
7) javax.swing.GroupLayout
8) javax.swing.ScrollPaneLayout
9) javax.swing.SpringLayout etc.
each of them will arrange your components in specific order, which you can read more about it in here (more details...)
public class Frame implements ActionListener {
public static int Calculator(int n1, int n2) {
return n1 + n2;
}
JTextField num1, num2, ans;
JButton calculate, add, sub, pro, div;
JPanel textFields, actions;
Frame() {
// Window is being created.
JFrame window = new JFrame("Calculator");
window.setDefaultCloseOperation(EXIT_ON_CLOSE);
window.setResizable(false);
window.setSize(400, 400);
window.setLayout(new BorderLayout());
// Creating panel
// Creating textfields.
num1 = new JTextField("Number 1");
num2 = new JTextField("Number 2");
ans = new JTextField("Answer");
ans.setEditable(false);
// Creating calculate button.
calculate = new JButton("Calclulate");
add = new JButton("+");
sub = new JButton("-");
pro = new JButton("*");
div = new JButton("/");
calculate.addActionListener(this);
textFields = new JPanel();
actions = new JPanel();
GridLayout txtBox = new GridLayout(4, 1);
txtBox.setVgap(20);
textFields.setLayout(txtBox);
GridLayout actionBox = new GridLayout(2, 2);
actions.setLayout(actionBox);
actions.setPreferredSize(new Dimension(100, 100));
// adding to my window
textFields.add(num1);
textFields.add(num2);
textFields.add(ans);
textFields.add(calculate);
actions.add(add);
actions.add(sub);
actions.add(pro);
actions.add(div);
window.setLayout(new FlowLayout());
window.add(textFields);
window.add(actions);
window.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String n1 = num1.getText();
String n2 = num2.getText();
int a = Integer.parseInt(n1);
int b = Integer.parseInt(n2);
int c;
c = Calculator(a, b);
String result = String.valueOf(c);
ans.setText(result);
}
public static void main(String[] args) {
new Frame();
}
}
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.
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));
}
I am trying to make the text field for quiz_7 set up, however, it is not showning up like the remaning six, i tried putting an parameter as 360, no text field. Changed it 340, but i only see half a textfield.
import java.awt.Container;
import javax.swing.*;
public class QuizEntry {
JPanel textPanel,panelForTextFields;
JLabel Entry_for_Quizes, quiz1, quiz2, quiz3, quiz4, quiz5, quiz6;
JTextField quiz_1, quiz_2, quiz_3, quiz_4, quiz_5, quiz_6;
JTextField quiz_7;
private JLabel quiz7;
public JPanel createContentPane() {
// We create a bottom JPanel to place everything on.
JPanel totalGUI1 = new JPanel();
totalGUI1.setLayout(null);
Entry_for_Quizes = new JLabel("Quiz Entry ");
Entry_for_Quizes.setLocation(0, 0);
Entry_for_Quizes.setSize(400, 400);
Entry_for_Quizes.setHorizontalAlignment(4);
totalGUI1.add(Entry_for_Quizes);
// Creation of a Panel to contain the JLabels
textPanel = new JPanel();
textPanel.setLayout(null);
textPanel.setLocation(10, 35);
textPanel.setSize(100, 600);
totalGUI1.add(textPanel);
// Username Label
quiz1 = new JLabel("Quiz 1");
quiz1.setLocation(-20, 0);
quiz1.setSize(70, 40);
quiz1.setHorizontalAlignment(4);
textPanel.add(quiz1);
// Login Label
quiz2 = new JLabel("Quiz 2");
quiz2.setLocation(-20, 60);
quiz2.setSize(70, 40);
quiz2.setHorizontalAlignment(4);
textPanel.add(quiz2);
// Username Label
quiz3 = new JLabel("Quiz 3");
quiz3.setLocation(-20, 120);
quiz3.setSize(70, 40);
quiz3.setHorizontalAlignment(4);
textPanel.add(quiz3);
// Login Label
quiz4 = new JLabel("Quiz 4");
quiz4.setLocation(-20, 180);
quiz4.setSize(70, 40);
quiz4.setHorizontalAlignment(4);
textPanel.add(quiz4);
// Username Label
quiz5 = new JLabel("Quiz 5");
quiz5.setLocation(-20, 240);
quiz5.setSize(70, 40);
quiz5.setHorizontalAlignment(4);
textPanel.add(quiz5);
// L
quiz6 = new JLabel("Quiz 6");
quiz6.setLocation(-20, 300);
quiz6.setSize(70, 40);
quiz6.setHorizontalAlignment(4);
textPanel.add(quiz6);
quiz7 = new JLabel("Quiz 7");
quiz7.setLocation(-20, 350);
quiz7.setSize(70, 40);
quiz7.setHorizontalAlignment(4);
textPanel.add(quiz7);
//////////////////////////////////////////////////////////////
panelForTextFields = new JPanel();
panelForTextFields.setLayout(null);
panelForTextFields.setLocation(110, 40);
panelForTextFields.setSize(100, 350);
totalGUI1.add(panelForTextFields);
// quiz Textfield
quiz_1 = new JTextField(8);
quiz_1.setLocation(0, 0);
quiz_1.setSize(100, 30);
panelForTextFields.add(quiz_1);
quiz_2 = new JTextField(8);
quiz_2.setLocation(0, 60);
quiz_2.setSize(100, 30);
panelForTextFields.add(quiz_2);
quiz_3 = new JTextField(8);
quiz_3.setLocation(0, 120);
quiz_3.setSize(100, 30);
panelForTextFields.add(quiz_3);
quiz_4 = new JTextField(8);
quiz_4.setLocation(0, 180);
quiz_4.setSize(100, 30);
panelForTextFields.add(quiz_4);
quiz_5 = new JTextField(8);
quiz_5.setLocation(0, 240);
quiz_5.setSize(100, 30);
panelForTextFields.add(quiz_5);
quiz_6 = new JTextField(8);
quiz_6.setLocation(0, 300);
quiz_6.setSize(100, 30);
panelForTextFields.add(quiz_6);
quiz_7 = new JTextField(8);
quiz_7.setLocation(0, 340);
quiz_7.setSize(100, 30);
panelForTextFields.add(quiz_7);
return totalGUI1;
}
private static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Quiz Entry");
QuizEntry demo = new QuizEntry();
frame.setContentPane(demo.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700, 700);
frame.setVisible(true);
}
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Basically change size: for panelForTextFields. From 350 to 500 for example.
To make code a bit generic I would write something like:
panelForTextFields.setSize(100, 6*80);
where 6 is count of JTextFields.
If we will go further, I would create list of JTextField like:
List<JTextField> list = new ArrayList<JTextField>();
list.add(quiz_1);
list.add(quiz_2);
list.add(quiz_3);
list.add(quiz_4);
list.add(quiz_5);
list.add(quiz_6);
and after would write:
final int GAP = 40;
panelForTextFields.setSize(100, 6*( quiz_1.getHeight() + GAP));
Since you used the same logic to configure JTextfields you can use now list like:
quiz_1 = new JTextField(8);
panelForTextFields.add(quiz_1);
quiz_2 = new JTextField(8);
panelForTextFields.add(quiz_2);
quiz_3 = new JTextField(8);
panelForTextFields.add(quiz_3);
quiz_4 = new JTextField(8);
panelForTextFields.add(quiz_4);
quiz_5 = new JTextField(8);
panelForTextFields.add(quiz_5);
quiz_6 = new JTextField(8);
panelForTextFields.add(quiz_6);
quiz_7 = new JTextField(8);
panelForTextFields.add(quiz_7);
list.add(quiz_1);
list.add(quiz_2);
list.add(quiz_3);
list.add(quiz_4);
list.add(quiz_5);
list.add(quiz_6);
list.add(quiz_7);
for(int k = 0; k<list.size(); k++){
JTextField f = list.get(k);
f.setLocation(0, k*60);
f.setSize(100, 30);
}
final int GAP = 40;
panelForTextFields.setSize(100, 6*( quiz_1.getHeight() + GAP));
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);}
}
}