How do I sum the total amount based on selected checkbox - java

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

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(){

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

Changing panels in gui

What I am trying to do is change the right side of my GUI each time I press a button. First button shows a JLabel second button a JTextField. Expected outcome change in panels. Outcome is that when I press the buttons nothing happens.
package javaapplication37;
import java.awt.GridLayout;
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.*;
public class Gui extends JFrame {
JTextField f1;
JPanel b, p1, p2;
JPanel p3;
JLabel l1;
JButton b2, b1;
String a;
public Gui() {
a="Input here";
setSize(600,600);
l1=new JLabel("8a petuxei");
b = new JPanel();
p3 = new JPanel();
p1 = new JPanel();
p2 = new JPanel();
b.setLayout(new GridLayout(2, 1));
b1 = new JButton("Eleos");
b2 = new JButton("elpizw");
b.add(b1);
b.add(b2);
b.setSize(150,600);
p1.setSize(450,600);
add(b);
add(p1);
ActionListener pou = new Listener(p1);
b1.addActionListener(pou);
p2.add(l1);
f1=new JTextField(a);
a=f1.getText();
p3.add(f1);
}
public class Listener implements ActionListener {
JPanel k;
public Listener(JPanel k) {
this.k = k;
}
#Override
public void actionPerformed(ActionEvent e) {
k.remove(getContentPane());
k.add(p2);
}
}
public class l implements ActionListener {
JPanel k;
public l(JPanel k) {
this.k = k;
}
#Override
public void actionPerformed(ActionEvent e) {
k.remove(getContentPane());
k.add(p3);
}
}
}
You need to be using a CardLayout. If you need help ask me.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
public class Gui extends JFrame implements ActionListener {
private JPanel menu = new JPanel();
private CardLayout contentLayout = new CardLayout();
private JPanel content = new JPanel(contentLayout);
private java.util.List<Card> cardList = new ArrayList<>();
public Gui() {
int i;
for (i = 0; i < 10; i++) {
Card card;
if(i % 2 == 0) card = new TextAreaCard("Card " + i, "this is the content for card #" + i);
else card = new LabelCard("Card " + i, "content for Label Card #" + i);
JButton btn = new JButton(card.name);
menu.add(btn);
btn.addActionListener(this);
content.add(card, card.name);
cardList.add(card);
}
menu.setLayout(new GridLayout(i, 1));
add(menu, BorderLayout.WEST);
add(content, BorderLayout.CENTER);
}
#Override
public void actionPerformed(ActionEvent e) {
contentLayout.show(content, e.getActionCommand());
}
class Card extends JPanel{
final String name;
public Card(String name){
this.name = name;
}
}
class TextAreaCard extends Card implements ActionListener {
JTextArea textArea = new JTextArea();
JButton btn = new JButton("OK");
public TextAreaCard(String name, String text) {
super(name);
textArea.setText(text);
setLayout(new BorderLayout());
add(textArea, BorderLayout.CENTER);
add(btn, BorderLayout.SOUTH);
btn.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(this, textArea.getText(), "click OK", JOptionPane.NO_OPTION);
}
}
class LabelCard extends Card{
JLabel label = new JLabel();
public LabelCard(String name, String text) {
super(name);
label.setText(text);
add(label);
}
}
public static void main(String [] args){
Gui gui = new Gui();
gui.setSize(600, 500);
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setVisible(true);
}
}

why is repaint() not working?

I am trying to add the buttons to the centerPanel that I created, then add that panel to the main center borderlayout. for some reason though my tab will not repaint anymore. It worked fine a while ago when I had the DrawFieldsListener class in the same class file as the MagicSquare, but nothing in the code has changed from my splitting them into two class files. So i really don't know what is going on. When it did repaint before, it would also take a long time. Any help? thanks!
All source for the project is on GitHub if it is easier to read and understand there: https://github.com/andrefecto/Academic-Convivium-Project
MagicSquare Class:
package magicSquare;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MagicSquare extends JPanel {
JLabel sizeLabel = new JLabel("Enter A Square Size: ");
JButton setSize;
static JButton calculate;
static JButton reset;
static JTextField squareSize;
static JTextField field;
public static ArrayList<JTextField> inputFields = new ArrayList<JTextField>();
public static ArrayList<Integer> inputs = new ArrayList<Integer>();
public static ArrayList<Integer> totals = new ArrayList<Integer>();
public static int squared = 0;
public static int square = 0;
public static JPanel centerPanel = new JPanel();
public static JPanel bottomPanel = new JPanel();
public MagicSquare (){
setLayout(new BorderLayout());
JPanel subPanel = new JPanel();
subPanel.add(sizeLabel);
squareSize = new JTextField();
squareSize.setColumns(6);
subPanel.add(squareSize);
setSize = new JButton("Enter");
subPanel.add(setSize);
setSize.addActionListener(new DrawFieldsListener());
add(subPanel, BorderLayout.NORTH);
add(new DrawFieldsListener(), BorderLayout.CENTER);
}
}
my DrawFieldsListener class:
package magicSquare;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
class DrawFieldsListener extends JPanel implements ActionListener {
int square = MagicSquare.square;
int squared = MagicSquare.squared;
JPanel centerPanel = MagicSquare.centerPanel;
JTextField squareSize = MagicSquare.squareSize;
JTextField field = MagicSquare.field;
ArrayList<JTextField> inputFields = MagicSquare.inputFields;
JButton calculate = MagicSquare.calculate;
JButton reset = MagicSquare.reset;
JPanel bottomPanel = MagicSquare.bottomPanel;
public void actionPerformed(ActionEvent e){
square = Integer.parseInt(squareSize.getText());
squared = square*square;
centerPanel.setLayout(new GridLayout(square, square));
for(int i = 0; i < squared; i++){
field = new JTextField();
field.setColumns(3);
inputFields.add(field);
centerPanel.add(inputFields.get(i));
System.out.println("DRAWING");
}
add(centerPanel, BorderLayout.CENTER);
System.out.println("ADDING ADDITINOAL BUTTONS");
additionalButtons();
System.out.println("ADDED ADDITINOAL BUTTONS");
System.out.println("REPAINTING");
repaint();
System.out.println("REPAINTED");
}
public void additionalButtons(){
calculate = new JButton("Calculate");
reset = new JButton("Reset");
bottomPanel.setLayout(new GridLayout(2, 2));
bottomPanel.add(reset);
bottomPanel.add(calculate);
add(bottomPanel, BorderLayout.SOUTH);
calculate.addActionListener(new CalculateListener());
reset.addActionListener(new ResetListener());
}
}
Mistake #1
public static JPanel centerPanel = new JPanel();
Followed by...
class DrawFieldsListener extends JPanel implements ActionListener {
//...
JPanel centerPanel = MagicSquare.centerPanel;
static is not a cross object communication mechanism...and now I have no idea who is suppose to be responsible for managing the centerPanel...
Remember, static is not your friend, beware of how it is used
Mistake #2
setSize.addActionListener(new DrawFieldsListener());
add(subPanel, BorderLayout.NORTH);
add(new DrawFieldsListener(), BorderLayout.CENTER);
You are creating two instances of DrawFieldsListener (which is a panel), one is acting as the ActionListener and one is acting as the view, but which one is actually housing MagicSquare.centerPanel as a component can only have one parent...
Mistake #3
Not revalidating the container after you have changed it...
public void actionPerformed(ActionEvent e) {
square = Integer.parseInt(squareSize.getText());
squared = square * square;
centerPanel.setLayout(new GridLayout(square, square));
for (int i = 0; i < squared; i++) {
field = new JTextField();
field.setColumns(3);
inputFields.add(field);
centerPanel.add(inputFields.get(i));
System.out.println("DRAWING");
}
add(centerPanel, BorderLayout.CENTER);
System.out.println("ADDING ADDITINOAL BUTTONS");
additionalButtons();
System.out.println("ADDED ADDITINOAL BUTTONS");
System.out.println("REPAINTING");
revalidate();
repaint();
System.out.println("REPAINTED");
}
Swing is lazy when it comes to container management, it assumes that you will want to do a number of adds or removes, so it won't update the container hierarchy layout until you ask it to, as the operation can be expensive
A better solution...
Isolate responsibility and provide information to your objects in a de-coupled manner.
For example, the DrawFieldsListener shouldn't care about MagicSquare, but should provide a means by which "some body" can tell it how many squares it should create.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MagicSquare extends JPanel {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new MagicSquare());
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
JLabel sizeLabel = new JLabel("Enter A Square Size: ");
JButton setSize;
private JSpinner squareSize;
JTextField field;
public MagicSquare() {
setLayout(new BorderLayout());
JPanel subPanel = new JPanel();
subPanel.add(sizeLabel);
squareSize = new JSpinner();
subPanel.add(squareSize);
setSize = new JButton("Enter");
subPanel.add(setSize);
DrawFieldsListener dfl = new DrawFieldsListener();
setSize.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int gridSize = (int) squareSize.getValue();
dfl.makeGrid(gridSize);
}
});
add(subPanel, BorderLayout.NORTH);
add(dfl, BorderLayout.CENTER);
}
class DrawFieldsListener extends JPanel {
private JButton calculate;
private JButton reset;
private ArrayList<JTextField> inputFields = new ArrayList<JTextField>();
private ArrayList<Integer> inputs = new ArrayList<Integer>();
private ArrayList<Integer> totals = new ArrayList<Integer>();
private int squared = 0;
private int square = 0;
private JPanel centerPanel = new JPanel();
private JPanel bottomPanel = new JPanel();
public void makeGrid(int gridSize) {
square = gridSize;
squared = square * square;
centerPanel.setLayout(new GridLayout(square, square));
for (int i = 0; i < squared; i++) {
field = new JTextField();
field.setColumns(3);
inputFields.add(field);
centerPanel.add(inputFields.get(i));
System.out.println("DRAWING");
}
add(centerPanel, BorderLayout.CENTER);
System.out.println("ADDING ADDITINOAL BUTTONS");
additionalButtons();
System.out.println("ADDED ADDITINOAL BUTTONS");
System.out.println("REPAINTING");
revalidate();
repaint();
System.out.println("REPAINTED");
}
public void additionalButtons() {
calculate = new JButton("Calculate");
reset = new JButton("Reset");
bottomPanel.setLayout(new GridLayout(2, 2));
bottomPanel.add(reset);
bottomPanel.add(calculate);
add(bottomPanel, BorderLayout.SOUTH);
// calculate.addActionListener(new CalculateListener());
// reset.addActionListener(new ResetListener());
}
}
}

Test to see if JPanel is closed

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

Categories

Resources