我将所有这些都放在一个文件中。我试图从文本字段 jtfNumber1 和 jtfNumber2 中获取 int,然后根据将哪个按钮按下到 jtfResult 中来显示操作的结果。我有按钮工作。他们目前显示一条测试消息。我坚持从文本字段中获取字符串。
public class Calculator extends JFrame {
// Create Buttons and fields
private JButton jbtAdd = new JButton("Add");
private JButton jbtSub = new JButton("Subtract");
private JButton jbtMul = new JButton("Multiply");
private JButton jbtDiv = new JButton("Divide");
private JTextField jtfNumber1 = new JTextField(8);
private JTextField jtfNumber2 = new JTextField(8);
private JTextField jtfResponse = new JTextField(8);
public Calculator() {
//Create Panel
JPanel panel = new JPanel();
panel.add(new JLabel("Number 1"));
panel.add(jtfNumber1);
panel.add(new JLabel("Number 2"));
panel.add(jtfNumber2);
panel.add(new JLabel("Result"));
panel.add(jtfResponse);
panel.add(jbtAdd);
panel.add(jbtSub);
panel.add(jbtMul);
panel.add(jbtDiv);
add(panel);
BtnListener listener = new BtnListener();
jbtAdd.addActionListener(listener);
jbtSub.addActionListener(listener);
jbtMul.addActionListener(listener);
jbtDiv.addActionListener(listener);
}
class JtfListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
int x = Intenger.parseInt(jtfNumber1.getText());
}
}
class BtnListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == jbtAdd) {
System.out.println("Test Test Test");
} else if (e.getSource() == jbtSub) {
System.out.println("Test Test Test");
} else if (e.getSource() == jbtMul) {
System.out.println("Test Test Test");
} else if (e.getSource() == jbtDiv) {
System.out.println("Test Test Test");
}
}
}
public static void main(String[] args) {
JFrame frame = new Calculator();
frame.setTitle("Calculator");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}