我尝试制作一个简单的计算器,如下图所示。但我想写:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
number1 = Integer.parseInt(n1.getText());
number2 = Integer.parseInt(n2.getText());
JOptionPane.showMessageDialog(null,(number1+number2));
每个按钮都有这个代码所以我怎样才能通过在一个公共场所声明来实现呢
答案 0 :(得分:2)
一些简单的辅助方法怎么样?
private int getNumber1() {
return Integer.parseInt(n1.getText());
}
private int getNumber2() {
return Integer.parseInt(n2.getText());
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
JOptionPane.showMessageDialog(null, getNumber1() + getNumber2());
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{
JOptionPane.showMessageDialog(null, getNumber1() - getNumber2());
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt)
{
JOptionPane.showMessageDialog(null, getNumber1() * getNumber2());
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt)
{
JOptionPane.showMessageDialog(null, getNumber1() / getNumber2());
}
答案 1 :(得分:1)
为操作定义枚举:
enum Operation {
PLUS {
@Override int operate(int a, int b) { return a + b; }
},
MINUS {
@Override int operate(int a, int b) { return a - b; }
},
// etc, for others.
;
abstract int operate(int a, int b);
}
然后定义一个ActionListener
子类,它将Operation
作为参数:
class MyActionListener implements ActionListener {
final Operation operation;
MyActionListener(Operation operation) {
this.operation = operation;
}
@Override public void actionPerformed(ActionEvent evt) {
int a = Integer.parseInt(n1.getText());
int b = Integer.parseInt(n2.getText());
int result = operation.operate(a, b);
JOptionPane.showMessageDialog(null, result);
}
}
然后将此类的实例添加为每个按钮的事件侦听器:
jButton1.addActionListener(new MyActionListener(Operation.PLUS));
jButton2.addActionListener(new MyActionListener(Operation.MINUS));