Test to see if JPanel is closed - java

So basically the program will work like this. The first window comes up and asks with 2 buttons whether you want to continue the program or exit the program. if you choose to continue then the program continues on to whatever is in the if statement.
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.*;
import java.awt.*;
import java.util.Scanner;
import java.io.*;
import javax.swing.border.EmptyBorder;
import java.awt.event.*;
public class Herons extends JFrame implements ActionListener {
public static JTextField a;
public static JTextField b;
public static JTextField c;
public static JFrame main = new JFrame("Herons Formula");
public static JPanel myPanel = new JPanel(new GridLayout (0,1));
public static void main(String args[]){
//splashscr();
Herons object = new Herons();
}
Herons(){
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel myPanel1 = new JPanel(new GridBagLayout());
myPanel.setPreferredSize(new Dimension(515,125));
JLabel lab1 = new JLabel(
("Herons Formula uses the lenghts of the sides of a triangle to calculate its area."));
main.add(myPanel);
lab1.setHorizontalAlignment(JLabel.CENTER);
myPanel.add(lab1);
JButton button1 = new JButton("Use the Formula!");
button1.setPreferredSize(new Dimension(20, 20));
JButton button2 = new JButton("Exit the program");
myPanel.add(button1);
myPanel.add(button2);
button1.addActionListener(this);
button2.addActionListener(this);
main.pack();
main.setVisible(true);
//Not really sure what to do with this
if (myPanel1.hasBeenDisposed()){
//JFrame main = new JFrame("Herons Formula");
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//JPanel myPanel = new JPanel(new GridLayout (0,1));
//JPanel pane = new JPanel(new GridLayout(0,1));
myPanel.setPreferredSize(new Dimension(325,275));
a = new JTextField(3);
b = new JTextField(3);
c = new JTextField(3);
JButton find = new JButton("Calculate!");
main.add(myPanel);
myPanel.add(new JLabel ("Input the lengh of each side of the triangle"));
main.add(myPanel);
myPanel.add(new JLabel ("Side A:"));
myPanel.add(a);
myPanel.add(new JLabel ("Side B:"));
myPanel.add(b);
myPanel.add(new JLabel ("Side C:"));
myPanel.add(c);
myPanel.add(find);
//find.setActionCommand("Calculate!");
find.addActionListener(this);
main.pack();
main.setVisible(true);
}
}
public void actionPerformed(ActionEvent e) {
String actionCommand = ((JButton) e.getSource()).getActionCommand();
//System.out.println("Action command for pressed button: " + actionCommand);
if (actionCommand == "Calculate!") {
main.setVisible(false);
myPanel.setVisible(false);
main.dispose();
double aaa = Double.parseDouble(a.getText());
double bbb = Double.parseDouble(b.getText());
double ccc = Double.parseDouble(c.getText());
double s = 0.5 * (aaa + bbb + ccc);
double area = Math.sqrt(s*(s-aaa)*(s-bbb)*(s-ccc));
area = (int)(area*10000+.5)/10000.0;
if (area == 0){
area = 0;
}
JOptionPane.showMessageDialog(this, "The area of the triangle is: " + area,"Herons Formula", JOptionPane.PLAIN_MESSAGE);
}
if (actionCommand == "Use the Formula!" ){
myPanel1.setVisible(false);
}
if (actionCommand == "Exit the program"){
System.exit(0);
}
}
}

Related

Swing-GUI GPA Calculator

