Add multiple instances of the same button - java

I am creating a simple calculator for a school assignment but I can't get it to work for multiple digits
package calculator;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Container;
public class Calculator implements ActionListener{
JFrame guiFrame;
JPanel buttonPanel;
JTextField numberCalc;
int calcOperation = 0;
int currentCalc;
public static void main(String[] args) {
//Use the event dispatch thread for Swing components
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new Calculator();
}
});
}
public Calculator()
{
guiFrame = new JFrame();
//make sure the program exits when the frame closes
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("Simple Calculator");
guiFrame.setSize(300,300);
//This will center the JFrame in the middle of the screen
guiFrame.setLocationRelativeTo(null);
numberCalc = new JTextField();
numberCalc.setHorizontalAlignment(JTextField.RIGHT);
numberCalc.setEditable(false);
guiFrame.add(numberCalc, BorderLayout.NORTH);
buttonPanel = new JPanel();
//Make a Grid that has three rows and four columns
buttonPanel.setLayout(new GridLayout(4,4));
guiFrame.add(buttonPanel, BorderLayout.CENTER);
//Add the number buttons
for (int i=1;i<10;i++)
{
addButton(buttonPanel, String.valueOf(i));
}
JButton addButton = new JButton("+");
addButton.setActionCommand("+");
OperatorAction subAction = new OperatorAction(1);
addButton.addActionListener(subAction);
JButton subButton = new JButton("-");
subButton.setActionCommand("-");
OperatorAction addAction = new OperatorAction(2);
subButton.addActionListener(addAction);
JButton multiplyButton = new JButton("*");
multiplyButton.setActionCommand("*");
OperatorAction multiAction = new OperatorAction(3);
multiplyButton.addActionListener(multiAction);
JButton divideButton = new JButton("/");
divideButton.setActionCommand("/");
OperatorAction diviAction = new OperatorAction(4);
divideButton.addActionListener(diviAction);
JButton clearButton = new JButton("ce");
clearButton.setActionCommand("ce");
OperatorAction clearAction = new OperatorAction(5);
clearButton.addActionListener(clearAction);
JButton blankButton = new JButton(" ");
JButton equalsButton = new JButton("=");
equalsButton.setActionCommand("=");
equalsButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
if (!numberCalc.getText().isEmpty())
{
int number = Integer.parseInt(numberCalc.getText());
if (calcOperation == 1)
{
int calculate = currentCalc + number;
numberCalc.setText(Integer.toString(calculate));
}
if (calcOperation == 2)
{
int calculate = currentCalc - number;
numberCalc.setText(Integer.toString(calculate));
}
if (calcOperation == 3)
{
int calculate = currentCalc * number;
numberCalc.setText(Integer.toString(calculate));
}
if (calcOperation == 4)
{
int calculate = currentCalc / number;
numberCalc.setText(Integer.toString(calculate));
}
if (calcOperation == 5)
{
int calculate = 0;
numberCalc.setText(Integer.toString(calculate));
}
}
}
});
buttonPanel.add(addButton);
buttonPanel.add(subButton);
buttonPanel.add(equalsButton);
buttonPanel.add(divideButton);
buttonPanel.add(multiplyButton);
buttonPanel.add(clearButton);
buttonPanel.add(blankButton);
guiFrame.setVisible(true);
}
//All the buttons are following the same pattern
//so create them all in one place.
private void addButton(Container parent, String name)
{
JButton but = new JButton(name);
but.setActionCommand(name);
but.addActionListener(this);
parent.add(but);
}
//As all the buttons are doing the same thing it's
//easier to make the class implement the ActionListener
//interface and control the button clicks from one place
#Override
public void actionPerformed(ActionEvent event)
{
//get the Action Command text from the button
String action = event.getActionCommand();
//set the text using the Action Command text
numberCalc.setText(action);
}
private class OperatorAction implements ActionListener
{
private int operator;
public OperatorAction(int operation)
{
operator = operation;
}
public void actionPerformed(ActionEvent event)
{
currentCalc = Integer.parseInt(numberCalc.getText());
calcOperation = operator;
}
}
}
However when I run the code It will not allow me to enter in numbers with more than one digit. Also the ce button I created will not reset to zero.
I have included an image of the output.
Thanks in advance.
Output of calculator

