[英]Should i use different instances of a single ActionListener for multiple buttons?
[英]single actionlistener for multiple buttons
谁能帮助我如何在多个按钮上添加单个动作侦听器? 这是我的多个按钮的多动作侦听器代码。 我还尝试将一个通用按钮用作所有按钮的动作侦听器。 任何人都可以建议我一个相关的答案。 我是初学者,我对Java没有太多了解。
import java.awt.event.ActionListener;
import javax.swing.*;
public class Calculator {
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame frame = new JFrame(); //object of JFrame
JLabel firstValue, secondValue, result, answer; //declaration of JLabel
JTextField one, two; //declaration of JTextField
JButton addition, subtraction, multiplication, division; //declaration of JButton
//Label for first value
firstValue = new JLabel("First Value:");
firstValue.setBounds(50,70,100,30);
frame.add(firstValue);
//Label for second value
secondValue = new JLabel("Second Value:");
secondValue.setBounds(50,120,100,30);
frame.add(secondValue);
//TextFields for first value
one = new JTextField();
one.setBounds(170, 70, 105, 30);
frame.add(one);
//TextFields for second value
two = new JTextField();
two.setBounds(170, 120, 105, 30);
frame.add(two);
//Button for addition
addition = new JButton("+");
addition.setBounds(50, 170, 45, 30);
frame.add(addition);
//Button for subtraction
subtraction = new JButton("-");
subtraction.setBounds(110, 170, 45, 30);
frame.add(subtraction);
//Button for multiplication
multiplication = new JButton("*");
multiplication.setBounds(170, 170, 45, 30);
frame.add(multiplication);
//Button for division
division = new JButton("/");
division.setBounds(230, 170, 45, 30);
frame.add(division);
//Label for Result
result = new JLabel("Result");
result.setBounds(50, 220, 100, 30);
frame.add(result);
//TextFields for first value
answer = new JLabel();
answer.setBounds(170, 220, 105, 30);
frame.add(answer);
//actionListener for addition button
addition.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//logic for addition
int finalAnswer = Integer.parseInt(one.getText()) + Integer.parseInt(two.getText());
answer.setText(Integer.toString(finalAnswer));
}
});
//actionListener for subtraction button
subtraction.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//logic for addition
int finalAnswer = Integer.parseInt(one.getText()) - Integer.parseInt(two.getText());
answer.setText(Integer.toString(finalAnswer));
}
});
//actionListener for multiplication button
multiplication.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//logic for addition
int finalAnswer = Integer.parseInt(one.getText()) * Integer.parseInt(two.getText());
answer.setText(Integer.toString(finalAnswer));
}
});
//actionListener for division button
division.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//logic for addition
int finalAnswer = Integer.parseInt(one.getText()) / Integer.parseInt(two.getText());
answer.setText(Integer.toString(finalAnswer));
}
});
frame.setSize(400,400); //set size of JFrame with width and height
frame.setLayout(null); //set layout type by null
frame.setVisible(true); //set JFrame visible by boolean value true/false
}
}
通常,您会执行以下操作(您可以将其附加到您的 Calculator 类中):
class Calculator {
private JButton subtraction;
public static void main(String[] args) {
// your code
// button example
subtraction = new JButton("-");
subtraction.addActionListener(new Listener());
// your code
}
class Listener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == nameOfJButton) {
// do the action for this button
} else if (e.getSource() == nameOfAnotherButton) {
// you get the idea
}
}
}
}
现在,您可以像这样更改代码:
// actionListener for addition button
addition.addActionListener(new Listener());
这是针对您的问题的一些高级解决方案。 主要思想是将您的操作作为您的操作的参数。 此外,我使用类AbstractAction
而不是ActionListener
来定义按钮。 它允许结合文本和动作。 所以代码看起来更小更智能。
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.util.function.BiFunction;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.border.EmptyBorder;
/**
* <code>ButtonExample</code>.
*/
public class ButtonExample {
private JTextField one, two;
private final JLabel answer = new JLabel();
private class ArithmeticAction extends AbstractAction {
private final BiFunction<Integer, Integer, Integer> arithmeticFunction;
public ArithmeticAction(String name, BiFunction<Integer, Integer, Integer> arithmeticFunction) {
super(name); // set name of button
this.arithmeticFunction = arithmeticFunction;
}
@Override
public void actionPerformed(ActionEvent e) {
Integer firstOperand = Integer.valueOf(one.getText());
Integer secondOperand = Integer.valueOf(two.getText());
Integer result = arithmeticFunction.apply(firstOperand, secondOperand);
answer.setText(result.toString());
}
}
private void initUI() {
one = new JTextField(5);
two = new JTextField(5);
JPanel panel = new JPanel(new GridLayout(3, 2, 5, 5));
panel.add(new JLabel("First value:"));
panel.add(one);
panel.add(new JLabel("Second value:"));
panel.add(two);
panel.add(new JLabel("Result:"));
panel.add(answer);
panel.setBorder(new EmptyBorder(0, 5, 0, 5));
JPanel operations = new JPanel();
operations.add(new JButton(new ArithmeticAction("+", (a, b) -> a + b)));
operations.add(new JButton(new ArithmeticAction("-", (a, b) -> a - b)));
operations.add(new JButton(new ArithmeticAction("*", (a, b) -> a * b)));
operations.add(new JButton(new ArithmeticAction("/", (a, b) -> a / b)));
JFrame frm = new JFrame();
frm.add(panel);
frm.add(operations, BorderLayout.NORTH);
frm.pack();
frm.setLocationRelativeTo(null);
frm.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frm.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new ButtonExample()::initUI);
}
}
小解释:
BiFunction
是一个标准接口,它变成两个参数,并返回一个值。 你可以像这样实现它:
BiFunction<Integer, Integer, Integer> sum = (a, b) -> a + b;
这意味着该函数接受两个参数: a
和b
并返回值a + b
。 这种可能性是在 Java 8 中添加的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.