[英]Need some advice with my ActionListener in Java
我目前正在使用 Java(初学者)开发一个程序,我需要一些帮助才能让我的按钮在 GUI 中实际工作。 我将我的代码复制到帖子的底部。 我已经编写了我的 ActionEvents 方法,感觉我离 if 语句越来越近了,但我仍然感到困惑。 我试图实现“result.setText(”给定两个数字的总和是“+ res”); 并让我的按钮工作,但我只是不知道下一步去哪里 go。
任何意见或建议将不胜感激!
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class ButtonActionOne extends JFrame implements ActionListener {
JButton add, subtract, multiply, divide;
JLabel operand1, operand2, display;
JTextField op1, op2, result;
Integer num1, num2;
public ButtonActionOne() {
setSize(250, 400);
setTitle("Button Action");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
operand1 = new JLabel("Operand 1:");
operand2 = new JLabel("Operand 2:");
display = new JLabel("Output:");
add = new JButton("Add");
add.addActionListener(this);
subtract = new JButton("Subtract");
subtract.addActionListener(this);
multiply = new JButton("Multiply");
multiply.addActionListener(this);
divide = new JButton("Divide");
divide.addActionListener(this);
result = new JTextField(50);
op1 = new JTextField(10);
op1.getText();
op1.addActionListener((ActionListener) this);
op2 = new JTextField(10);
op2.getText();
op2.addActionListener((ActionListener) this);
int num1 = Integer.parseInt(op1.getText());
int num2 = Integer.parseInt(op2.getText());
add(operand1);
add(op1);
add(operand2);
add(op2);
add(add);
add(subtract);
add(multiply);
add(divide);
add(display);
add(result);
setVisible(true);
}
public static void main(String args[]) {
new ButtonActionOne();
}
public void actionPerformed(ActionEvent ae) {
Object o = ae.getSource();
if(o == add) {
result.setText("The sum of the given numbers is " );
System.out.println(result);
}
if(o == subtract) {
System.out.println();
} if(o == multiply)
System.out.println();
if(o == divide) {
System.out.println();
}
}
}
调出 GUI 时我没有收到任何错误,但我不知道如何或何时使用我的 getText。 我还声明了两个整数并使用了“parseInt”,但我仍然不知道如何继续让我的按钮工作! 先感谢您!
您只有一个 actionPerformed 方法(只有一个侦听器),但将它绑定到所有 UI 对象:添加/减去按钮和 JTextFields,这意味着它甚至会在用户执行输入并按下回车键时被调用。
因此,您必须检查调用该方法的原因。 您的 actionPerformed 方法应如下所示。 它不完整,但我想你明白了。
public void actionPerformed(ActionEvent ae) {
try {
if (ae.getSource()==add) {
o1 = Integer.parseInt(op1.getText());
o2 = Integer.parseInt(op3.getText());
result.setText(String.format("%d + %d = %d", o1, o2, o1+o2));
}
if (ae.getSource()==subtract) {
o1 = Integer.parseInt(op1.getText());
o2 = Integer.parseInt(op3.getText());
result.setText(String.format("%d - %d = %d", o1, o2, o1-o2));
}
} catch (Exception e) {
result.setText("Could not calculate");
e.printStackTrace(System.out);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.