The ActionListener is not correct
#Override
public void actionPerformed(ActionEvent event)
{
//get the Action Command text from the button
String action = event.getActionCommand();
//set the text using the Action Command text
numberCalc.setText(action);
}
This will set the numberCalc text to the value of the button, not append the value.
Use numberCalc.setText(NumberCalc.getText() + action); to append the text
Also, for OperatorAction, you don't update any GUI component
public void actionPerformed(ActionEvent event)
{
currentCalc = Integer.parseInt(numberCalc.getText());
calcOperation = operator;
}
You should clear numberCalc to wait for the next value or you will end up with 1 + 12 instead of 1 + 2.
If the button is clearButton, you need to change the logic and reset everything currentCalc, numberCalc, calcOperation, ...

Related

How to use a button press from a second JFrame in a seperate Class as an action in the main class

So for school, we have to make 2 separate JFrames that interact with each other. From within the first JFrame, a button gets pressed which opens the second one, where a name, speed, and position can be filled in.
When pressing OK on the second JFrame, I save the filled-in text and numbers but I have no clue how to use them in the code of the first JFrame. I had tried to use a "getter" from the second JFrame to check in the first one if the "OK" button had been pressed. But this gets checked immediately after opening the window. That means it isn't true YET and it doesn't check it again.
CONTEXT:
We are forced to use 2 separate JFrame.
We are not allowed to add extra methods.
We are not allowed to change the constructor.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TourFrame extends JFrame implements ActionListener{
private Etappe etappe;
private JLabel jlAantal;
private JTextField jtfAantal;
private JButton knopPrint;
private JButton knopStap;
private JButton knopVoegFietsenToe;
private JButton knopVoegCustomFietsToe;
public TourFrame(Etappe etappe){
this.etappe = etappe;
setTitle("Tour de Windesheim: " + etappe.toString());
setSize(650, 550);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jlAantal = new JLabel("aantal:");
add(jlAantal);
jtfAantal = new JTextField(10);
add(jtfAantal);
knopPrint = new JButton("print");
add(knopPrint);
knopPrint.addActionListener(this);
knopStap = new JButton("stap");
add(knopStap);
knopStap.addActionListener(this);
knopVoegFietsenToe = new JButton("voeg fietsen toe");
add(knopVoegFietsenToe);
knopVoegFietsenToe.addActionListener(this);
knopVoegCustomFietsToe = new JButton("voeg custom fiets toe");
add(knopVoegCustomFietsToe);
knopVoegCustomFietsToe.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == knopPrint){
etappe.print();
} else if(e.getSource() == knopStap){
etappe.stap();
setTitle("Tour de Windesheim: " + etappe.toString());
} else if(e.getSource() == knopVoegFietsenToe){
try {
int aantal = Integer.parseInt(jtfAantal.getText());
for(int i = 0; aantal > i; i++){
Fiets tijdelijk = new Fiets();
etappe.voegDeelnemerToe(tijdelijk);
}
} catch (NumberFormatException nfe){
jlAantal.setText("Voer een getal in");
}
} else if(e.getSource() == knopVoegCustomFietsToe){
FietsDialoog fietsdialoog = new FietsDialoog();
}
}
}
The Second one looks as follwed:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class FietsDialoog extends JFrame implements ActionListener {
private JLabel jlNaam;
private JTextField jtfNaam;
private JLabel jlStartPositie;
private JTextField jtfStartPositie;
private JLabel jlSnelheid;
private JTextField jtfSnelheid;
private JButton knopOk;
private JButton knopCancel;
private String naam;
private int startpositie;
private int snelheid;
private boolean ok;
private boolean cancel;
public FietsDialoog(){
setTitle("FietsDialoog");
setSize(600, 100);
setLayout(new FlowLayout());
setDefaultCloseOperation(HIDE_ON_CLOSE);
jlNaam = new JLabel("naam");
add(jlNaam);
jtfNaam = new JTextField(10);
add(jtfNaam);
jlStartPositie = new JLabel("startpositie");
add(jlStartPositie);
jtfStartPositie = new JTextField(10);
add(jtfStartPositie);
jlSnelheid = new JLabel("snelheid");
add(jlSnelheid);
jtfSnelheid = new JTextField(10);
add(jtfSnelheid);
knopOk = new JButton("ok");
add(knopOk);
knopOk.addActionListener(this);
knopCancel = new JButton("cancel");
add(knopCancel);
knopCancel.addActionListener(this);
setVisible(true);
}
public String getNaam() {
return naam;
}
public int getStartpositie() {
return startpositie;
}
public int getSnelheid() {
return snelheid;
}
public boolean isOk() {
return ok;
}
public boolean isCancel() {
return cancel;
}
public JButton getKnopOk() {
return knopOk;
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == knopOk){
this.naam = jtfNaam.getText();
this.startpositie = Integer.parseInt(jtfStartPositie.getText());
this.snelheid = Integer.parseInt(jtfSnelheid.getText());
this.ok = true;
this.cancel = false;
} else if(e.getSource() == knopCancel){
this.ok = false;
this.cancel = true;
dispose();
}
}
}
Try and print fietsdialoog.getNaam(), fietsdialoog.getStartpositie()...etc, the getter from the fietsdialoog class after closing the window.
Also, rather than dispose the window: use setVisible to false. JFrame.setVisible(true/false);

