简体   繁体   中英

How to implement multiple buttons using Java's Swing library and ActionEvent

I'm teaching myself how to use Java's Graphic UI with Swing, and currently making simple calculator. However, I am having issue implementing +, -, and clear button on my application.

Before presenting my code, I would like to note that I have omitted parts that are working fine and irrelevant to my current problem.

I would also like to note that my program has separate package " calculator.applicationlogic " that contains interface NumberMath and its implementation CalculateNumber . NumberMath and CalculateNumber is used to record the number and hence all it does is return current number, add to current number, subtract from current number, and clear recorded number by setting to 0.

Following is the file that implements the UI:

// GraphicCalculator.java
package calculator.ui;

import calculator.applicationlogic.*;
import calculator.ui.*;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.JButton;


public class GraphicCalculator implements Runnable{
    private JFrame frame;
    private NumberMath num;

    public GraphicCalculator(NumberMath num){
        this.num = num;
    };

    @Override
    public void run(){
      ... config for how windows look ...
    }

    // displays output and input
    private void createComponents(Container container){
        GridLayout layout = new GridLayout(3, 1);   
        container.setLayout(layout);

        JTextField output = new JTextField("0");
        output.setEnabled(false);
        JTextField input = new JTextField();

        container.add(output);
        container.add(input);
        container.add(createPanel(input, output));
    }

    // Button that has +, -, and clear (clear denoted with letter Z)
    private JPanel createPanel(JTextField in, JTextField out){
        JPanel panel = new JPanel(new GridLayout(1,3));

        // create buttons
        JButton addButton = new JButton("+");
        JButton subButton = new JButton("-");
        JButton clearButton = new JButton("Z");

        // Action
        CalculateListener listener = new CalculateListener(this.num, in, out);
        addButton.addActionListener(listener); 
        subButton.addActionListener(listener); 
        clearButton.addActionListener(listener); 

        // add buttons to panel
        panel.add(addButton);
        panel.add(subButton);
        panel.add(clearButton);

        return panel;
    }

    public JFrame getFrame(){
        return frame;
    }

}

and following is EventListener that implements action to the buttons:

// CalculateListener.java
package calculator.ui;

import calculator.applicationlogic.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;
import javax.swing.JButton;

public class CalculateListener implements ActionListener{

    private NumberMath value;
    private JTextField input;
    private JTextField output;

    public CalculateListener(NumberMath value, JTextField input, JTextField output){
        this.value = value;
        this.input = input; 
        this.output = output;   
    }

    @Override
    public void actionPerformed(ActionEvent ae){

        if(ae.getSource().getClass().equals(JButton.class)){
            String userInput = this.input.getText();    
            int inputValue = Integer.parseInt(userInput);

            JButton buttonPressed = (JButton)ae.getSource();    

            // add
            // ****** buttonPressed.getName() returns Null, which is causing program to crash ******//
            if(buttonPressed.getName().equals("+")){
                this.value.addNum(inputValue);  
            }

            // sub
            if(buttonPressed.getName().equals("-")){
                this.value.subNum(inputValue);  
            }

            // clear
            if(buttonPressed.getName().equals("Z")){
                this.value.clearNum();  
            }

            this.output.setText(String.valueOf(this.value.getNum()));
            this.input.setText("");
        }
        else{
            System.err.println("No Button");
        }
    }
}

Since I had issue of ActionEvent not recognizing button name, I referenced this post to determine different buttons. While it compiles, program crashes as soon as I enter number in my calculator due to having "null" when getting name for ae.getSource() . Below are what my program looks like and the crash result:

在此处输入图片说明

On above example, program crashes after entering number 2 on input field and pressing "+" button. I was wondering if anyone can guide me on why buttonPressed.getName() on CalculateListener.java returns null value and how to solve this issue.

Thank you for your help in advance.

Simply change

buttonPressed.getName().equals("+")

to

buttonPressed.getText().equals("+")

And do the same for another checks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM