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);
}
}
Related
I simply need to have two JTextFields that take in two numbers and when clicking the Multiply or Divide button it produces the answer. It looks good to me, but not good enough to work.. Please any help would be greatly appreciated.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener {
String result;
JLabel introduction = new JLabel("Solve Math Problems");
Font myFont = new Font("Arial", Font.BOLD, 16);
JTextField jtNum1 = new JTextField(10);
JTextField jtNum2 = new JTextField(10);
JTextField jtResponse = new JTextField(10);
JButton multiply = new JButton(" X ");
JButton divide = new JButton(" / ");
JLabel answer = new JLabel("");
final int WIDTH = 400;
final int HEIGHT = 135;
public Calculator(){
super("My First Calculator");
setLayout(new FlowLayout());
setSize(WIDTH, HEIGHT);
introduction.setFont(myFont);
answer.setFont(myFont);
add(introduction);
add(jtNum1);
add(jtNum2);
add(multiply);
add(divide);
multiply.addActionListener(this);
divide.addActionListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e) {
int int1 = Integer.parseInt(jtNum1.getText());
int int2 = Integer.parseInt(jtNum2.getText());
if (e.getSource() == multiply) {
jtResponse.setText(String.valueOf(int1*int2));
} else if (e.getSource() == divide) {
jtResponse.setText(String.valueOf(int1/int2));
System.out.println(jtResponse);
}
}
}
public class CalculatorAction {
public static void main(String[] args) {
Calculator frame = new Calculator();
frame.setVisible(true);
}
}
You must add the action listener to the button.
jbutton.addActionListener(new ActionListener()
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();
}
}
I am writing a stock control system program for a school project. This is the last thing I need to do, but seeing as I am a relative Java noob, I kindly request your assistance.
I have a DisplayRecord class, which is created by taking String input from a "search" JTextField in the Search class, finding the Object (Product p) it's linked to, and passing it to the displayRecord method. This part works perfectly.
I want to take that Product p and pass it to the EditProduct class or the DeleteRecord class (depending on the JButton pressed) so the user can then edit the Name, Quantity or Cost of that same Product. Here are my DisplayRecord, EditProduct and DeleteRecord classes. I have no idea what to do.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
public class DisplayRecord extends JFrame implements ActionListener {
final private StockList stocks;
final private ArrayList<Product> list;
JFrame showWindow;
private JPanel top, bot;
private JPanel barcodePanel1 = new JPanel();
private JPanel barcodePanel2 = new JPanel();
private JPanel namePanel1 = new JPanel();
private JPanel namePanel2 = new JPanel();
private JPanel descPanel1 = new JPanel();
private JPanel descPanel2 = new JPanel();
private JPanel compPanel1 = new JPanel();
private JPanel compPanel2 = new JPanel();
private JPanel ratingPanel1 = new JPanel();
private JPanel ratingPanel2 = new JPanel();
private JPanel costPanel1 = new JPanel();
private JPanel costPanel2 = new JPanel();
private JPanel quantityPanel1 = new JPanel();
private JPanel quantityPanel2 = new JPanel();
private JLabel barcodeLabel = new JLabel();
private JLabel nameLabel = new JLabel();
private JLabel descLabel = new JLabel();
private JLabel compLabel = new JLabel();
private JLabel ratingLabel = new JLabel();
private JLabel costLabel = new JLabel();
private JLabel quantityLabel = new JLabel();
private GridLayout displayLayout;
JButton edit = new JButton("Edit");
JButton backToMenu = new JButton("Back to Menu");
JButton delete = new JButton("Delete");
public DisplayRecord() {
stocks = new StockList();
list = stocks.getList();
try {
stocks.load();
} catch (IOException ex) {
System.out.println("Cannot load file");
}
}
public void displayRecord(Product p) {
this.setTitle("Displaying one record");
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setPreferredSize(new Dimension(500, 350));
top = new JPanel();
displayLayout = new GridLayout(7, 2, 2, 2);
top.setLayout(displayLayout);
top.setBorder(BorderFactory.createEmptyBorder(5, 20, 5, 5));
bot = new JPanel();
bot.setLayout(new BoxLayout(bot, BoxLayout.LINE_AXIS));
bot.add(Box.createHorizontalGlue());
bot.setBorder(BorderFactory.createEmptyBorder(20, 5, 5, 5));
barcodeLabel.setText("Barcode: ");
nameLabel.setText("Name: ");
descLabel.setText("Description: ");
compLabel.setText("Developer: ");
ratingLabel.setText("EU Rating: ");
costLabel.setText("Cost: ");
quantityLabel.setText("Quantity in Stock: ");
JLabel barcodeField = new JLabel(Long.toString(p.getBarcode()));
JLabel nameField = new JLabel(p.getName());
JLabel descField = new JLabel(p.getDesc());
JLabel compField = new JLabel(p.getCompany());
JLabel ratingField = new JLabel(p.getRating());
JLabel costField = new JLabel(Double.toString(p.getCost()));
JLabel quantityField = new JLabel(Integer.toString(p.getQuantity()));
barcodePanel1.add(barcodeLabel);
barcodePanel1.setBorder(BorderFactory.createLineBorder(Color.black));
barcodePanel2.add(barcodeField); barcodePanel2.setBorder(BorderFactory.createLineBorder(Color.black));
namePanel1.add(nameLabel);
namePanel1.setBorder(BorderFactory.createLineBorder(Color.black));
namePanel2.add(nameField);
namePanel2.setBorder(BorderFactory.createLineBorder(Color.black));
descPanel1.add(descLabel);
descPanel1.setBorder(BorderFactory.createLineBorder(Color.black));
descPanel2.add(descField);
descPanel2.setBorder(BorderFactory.createLineBorder(Color.black));
compPanel1.add(compLabel);
compPanel1.setBorder(BorderFactory.createLineBorder(Color.black));
compPanel2.add(compField);
compPanel2.setBorder(BorderFactory.createLineBorder(Color.black));
ratingPanel1.add(ratingLabel);
ratingPanel1.setBorder(BorderFactory.createLineBorder(Color.black));
ratingPanel2.add(ratingField);
ratingPanel2.setBorder(BorderFactory.createLineBorder(Color.black));
costPanel1.add(costLabel);
costPanel1.setBorder(BorderFactory.createLineBorder(Color.black));
costPanel2.add(costField);
costPanel2.setBorder(BorderFactory.createLineBorder(Color.black));
quantityPanel1.add(quantityLabel);
quantityPanel1.setBorder(BorderFactory.createLineBorder(Color.black));
quantityPanel2.add(quantityField);
quantityPanel2.setBorder(BorderFactory.createLineBorder(Color.black));
top.add(barcodePanel1);
top.add(barcodePanel2);
top.add(namePanel1);
top.add(namePanel2);
top.add(descPanel1);
top.add(descPanel2);
top.add(compPanel1);
top.add(compPanel2);
top.add(ratingPanel1);
top.add(ratingPanel2);
top.add(costPanel1);
top.add(costPanel2);
top.add(quantityPanel1);
top.add(quantityPanel2);
edit.addActionListener(this);
delete.addActionListener(this);
backToMenu.addActionListener(this);
bot.add(edit);
bot.add(Box.createRigidArea(new Dimension(10, 0)));
bot.add(delete);
bot.add(Box.createRigidArea(new Dimension(10, 0)));
bot.add(backToMenu);
this.add(top);
this.add(bot, BorderLayout.SOUTH);
this.setLocationRelativeTo(null);
this.pack();
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) { // here is where I'd LIKE to pass Product p as parameter but obviously that's not a thing
if (e.getSource() == edit) {
// EditProduct ed = new EditProduct(); <- hypothetical!
// ed.editProduct(p);
} else if (e.getSource() == delete) {
// DeleteRecord del = new DeleteRecord(); <- hypothetical!
// del.deleteRecord(p);
} else if (e.getSource() == backToMenu) {
new CreateDisplay();
this.dispose();
}
}
}
My EditProduct class:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class EditProduct extends JFrame implements FocusListener, ActionListener {
final private StockList stocks;
final private ArrayList<Product> list;
JPanel top, bot;
JLabel nameLabel, costLabel, quantityLabel = new JLabel();
JTextField nameField, costField, quantityField = new JTextField();
JButton save, quit = new JButton();
private GridLayout topLayout;
public EditProduct() {
stocks = new StockList();
list = stocks.getList();
}
public void editProduct(Product p) {
this.setTitle("Editing a Product");
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setPreferredSize(new Dimension(500, 250));
top = new JPanel();
topLayout = new GridLayout(3, 2, 5, 5);
top.setBorder(BorderFactory.createEmptyBorder(5, 20, 5, 5));
top.setLayout(topLayout);
bot = new JPanel();
bot.setLayout(new BoxLayout(bot, BoxLayout.LINE_AXIS));
bot.add(Box.createHorizontalGlue());
bot.setBorder(BorderFactory.createEmptyBorder(20, 5, 5, 5));
nameLabel.setText("Name: ");
costLabel.setText("Cost: ");
quantityLabel.setText("Quantity: ");
top.add(nameLabel);
top.add(costLabel);
top.add(quantityLabel);
nameField = new JTextField(p.getName());
costField = new JTextField(String.valueOf(p.getCost()));
quantityField = new JTextField(p.getQuantity());
nameField.addFocusListener(this);
costField.addFocusListener(this);
quantityField.addFocusListener(this);
save.setText("Save");
save.addActionListener(this);
quit.setText("Quit");
quit.addActionListener(this);
bot.add(save);
bot.add(Box.createRigidArea(new Dimension(10, 0)));
bot.add(quit);
this.add(top);
this.add(bot, BorderLayout.SOUTH);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
#Override
public void focusGained(FocusEvent e) {
if (e.getSource() == nameField) {
nameField.setText("");
} else if (e.getSource() == costField) {
costField.setText("");
} else if (e.getSource() == quantityField) {
quantityField.setText("");
}
}
#Override
public void focusLost(FocusEvent fe) {
//do nothing
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == save) {
String newName = nameField.getText();
double newCost = Double.parseDouble(costField.getText());
int newQty = Integer.parseInt(quantityField.getText());
stocks.editProduct(newName, newCost, newQty);
this.dispose();
JOptionPane.showMessageDialog(null, "Changes have been saved!", "Saved!", JOptionPane.PLAIN_MESSAGE);
} else if (e.getSource() == quit) {
}
}
}
Aaand the DeleteRecord class:
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class DeleteRecord {
private StockList stocks;
private ArrayList<Product> list;
public DeleteRecord() {
stocks = new StockList();
list = stocks.getList();
}
public DeleteRecord(Product p) {
String title = "Are you sure you want to delete " + p.getName() + "?";
if (JOptionPane.showConfirmDialog(null, title, "Deleting...", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
stocks.deleteRecord(p);
} else {
new CreateDisplay();
}
}
}
I'm sorry for the massive post and text wall but I honestly have no idea where my problem is or how to work around this problem (and I'm also new to StackOverflow). Can anyone help me?
It seems to me that DisplayRecord can only display one Product at a time. If that is indeed the case, you can store that Product in a field and then access it from actionPerfomed().
I am pretty new to using swing, and I have a question. My code stopped working this morning, but I don't know why. I ran the debugger, and it says 2 lines of code. One is in the main class, one is in the other. They are both creating instances of each other.
The lines are something like this:
Main Class:
OnePlayerFrame OnePFrame = new OnePlayerFrame();
OnePlayerFrame Class:
MainFrame MainClass = new MainFrame();
I hope you can understand what I'm saying, as I said I'm pretty new to swing.
Thanks
-Matt
Ok, here is the whole thing:
Right, forgot to mention, I may have deleted a simple line of code and am overlooking it, so please stay calm if it's something simple :)
Main Class:
package rockpaperscissors;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MainFrame {
public JFrame frame = new JFrame();
private final ImageIcon rock = new ImageIcon("C:/Users/Matthew/Documents/NetBeansProjects/RockPaperScissors/src/assets/rock.jpg");
private final ImageIcon paper = new ImageIcon("C:/Users/Matthew/Documents/NetBeansProjects/RockPaperScissors/src/assets/paper.png");
private final ImageIcon scissors = new ImageIcon("C:/Users/Matthew/Documents/NetBeansProjects/RockPaperScissors/src/assets/scissors.png");
private final JLabel rockLabel = new JLabel();
private final JLabel paperLabel = new JLabel();
private final JLabel scissorsLabel = new JLabel();
private final JPanel panel1 = new JPanel();
private final JPanel panel2 = new JPanel();
private final JPanel panel3 = new JPanel();
private final JPanel empty1 = new JPanel();
private final JPanel empty2 = new JPanel();
private final JPanel empty3 = new JPanel();
private final JPanel empty4 = new JPanel();
private final JPanel empty5 = new JPanel();
OnePlayerFrame OnePlayerFrame = new OnePlayerFrame();
public JButton btn1 = new JButton("1 Player");
private final JTextField text = new JTextField();
private final Font font = new Font("Showcard Gothic Regular", Font.BOLD, 28);
public MainFrame(){
frame.setSize(360, 300);
frame.setAlwaysOnTop(false);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.add(panel1);
frame.add(panel2);
frame.add(panel3);
frame.setLayout(new GridLayout(3, 1));
panel1.setLayout(new GridLayout(1, 3));
panel1.add(rockLabel);
panel1.add(paperLabel);
panel1.add(scissorsLabel);
panel1.setBackground(Color.WHITE);
panel2.setLayout(new GridLayout(2, 3));
panel2.add(empty1);
panel2.add(empty2);
panel2.add(empty3);
panel2.add(empty4);
panel2.add(btn1);
panel2.add(empty5);
panel3.add(text);
panel3.setBackground(Color.WHITE);
empty1.setBackground(Color.WHITE);
empty2.setBackground(Color.WHITE);
empty3.setBackground(Color.WHITE);
empty4.setBackground(Color.WHITE);
empty5.setBackground(Color.WHITE);
text.setText("Rock Paper Scissors");
text.setFont(font);
text.setPreferredSize(new Dimension(360, 80));
text.setEditable(false);
text.setBorder(null);
text.setHorizontalAlignment(JTextField.CENTER);
text.setBackground(Color.WHITE);
rockLabel.setIcon(rock);
paperLabel.setIcon(paper);
scissorsLabel.setIcon(scissors);
btn1.setFocusPainted(false);
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
frame.dispose();
OnePlayerFrame.startGame1();
}
});
}
public static void main(String[] args) {
new MainFrame();
}
}
And here is the second class:
package rockpaperscissors;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class OnePlayerFrame {
MainFrame MainClass = new MainFrame();
JFrame gameFrame = new JFrame();
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
JPanel panel5 = new JPanel();
JPanel panel6 = new JPanel();
JPanel panel7 = new JPanel();
JPanel panel8 = new JPanel();
JPanel panel9 = new JPanel();
JPanel empty1 = new JPanel();
JPanel empty2 = new JPanel();
JTextField playerText1 = new JTextField();
JTextField playerText2 = new JTextField();
JTextField playerText3 = new JTextField();
JTextField compText1 = new JTextField();
JTextField compText2 = new JTextField();
JTextField compText3 = new JTextField();
JTextField pChoose = new JTextField();
JTextField cChoose = new JTextField();
JButton btn1 = new JButton("Rock");
JButton btn2 = new JButton("Paper");
JButton btn3 = new JButton("Scissors");
JButton btn4 = new JButton("Confirm");
JButton btn5 = new JButton("Fight!");
JButton getB = new JButton();
JLabel label1 = new JLabel();
JLabel label2 = new JLabel();
boolean confirmed = false;
boolean hasSelected = false;
boolean runThread = true;
String playerMove;
ImageIcon playerIcon = new ImageIcon("C:/Users/Matthew/Documents/NetBeansProjects/RockPaperScissors/src/assets/question-mark.jpg");
ImageIcon computerIcon = new ImageIcon("C:/Users/Matthew/Documents/NetBeansProjects/RockPaperScissors/src/assets/question-mark.jpg");
Font font = new Font("Showcard Gothic Regular", Font.BOLD, 18);
public OnePlayerFrame(){
gameFrame.setVisible(true);
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameFrame.setSize(500, 400);
gameFrame.setLocationRelativeTo(MainClass.frame);
gameFrame.setLayout(new GridLayout(3, 1));
gameFrame.add(panel1);
gameFrame.add(panel2);
gameFrame.add(panel3);
MainClass.frame.dispose();
panel1.setBackground(Color.WHITE);
panel1.setLayout(new GridLayout(1, 4));
panel1.add(panel4);
panel1.add(panel5);
panel1.add(panel6);
panel1.add(panel7);
panel2.setBackground(Color.WHITE);
panel2.setLayout(new GridLayout(3, 1));
panel2.add(pChoose);
panel2.add(panel8);
panel2.add(btn4);
panel3.setBackground(Color.WHITE);
panel3.add(cChoose);
panel3.add(panel9);
panel3.setLayout(new GridLayout(2, 1));
panel4.setBackground(Color.WHITE);
panel4.add(playerText1);
panel4.add(playerText2);
panel4.add(playerText3);
panel4.setLayout(new GridLayout(3, 1));
panel5.setBackground(Color.WHITE);
panel5.add(label1);
panel6.setBackground(Color.WHITE);
panel6.add(label2);
panel7.setBackground(Color.WHITE);
panel7.add(compText1);
panel7.add(compText2);
panel7.add(compText3);
panel7.setLayout(new GridLayout(3, 1));
panel8.setLayout(new GridLayout(1, 3));
panel8.add(btn1);
panel8.add(btn2);
panel8.add(btn3);
panel9.setLayout(new GridLayout(1, 3));
panel9.setBackground(Color.WHITE);
panel9.add(empty1);
panel9.add(btn5);
panel9.add(empty2);
empty1.setBackground(Color.WHITE);
empty2.setBackground(Color.WHITE);
playerText1.setEditable(false);
playerText1.setBorder(null);
playerText1.setText("Player");
playerText1.setBackground(Color.WHITE);
playerText1.setFont(font);
playerText1.setHorizontalAlignment(JTextField.CENTER);
playerText2.setEditable(false);
playerText2.setBorder(null);
playerText2.setText("Chose");
playerText2.setBackground(Color.WHITE);
playerText2.setFont(font);
playerText2.setHorizontalAlignment(JTextField.CENTER);
playerText3.setEditable(false);
playerText3.setBorder(null);
playerText3.setText("====>");
playerText3.setBackground(Color.WHITE);
playerText3.setFont(font);
playerText3.setHorizontalAlignment(JTextField.CENTER);
compText1.setEditable(false);
compText1.setBorder(null);
compText1.setText("Computer");
compText1.setBackground(Color.WHITE);
compText1.setFont(font);
compText1.setHorizontalAlignment(JTextField.CENTER);
compText2.setEditable(false);
compText2.setBorder(null);
compText2.setText("Chose");
compText2.setBackground(Color.WHITE);
compText2.setFont(font);
compText2.setHorizontalAlignment(JTextField.CENTER);
compText3.setEditable(false);
compText3.setBorder(null);
compText3.setText("<====");
compText3.setBackground(Color.WHITE);
compText3.setFont(font);
compText3.setHorizontalAlignment(JTextField.CENTER);
pChoose.setEditable(false);
pChoose.setBorder(null);
pChoose.setText("Choose your move");
pChoose.setFont(font);
pChoose.setHorizontalAlignment(JTextField.CENTER);
pChoose.setBackground(Color.WHITE);
cChoose.setEditable(false);
cChoose.setBorder(null);
cChoose.setText("Computer is choosing");
cChoose.setFont(font);
cChoose.setHorizontalAlignment(JTextField.CENTER);
cChoose.setBackground(Color.WHITE);
btn1.setRolloverEnabled(true);
btn1.setFocusPainted(false);
btn2.setFocusPainted(false);
btn2.setRolloverEnabled(true);
btn3.setFocusPainted(false);
btn3.setRolloverEnabled(true);
btn4.setFocusPainted(false);
btn4.setRolloverEnabled(true);
btn5.setFocusPainted(false);
btn5.setRolloverEnabled(true);
btn5.setVisible(false);
btn5.setFont(font);
label1.setIcon(playerIcon);
label2.setIcon(computerIcon);
}
public void startGame1(){
new Thread(new Runnable() {
public void run() {
while(confirmed == true || confirmed == false){
if(confirmed == false){
try{
if(confirmed == false){
cChoose.setText("Computer is choosing");
Thread.sleep(500);
}
if(confirmed == false){
cChoose.setText("Computer is choosing.");
Thread.sleep(500);
}
if(confirmed == false){
cChoose.setText("Computer is choosing..");
Thread.sleep(500);
}
if(confirmed == false){
cChoose.setText("Computer is choosing...");
Thread.sleep(500);
}
}
catch(Exception e){
gameFrame.dispose();
}
}
if(confirmed == true){
cChoose.setText("Computer has chosen!");
fightButtonSet();
}
}
}
}).start();
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if(confirmed == false){
playerMove = btn1.getText();
hasSelected = true;
pChoose.setText("You have selected rock");
getB = btn1;
}
else{
pChoose.setText("You have already confirmed " + getB.getText().toLowerCase() + "!");
}
}
});
btn2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if(confirmed == false){
playerMove = btn2.getText();
hasSelected = true;
pChoose.setText("You have selected paper");
getB = btn2;
}
else{
pChoose.setText("You have already confirmed " + getB.getText().toLowerCase() + "!");
}
}
});
btn3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if(confirmed == false){
playerMove = btn3.getText();
hasSelected = true;
pChoose.setText("You have selected scissors");
getB = btn3;
}
else{
pChoose.setText("You have already confirmed " + getB.getText().toLowerCase() + "!");
}
}
});
btn4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if(hasSelected == true && confirmed == false){
confirmed = true;
pChoose.setText("You have confirmed " + getB.getText().toLowerCase() + "!");
cChoose.setText("Computer has chosen!");
}
else{
if(hasSelected == false){
pChoose.setText("You haven't selected anything yet!");
}
else if (confirmed == true){
pChoose.setText("You have already confirmed " + getB.getText().toLowerCase() + "!");
}
}
}
});
}
public void fightButtonSet(){
btn5.setVisible(true);
btn5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
FIGHT();
}
});
}
public void FIGHT(){
if(getB.getText().equalsIgnoreCase("Rock")){
}
if(getB.getText().equalsIgnoreCase("Paper")){
}
if(getB.getText().equalsIgnoreCase("Scissors")){
}
}
}
We can abstract a little you have this.
public class TestCircularDependency {
static class A{
B b = new B();
}
static class B{
A a = new A();
}
public static void main(String args[]){
A a = new A();
}
}
This will throw a StackOverflowError. You have a circular dependency. The problem is that you are instance each one in constructor then you have infinite recursion.
In java you can have circular dependency but not in object creation. You can do something like this.
public class TestCircularDependency {
static class A{
B b;
}
static class B{
A a;
}
public static void main(String args[]){
A a = new A();
a.b = new B();
b.a= a;
}
}
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);
}
}
}