JButton size & location

Hello fellow programmers! I'm starting to learn java, and as a project, i put in my mind to make a visual calculator. My problem is that i can't set an exact location or size for my button, and i would like some help please!
import javax.swing.*;
import java.awt.*;
public class Calculator{
public static void main(String[] args) {
//Frame & sizes
JFrame f = new JFrame("Calculator");
f.setSize(400, 500);
f.setLocation(300,200);
//Text area
final JTextArea textArea = new JTextArea(10, 40);
f.getContentPane().add(BorderLayout.NORTH, textArea);
//Buttons
final JButton button1 = new JButton("1");
button1.setBounds(160, 100, 410, 100);
}
}
There is a lot of additional set-up you need to do, for a tutorial please refer to this article. They do a great job walking you through the steps, I simply pasted the final solution if you want to try it out on your end. To replicate simply create a new Java class called JavaCalculator and run the main method, hopefully this helps!
JavaCalculator:
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Container;
public class JavaCalculator implements ActionListener{
JFrame guiFrame;
JPanel buttonPanel;
JTextField numberCalc;
int calcOperation = 0;
int currentCalc;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable()
{
public void run()
{
new JavaCalculator();
}
});
}
public JavaCalculator()
{
guiFrame = new JFrame();
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("Simple Calculator");
guiFrame.setSize(300,300);
guiFrame.setLocationRelativeTo(null);
numberCalc = new JTextField();
numberCalc.setHorizontalAlignment(JTextField.RIGHT);
numberCalc.setEditable(false);
guiFrame.add(numberCalc, BorderLayout.NORTH);
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4,4));
guiFrame.add(buttonPanel, BorderLayout.CENTER);
for (int i=0;i<10;i++)
{
addNumberButton(buttonPanel, String.valueOf(i));
}
addActionButton(buttonPanel, 1, "+");
addActionButton(buttonPanel, 2, "-");
addActionButton(buttonPanel, 3, "*");
addActionButton(buttonPanel, 4, "/");
addActionButton(buttonPanel, 5, "^2");
JButton equalsButton = new JButton("=");
equalsButton.setActionCommand("=");
equalsButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if (!numberCalc.getText().isEmpty())
{
int number = Integer.parseInt(numberCalc.getText());
if (calcOperation == 1)
{
int calculate = currentCalc + number;
numberCalc.setText(Integer.toString(calculate));
}
else if (calcOperation == 2)
{
int calculate = currentCalc - number;
numberCalc.setText(Integer.toString(calculate));
}
else if (calcOperation == 3)
{
int calculate = currentCalc * number;
numberCalc.setText(Integer.toString(calculate));
}
else if (calcOperation == 4)
{
int calculate = currentCalc / number;
numberCalc.setText(Integer.toString(calculate));
}
else if (calcOperation == 5)
{
int calculate = currentCalc * currentCalc;
numberCalc.setText(Integer.toString(calculate));
}
}
}
});
buttonPanel.add(equalsButton);
guiFrame.setVisible(true);
}
private void addNumberButton(Container parent, String name)
{
JButton but = new JButton(name);
but.setActionCommand(name);
but.addActionListener(this);
parent.add(but);
}
private void addActionButton(Container parent, int action, String text)
{
JButton but = new JButton(text);
but.setActionCommand(text);
OperatorAction addAction = new OperatorAction(1);
but.addActionListener(addAction);
parent.add(but);
}
public void actionPerformed(ActionEvent event)
{
String action = event.getActionCommand();
numberCalc.setText(action);
}
private class OperatorAction implements ActionListener
{
private int operator;
public OperatorAction(int operation)
{
operator = operation;
}
public void actionPerformed(ActionEvent event)
{
currentCalc = Integer.parseInt(numberCalc.getText());
calcOperation = operator;
}
}
}