I am working on an app which will get info from the user through the buttons and text frames in the MyPanel class. So far that part works. Now I want to display the courses-infos the user entered in the DisplayTable panel. I want it to update each time the add course button in the MyPanel class is pressed. I tried adding a function to DisplayTable to add a label each time the button is pressed but I could not get it to work since one is static and one is not. Any ideas on how to do that?(Or any tips on how to improve the app in general :) )
Class Main
public class Main {
//TODO
// PREVENT TYPE MISMATCH IN TEXT FIELDS
// DISPLAY A TABLE OF COURSE NAMES - COURSE CREDITS - COURSE NAME AND THE GPA
public static void main(String[] args) {
new MyFrame();
}
}
Class MyFrame
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MyFrame extends JFrame{
MainPanel mainPanel;
MyFrame(){
mainPanel = new MainPanel();
this.add(mainPanel);
this.setTitle("GPA Calculator");
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500,500);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
}
Class MainPanel
import javax.swing.*;
public class MainPanel extends JPanel {
MyPanel myPanel = new MyPanel();
DisplayPanel displayPanel = new DisplayPanel();
MainPanel() {
this.add(myPanel);
this.add(displayPanel);
}
}
Class DisplayPanel
import javax.swing.*;
import java.awt.*;
public class DisplayPanel extends JPanel {
static JLabel addLabel = new JLabel();
public DisplayPanel() {
this.setPreferredSize(new Dimension(500, 500));
this.setBackground(new Color(0xEED2CC));
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
}
public static void addElements(String courseName, int courseCredits, double courseGrade) {
addLabel.setText(courseName + " " + courseCredits + " " + courseGrade);
addLabel.setText("");
}
}
Class MyPanel
import javax.swing.*;
import javax.swing.Timer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import java.util.List;
public class MyPanel extends JPanel implements ActionListener{
List<String> courseNames;
List<Integer> courseCredits;
List<Double> courseGrades;
Thread thread;
JLabel nameLabel;
JLabel creditLabel;
JLabel gradeLabel;
JTextField nameField;
JTextField creditField;
JTextField gradeField;
JButton calculateButton;
JButton addCourseButton;
JButton resetButton;
JLabel message;
double result = 0;
int tempInt = 0;
double tempDouble = 0;
MyPanel() {
message = new JLabel();
message.setHorizontalAlignment(JLabel.CENTER);
message.setFont(new Font("Helvetica Neue", Font.PLAIN, 35));
message.setForeground(new Color(0xA1683A));
message.setAlignmentX(JLabel.CENTER_ALIGNMENT);
courseNames = new ArrayList();
courseCredits = new ArrayList();
courseGrades = new ArrayList();
nameLabel = new JLabel();
nameLabel.setHorizontalAlignment(JLabel.CENTER);
nameLabel.setText("Course Name");
nameLabel.setFont(new Font("Helvetica Neue", Font.PLAIN, 25));
nameLabel.setForeground(new Color(0xA1683A));
nameLabel.setAlignmentX(JLabel.CENTER_ALIGNMENT);
nameField = new JTextField();
nameField.setPreferredSize(new Dimension(300,30));
nameField.setMaximumSize(nameField.getPreferredSize());
creditLabel = new JLabel();
creditLabel.setHorizontalAlignment(JLabel.CENTER);
creditLabel.setText("Course Credits(ECTS)");
creditLabel.setFont(new Font("Helvetica Neue", Font.PLAIN, 25));
creditLabel.setForeground(new Color(0xA1683A));
creditLabel.setAlignmentX(JLabel.CENTER_ALIGNMENT);
creditField = new JTextField();
creditField.setPreferredSize(new Dimension(300,30));
creditField.setMaximumSize(creditField.getPreferredSize());
gradeLabel = new JLabel();
gradeLabel.setHorizontalAlignment(JLabel.CENTER);
gradeLabel.setText("Your Grade");
gradeLabel.setFont(new Font("Helvetica Neue", Font.PLAIN, 25));
gradeLabel.setForeground(new Color(0xA1683A));
gradeLabel.setAlignmentX(JLabel.CENTER_ALIGNMENT);
gradeField = new JTextField();
gradeField.setPreferredSize(new Dimension(300,30));
gradeField.setMaximumSize(gradeField.getPreferredSize());
resetButton = new JButton("Reset");
resetButton.setAlignmentX(JLabel.CENTER_ALIGNMENT);
resetButton.addActionListener(this);
addCourseButton = new JButton("Add Course");
addCourseButton.setAlignmentX(JLabel.CENTER_ALIGNMENT);
addCourseButton.addActionListener(this);
calculateButton = new JButton("Calculate GPA");
calculateButton.setAlignmentX(JLabel.CENTER_ALIGNMENT);
calculateButton.addActionListener(this);
//spacing and adding the elements
this.add(Box.createRigidArea(new Dimension(0,20)));
this.add(nameLabel);
this.add(Box.createRigidArea(new Dimension(0,10)));
this.add(nameField);
this.add(Box.createRigidArea(new Dimension(0,20)));
this.add(creditLabel);
this.add(Box.createRigidArea(new Dimension(0,10)));
this.add(creditField);
this.add(Box.createRigidArea(new Dimension(0,20)));
this.add(gradeLabel);
this.add(Box.createRigidArea(new Dimension(0,10)));
this.add(gradeField);
this.add(Box.createRigidArea(new Dimension(0,20)));
this.add(addCourseButton);
this.add(Box.createRigidArea(new Dimension(0,5)));
this.add(calculateButton);
this.add(Box.createRigidArea(new Dimension(0,5)));
this.add(resetButton);
this.add(Box.createRigidArea(new Dimension(0,30)));
this.add(message);
this.setPreferredSize(new Dimension(500, 500));
this.setBackground(new Color(0xEED2CC));
this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
}
//calculate the GPA
public double calculateGPA(){
for (Integer courseCredit : courseCredits) {
tempInt += courseCredit;
}
for(int i = 0; i<courseGrades.size();i++){
tempDouble += courseGrades.get(i) * courseCredits.get(i);
}
return tempDouble/tempInt;
}
//create labels to display on the table
public void createLabel(){
}
#Override
public void actionPerformed(ActionEvent e) throws NumberFormatException {
if(e.getSource().equals(addCourseButton)){
//add items from the textFields to lists
String tempText = nameField.getText();
int tempCredit = Integer.parseInt(creditField.getText());
double tempGrade = Double.parseDouble(gradeField.getText());
courseNames.add(tempText);
courseCredits.add(tempCredit);
courseGrades.add(tempGrade);
//set textFields to empty
nameField.setText("");
creditField.setText("");
gradeField.setText("");
//display a message for 3 seconds
thread = new Thread();
thread.start();
message.setText("Course Added Successfully!");
Timer timer = new Timer(3000, a -> message.setText(null));
timer.setRepeats(false);
timer.start();
//add to table panel
DisplayPanel.addElements(){
}
}
//calculate the GPA, initialize the display panel
//to display the courses names-credits-results and the gpa
//as a table
if(e.getSource().equals(calculateButton)){
result = calculateGPA();
message.setText(result + "");
}
//clear the lists,text fields and the message
//get rid of the table panel
if(e.getSource().equals(resetButton)){
courseNames.clear();
courseGrades.clear();
courseCredits.clear();
nameField.setText("");
creditField.setText("");
gradeField.setText("");
message.setText(null);
}
}
}
You appear to have used static without need.
static JLabel addLabel = new JLabel();
Make the above non-static, (ideally also make private)
public static void addElements
Make the above non static also, rename to something like setLabelText
DisplayPanel displayPanel = new DisplayPanel();
MyPanel myPanel = new MyPanel(displayPanel);
As shown above, pass displayPanel as a parameter to myPanel.
Obviously in MyPanel, you would have one more instance variable:
DisplayPanel displayPanel;
which would be initialized in the constructor, using the constructor argument.
In MyPanel#actionPerformed, instead of:
//add to table panel
DisplayPanel.addElements(){
}
do:
displayPanel.addElements(....);
or rather
displayPanel.setLabelText(...);
invoke the DisplayPanel#setLabelText method on grade calculation and resetting also.
Also invoke the
Finally, remove line:
addLabel.setText("");
If you want DisplayPanel, why then also have the following?
public void createLabel(){

java input JTextfield

I have a problem. The user input(inputUser) must be compared with the random number. Its kinda like a gamble program.
But I dont know how can I compare the input user string and the random number. And after that it is compared the output is in a dialog.
The input of the user comes with a string and the random number comes with a int. I already tried to convert the int to the string. but for some reason it doesnt work.
package gamble;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import java.util.Random;
import java.util.Scanner;
public class Gamble extends JFrame {
public JLabel inputUser;
public JPanel panel;
Font myFont = new Font("Serif", Font.BOLD, 25);
Font rulesFont = new Font("Serif", Font.BOLD, 15);
public static void main(String[] args) {
Gamble GUI = new Gamble();
GUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI.setSize(600, 600);
GUI.setResizable(false);
GUI.setVisible(true);
GUI.setLocationRelativeTo(null);
}
public Gamble(){
super("NUMERO");
JPanel panel = new JPanel();
panel.setLayout(null);
add(panel);
//nieuwe label
JLabel label = new JLabel("Raad het getal");
label.setLayout(null);
label.setBounds(250,10, 300, 30);
label.setFont(myFont);
panel.add(label);
//nieuwe label
JLabel rules = new JLabel("Gok een nummer tot en met 5");
rules.setBounds(225,40,300,30);
rules.setFont(rulesFont);
panel.add(rules);
//nieuw textfield
JTextField inputUser = new JTextField(100);
inputUser.setBounds(275,100,100,30);
inputUser.setFont(rulesFont);
inputUser.setBackground(Color.LIGHT_GRAY );
panel.add(inputUser);
thehandler handler = new thehandler();
inputUser.addActionListener(handler);
}
private class thehandler implements ActionListener {
public void actionPerformed(ActionEvent event){
Random rand = new Random(); //random number
int n = rand.nextInt(5) + 1; //random number wordt gemaakt
int j = Integer.parseInt(inputUser.getText());
if (event.getSource()== inputUser){
if(n == j){
JOptionPane.showMessageDialog(null, "test");
}
}
else {
JOptionPane.showMessageDialog(null, "dfd");
}
}
}
}
There're some problems with the declaration of inputUser, just change the global declaration of it to JTextField and remove the local declaration of it.
The code should looks like below:
class Gamble extends JFrame {
public JTextField inputUser;
public JPanel panel;
Font myFont = new Font("Serif", Font.BOLD, 25);
Font rulesFont = new Font("Serif", Font.BOLD, 15);
public static void main(String[] args) {
Gamble GUI = new Gamble();
GUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI.setSize(600, 600);
GUI.setResizable(false);
GUI.setVisible(true);
GUI.setLocationRelativeTo(null);
}
public Gamble(){
super("NUMERO");
JPanel panel = new JPanel();
panel.setLayout(null);
add(panel);
//nieuwe label
JLabel label = new JLabel("Raad het getal");
label.setLayout(null);
label.setBounds(250,10, 300, 30);
label.setFont(myFont);
panel.add(label);
//nieuwe label
JLabel rules = new JLabel("Gok een nummer tot en met 5");
rules.setBounds(225,40,300,30);
rules.setFont(rulesFont);
panel.add(rules);
//nieuw textfield
inputUser = new JTextField(100);
inputUser.setBounds(275,100,100,30);
inputUser.setFont(rulesFont);
inputUser.setBackground(Color.LIGHT_GRAY );
panel.add(inputUser);
thehandler handler = new thehandler();
inputUser.addActionListener(handler);
}
private class thehandler implements ActionListener {
public void actionPerformed(ActionEvent event){
Random rand = new Random(); //random number
int n = rand.nextInt(5) + 1; //random number wordt gemaakt
int j = Integer.parseInt(inputUser.getText());
if (event.getSource()== inputUser){
if(n == j){
JOptionPane.showMessageDialog(null, "Yep, you're right");
}
else {
JOptionPane.showMessageDialog(null, "Nope nope nope, the number is " + n);
}
}
}
}
}

Why is my first panel running twice?

I am working on my final project and we are making a quiz to find out what kind of parties people like... but I can't get mine to run sequentially and with this right panels!
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.awt.*;
import javax.swing.ImageIcon;
import java.awt.Dimension;
import javax.swing.JPanel;
import java.awt.GridLayout;
import javax.swing.BoxLayout;
import java.awt.Component;
import java.awt.Container;
import javax.swing.JOptionPane;
import java.applet.Applet;
//This class is where we set up all the questions.
class party{
int num_questions = 10;
int panel_number = 0;
int party_score = 0;
JFrame frame = new JFrame();
String AnswerA;
String AnswerB;
String AnswerC;
String AnswerD;
JButton button1;
JButton button2;
JButton button3;
JButton button4;
String target_word;
String user_text;
String label_text;
JLabel question_frame;
JPanel pane;
JPanel panel;
public void image_question(){
//This panel will display four images that the user will choose from.
panel = new JPanel();
panel.setLayout(new BorderLayout());
label_text = "Which party appeals to you the most?";
question_frame = new JLabel(label_text);
question_frame.setFont(new Font("Calibri", Font.PLAIN, 20));
panel.add(question_frame, BorderLayout.NORTH);
button1 = new JButton();
JPanel inner = new JPanel();
inner.setLayout(new GridLayout(0, 2));
button1.setIcon(new ImageIcon("ball.jpg")); //img1
button1.setPreferredSize(new Dimension(100, 100));
button1.setActionCommand("1");
inner.add(button1);
button2 = new JButton();
button2.setIcon(new ImageIcon("christmas_party.jpg"));
button2.setPreferredSize(new Dimension(100, 100));
button2.setActionCommand("2");
inner.add(button2);
button3 = new JButton();
button3.setIcon(new ImageIcon("college_party.jpg"));
button3.setPreferredSize(new Dimension(100, 100));
button3.setActionCommand("3");
inner.add(button3);
button4 = new JButton();
button4.setIcon(new ImageIcon("kid_party.jpg"));
button4.setPreferredSize(new Dimension(100, 100));
button4.setActionCommand("4");
inner.add(button4);
panel.add(inner, BorderLayout.CENTER);
//ImageIcon icon = new ImageIcon("Alex.jpg");
//frame.getContentPane().add(new JLabel(icon), BorderLayout.EAST);
//frame.setVisible(true);
frame.add(panel);
ActionListener al = new click();
button1.addActionListener(al);
button2.addActionListener(al);
button3.addActionListener(al);
button4.addActionListener(al);
frame.setSize(600, 600);
frame.setVisible(true);
frame.setBackground(Color.white);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void multiple_choice_question(){
//This panel displays a 4 answer multiple choice question that they user will choose from.
pane = new JPanel();
pane.setLayout(new BorderLayout());
label_text = "What music would you prefer at a party?";
question_frame = new JLabel(label_text);
pane.add(question_frame, BorderLayout.NORTH);
JPanel center = new JPanel();
GridLayout grid = new GridLayout(0,2);
center.setLayout(grid);
pane.add(center, BorderLayout.CENTER);
AnswerA = "1";
AnswerB = "2";
AnswerC = "3";
AnswerD = "4";
ActionListener al = new click();
addAButton(AnswerA, center, al, "1");
addAButton(AnswerB, center, al, "2");
addAButton(AnswerC, center, al, "3");
addAButton(AnswerD, center, al, "4");
frame.add(pane);
frame.setSize(600, 600);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void input_question(){
//This panel will display a question and chance for the user to input their answer.
user_text = JOptionPane.showInputDialog(null, "Describe your ideal party");
target_word = "music";
if (user_text.indexOf(target_word) >=0){
System.out.println("ho ho ho");
}
}
public void party() {
panel_number++;
if (panel_number == 1){
image_question();
}
if(panel_number == 2){
multiple_choice_question();
}
if(panel_number == 3){
input_question();
}
/* else if (panel_number == 4){
image_question();
}
else if(panel_number == 5){
multiple_choice_question();
}
else if(panel_number == 6){
input_question();
}*/
}
private static void addAButton(String text, Container container, ActionListener al, String actionCommand) {
JButton button = new JButton(text);
button.setAlignmentX(Component.CENTER_ALIGNMENT);
container.add(button);
button.addActionListener(al);
button.setActionCommand(actionCommand);
}
public static void main(String args[]) {
party myGUI = new party();
myGUI.party();
}
class ClassParty{
//This class will read txt documents created by users and suggest a party that everyone would enjoy!
}
class click implements ActionListener{
public void actionPerformed(ActionEvent event){
party partier = new party();
if (event.getActionCommand().equals("1")){
party_score++;
}
else if (event.getActionCommand().equals("2")){
party_score++;
}
else if (event.getActionCommand().equals("3")){
party_score++;
}
else if (event.getActionCommand().equals("4")){
party_score++;
}
System.out.println(panel_number);
frame.dispose();
party();
//System.out.println(party_score);
/* creates a GUI that presents the user with a question with clickable answers that gives you the next question
when you finish answering. It plays jeapordy theme music and has a picture Alex Trabeck. It has a status bar
that tells you how close you are to finishing the program. */
}
}
}
When I run my code it runs the image_question twice and then runs input_question and quits. I can't get the multiple_choice_question to work.
I fixed it using debug and stepping through each command. Debug works great, you should try it. Debug was key because it showed that multiple_choice_question() was actually getting reached, even though the GUI looked like the first GUI. It narrowed down the source of the bug.
public void multiple_choice_question(){
frame=new JFrame(); <----add this and everything seems to be working
pane = new JPanel();
pane.setLayout(new BorderLayout());
label_text = "What music would you prefer at a party?";
...

How do I sum the total amount based on selected checkbox

How can I sum the total amount of all the checkbox I chose?
public class Frame extends JFrame implements ItemListener{
JLabel lbl1=new JLabel("SERVICES");
JLabel price1=new JLabel("100.00");
JLabel price2=new JLabel("200.00");
JLabel price3=new JLabel("300.00");
JCheckBox haircut=new JCheckBox("Hair Cut");
JCheckBox fullcolor=new JCheckBox("Full Color");
JCheckBox hairrebond=new JCheckBox("Hair Rebond");
JPanel first = new JPanel();
JPanel second= new JPanel();
JPanel third = new JPanel();
double price,total;
public Frame(){
FlowLayout flow = (new FlowLayout(FlowLayout.LEFT, 30,30));
add(lbl1);
first.add(hairrebond);
first.add(price1);
second.add(haircut);
second.add(price2);
third.add(fullcolor);
third.add(price3);
add(first);
add(second);
add(third);
setLayout(flow);
setVisible(true);
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void itemStateChanged(ItemEvent e) {
if(hairrebond.isSelected()==true){
price=100;
total += price;
}
if(fullcolor.isSelected()==true){
price=400;
total += price;
}if(haircut.isSelected()==true){
price=500;
total += price;
}
}
public static void main(String args[]){
Frame one = new Frame();
}}
Try this code out. Key is to use a local variable inside itemStateChanged method.
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Frame extends JFrame implements ItemListener {
JLabel lbl1 = new JLabel("SERVICES");
JLabel price1 = new JLabel("100.00");
JLabel price2 = new JLabel("200.00");
JLabel price3 = new JLabel("300.00");
JCheckBox haircut = new JCheckBox("Hair Cut");
JCheckBox fullcolor = new JCheckBox("Full Color");
JCheckBox hairrebond = new JCheckBox("Hair Rebond");
JPanel first = new JPanel();
JPanel second = new JPanel();
JPanel third = new JPanel();
double price, total;
public Frame() {
FlowLayout flow = (new FlowLayout(FlowLayout.LEFT, 30, 30));
add(lbl1);
first.add(hairrebond);
first.add(price1);
second.add(haircut);
second.add(price2);
third.add(fullcolor);
third.add(price3);
add(first);
add(second);
add(third);
setLayout(flow);
setVisible(true);
setSize(600, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
haircut.addItemListener(this);
fullcolor.addItemListener(this);
hairrebond.addItemListener(this);
}
#Override
public void itemStateChanged(ItemEvent e) {
int sum = 0;
if (hairrebond.isSelected() == true) {
sum += 100;
}
if (fullcolor.isSelected() == true) {
sum += 300;
}
if (haircut.isSelected() == true) {
sum += 200;
}
total = sum;
System.out.println(total);
}
public static void main(String args[]) {
Frame one = new Frame();
}
}

How do you get a row of buttons in a fixed position?

I have to make a very simple calculator and the buttons(add, subtract, divide and multiply) need to be below the numbers input and results in a fixed position. In the picture shows what I should have and on the other side it shows what I currently have.
package calculator;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.BorderLayout;
public class Calculator extends JFrame {
private JTextField Number1TxtField;
private JTextField Number2TxtField;
private JTextField ResultTxtField;
private JButton add;
private JButton subtract;
private JButton multiply;
private JButton divide;
public Calculator() { // class for the calculator
setLayout(new FlowLayout(FlowLayout.LEFT,8,10));
add(new JLabel("Number 1"));
Number1TxtField=new JTextField(8); add(Number1TxtField);
add(new JLabel("Number 2"));
Number2TxtField=new JTextField(8);
Number2TxtField=new JTextField(8); add(Number2TxtField);
add(new JLabel("Result"));
ResultTxtField= new JTextField(8); add(ResultTxtField);
ResultTxtField.setEditable(false); add(ResultTxtField);
//new JPanel
add = new JButton("Add"); add(add);
subtract = new JButton ("Subtract"); add(subtract);
multiply = new JButton ("Multiply"); add(multiply);
divide = new JButton ("Divide"); add(divide);
ButtonListener btnlistener = new ButtonListener ();
add.addActionListener(btnlistener);
subtract.addActionListener(btnlistener);
multiply.addActionListener(btnlistener);
divide.addActionListener(btnlistener);
}
class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String num1str = Number1TxtField.getText();
double num1 = Double.parseDouble(num1str );
String num2str = Number2TxtField.getText();
double num2 = Double.parseDouble(num2str );
double result;
if (e.getSource() == add)
result = num1+num2;
else if (e.getSource() == subtract)
result = num1-num2;
else if (e.getSource() == multiply)
result = num1*num2;
else //DivideButton
result = num1/num2;
ResultTxtField.setText(String.valueOf(result));
}
}
public static void main(String[] args) {
Calculator frame = new Calculator();
frame.setTitle("Calculator");
frame.setSize(600,120);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Create two panel: topPanel and buttonsPanel. Add your buttons to the buttonsPanel and add this panel to the CENTER position of the JFrame. Then add your textfields to the topPanel and put topPanel to the NORTH position of the JFrame.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Calculator extends JFrame {
private JTextField Number1TxtField;
private JTextField Number2TxtField;
private JTextField ResultTxtField;
private JButton add;
private JButton subtract;
private JButton multiply;
private JButton divide;
public Calculator() { // class for the calculator
JPanel topPanel = new JPanel();
topPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 8, 5));
topPanel.add(new JLabel("Number 1"));
Number1TxtField = new JTextField(5);
topPanel.add(Number1TxtField);
topPanel.add(new JLabel("Number 2"));
Number2TxtField = new JTextField(5);
topPanel.add(Number2TxtField);
topPanel.add(new JLabel("Result"));
ResultTxtField = new JTextField(8);
topPanel.add(ResultTxtField);
ResultTxtField.setEditable(false);
topPanel.add(ResultTxtField);
// new JPanel
JPanel buttonsPanel = new JPanel();
buttonsPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 8, 5));
add = new JButton("Add");
buttonsPanel.add(add);
subtract = new JButton("Subtract");
buttonsPanel.add(subtract);
multiply = new JButton("Multiply");
buttonsPanel.add(multiply);
divide = new JButton("Divide");
buttonsPanel.add(divide);
ButtonListener btnlistener = new ButtonListener();
add.addActionListener(btnlistener);
subtract.addActionListener(btnlistener);
multiply.addActionListener(btnlistener);
divide.addActionListener(btnlistener);
getContentPane().add(topPanel, BorderLayout.NORTH);
getContentPane().add(buttonsPanel);
}
class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String num1str = Number1TxtField.getText();
double num1 = Double.parseDouble(num1str);
String num2str = Number2TxtField.getText();
double num2 = Double.parseDouble(num2str);
double result;
if (e.getSource() == add)
result = num1 + num2;
else if (e.getSource() == subtract)
result = num1 - num2;
else if (e.getSource() == multiply)
result = num1 * num2;
else // DivideButton
result = num1 / num2;
ResultTxtField.setText(String.valueOf(result));
}
}
public static void main(String[] args) {
Calculator frame = new Calculator();
frame.setTitle("Calculator");
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Categories

Resources