JComboBox with JButton into TextField

I want to detect what JComboBox item is selected when I click the JButton. The result will be placed in a TextField that I've stacked up in my action performed.
For example, when I select an appropriate number then it will classified into something using the JButton and the result will be on TextField.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class mFrame extends JFrame implements ActionListener
{
JLabel lblAge = new JLabel("Age");
JComboBox cboAge = new JComboBox();
JButton btnClass = new JButton("Classification");
JTextField txtField = new JTextField();
JButton btnClose = new JButton("Close");
public mFrame()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
setSize(400,200);
add(lblAge);
add(cboAge);
add(btnClass);
add(txtField);
add(btnClose);
lblAge.setBounds(10,10,100,20);
cboAge.setBounds(140,10,120,20);
btnClass.setBounds(10,30,120,20);
txtField.setBounds(140,30,120,20);
btnClose.setBounds(200,105,70,20);
for (int j = 10; j < 101; j++) cboAge.addItem(new Integer(j));
cboAge.addActionListener(this);
btnClass.addActionListener(this);
txtField.addActionListener(this);
btnClose.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent age)
{
//if (age.getSource() == btnClass)
{
//
if (age.getSource() == btnClose)
{
System.exit(0);
}
}
}
}
class StartHere
{
public static void main(String [] args)
{
new mFrame();
}
}
first you don't need addActionListener() for txtField and cboAge
because you are not doing anything when action is performed there.
just do it for buttons.
and this is how actionPerformed() can be (note: i changed ActionEvent age to ActionEvent e)
public void actionPerformed(ActionEvent e){
if (e.getSource() == btnClass){
String selectedValue = cboAge.getSelectedItem().toString();
// if you need it as integer...
int age = Integer.parseInt(selectedValue);
// do your classification processing... assuming output value is assigned in String result.
//ex for classification processing:
String result = "";
if(age>=10 && age<=19){
result = "Teenage";
}else if(age>=20 && age<=28){
result = "blah blah";
}//... and so on...
txtField.setText(result);
}else if (e.getSource() == btnClose){
System.exit(0);
}
}

action listener doesnt work

I am new in java swing unfortunately when i want to set action listener to one of the button that it has to get the textArea content and send that to another class it doesn't work in a way that i expect and instead it works when i change the text area's content, i don't know What's happened?
first button i named Button and the same problem happened when i use another action listener inside the Button's action listener named Clac
here is my code:
import java.awt.BorderLayout;
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.JOptionPane;
public class FFT_Main_Frame extends JFrame {
JLabel label;
JButton button;
TextPanel txtPanel;
JButton Button;
JLabel label1;
// JTextArea[] BoxArray;
makePolynomial mp;
JButton Calc;
Complex[] Nums;
Complex[] Result;
int input;
FFT_Main fft_main;
ShowResult shr;
public FFT_Main_Frame() {
Button.addActionListener(new ActionListener() {
// Test t;
// Integer content;
#Override
public void actionPerformed(ActionEvent arg0) {
try {
Integer content = new Integer(Integer.parseInt(txtPanel.getTextArea()));
input = content;
System.out.println(input);
// inputt=input;
mp = new makePolynomial(content);
setLayout(new FlowLayout());
add(mp);
// setLayout(new BorderLayout());
add(Calc);
Nums = new Complex[input + 1];
Calc.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
for (int i = input; i >= 0; i--) {
Nums[i] = new Complex(Double.parseDouble(mp.BoxArray[2 * (i + 1) - 1].getText()),
Double.parseDouble(mp.BoxArray[2 * i].getText()));
}
for (int i = 0; i <= input; i++) {
System.out.println(Nums[i]);
}
fft_main = new FFT_Main();
Result = new Complex[input];
Result = fft_main.Recursive_FFT(Nums);
shr = new ShowResult(Result);
setLayout(new BorderLayout());
add(shr, BorderLayout.CENTER);
System.out.println("Result\n\n");
for (int i = 0; i <= input; i++) {
System.out.println(Result[i]);
}
}
});
} catch (NumberFormatException exception) {
JOptionPane.showMessageDialog(null, "Please Enter Just Numbers! ", "Wrong Value",
JOptionPane.ERROR_MESSAGE);
}
}
});
}
}
thanks for your help
You are using action listener wrong way here is an example how to use it
public FFT_Main_Frame() {
JButton Button = new JButton("Button");
Button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
try {
// Code Here
}catch(Exception e) {
// Code Here
}
});
JButton Calc = new JButton("Calc");
Calc.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// Code Here
}
});
}
}
Some tutorials on how to use action listener
https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
http://www.tutorialspoint.com/swing/swing_action_listener.htm

Java displayField refuses to clear

I'm working on a calculator application (which I have simplified downed to make it easier to debug). When the user hits '=' the IMPORTANTINT will change to 1. When the users clicks another button the field is supposed to clear with the if then statement in CalculatorEngine:
if(IMPORTANTINT == 1){
System.out.println("Ran the block of code");
parent.setDisplayValue("");
IMPORTANTINT = 0;
System.out.println(IMPORTANTINT);
}
This is done so the user can view the result and then start a new calculation. The textField doesn't want to clear. Does anyone know why this is? Thanks!
CalculatorEngine.java
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
import javax.swing.JButton;
public class CalculatorEngine implements ActionListener{
Calculator parent;
double firstNum, secondNum;
String symbol;
int IMPORTANTINT = 0;
CalculatorEngine(Calculator parent){
this.parent = parent;
}
public void actionPerformed(ActionEvent e){
JButton clickedButton = (JButton) e.getSource();
String clickedButtonLabel = clickedButton.getText();
String dispFieldText = parent.getDisplayValue();
if(IMPORTANTINT == 1){
System.out.println("Ran the block of code");
parent.setDisplayValue("");
IMPORTANTINT = 0;
System.out.println(IMPORTANTINT);
}
if(clickedButtonLabel == "+"){
firstNum = (Double.parseDouble(parent.getDisplayValue()));
parent.setDisplayValue("");
symbol = clickedButtonLabel;
} else if(clickedButtonLabel == "="){
IMPORTANTINT = 1;
secondNum = Double.parseDouble(parent.getDisplayValue());
double answer = firstNum + secondNum;
parent.setDisplayValue(Double.toString(answer));
} else{
parent.setDisplayValue(dispFieldText + clickedButtonLabel);
}
}
Calculator.java
import javax.swing.*;
import java.awt.GridLayout;
import java.awt.BorderLayout;
public class Calculator {
private JPanel windowContent;
private JPanel p1;
private JPanel sideBar;
private JTextField displayField;
private JButton button8;
private JButton button9;
private JButton buttonEqual;
private JButton buttonPlus;
Calculator(){
windowContent= new JPanel();
BorderLayout bl = new BorderLayout();
windowContent.setLayout(bl);
displayField = new JTextField(30);
windowContent.add("North",displayField);
button8=new JButton("8");
button9=new JButton("9");
buttonEqual=new JButton("=");
buttonPlus = new JButton("+");
p1 = new JPanel();
GridLayout gl =new GridLayout(4,3);
p1.setLayout(gl);
sideBar = new JPanel();
GridLayout gl2 = new GridLayout(5,1);
sideBar.setLayout(gl2);
p1.add(button8);
p1.add(button9);
p1.add(buttonEqual);
sideBar.add(buttonPlus);
windowContent.add("Center", p1);
windowContent.add("East", sideBar);
JFrame frame = new JFrame("Calculator");
frame.setContentPane(windowContent);
frame.pack();
frame.setVisible(true);
CalculatorEngine calcEngine = new CalculatorEngine(this);
button8.addActionListener(calcEngine);
button9.addActionListener(calcEngine);
buttonEqual.addActionListener(calcEngine);
buttonPlus.addActionListener(calcEngine);
}
public void setDisplayValue(String val){
displayField.setText(val);
}
public String getDisplayValue(){
return displayField.getText();
}
public static void main(String[] args)
{
Calculator calc = new Calculator();
}
}
public void setDisplayValue(String val){
SwingUtilities.invokeLater(new Runnable{
#Override
public void run()
{
displayField.setText(val);
}
});
}
You are effectively caching the dispFieldText before entering the IMPORTANTINT if statement block. Therefore the JTextField is being cleared but subsequently then to the cached value in the else block.
if (IMPORTANTINT == 1) {
dispFieldText = ""; // add this
...
}
if (clickedButtonLabel.equals("+")) {
...
} else if (clickedButtonLabel.equals("=")) {
...
} else {
// Field being reset here vvvv
parent.setDisplayValue(dispFieldText + clickedButtonLabel);
}
Make sure to clear the variable. Use String#equals to check String content. The == operator checks Object references.
Aside: Use Java naming conventions, IMPORTANTINT is a modifiable variable so should be importantInt (A boolean typically handles a true/false scenario)

Categories