发布网友 发布时间:2022-05-15 16:45
共2个回答
热心网友 时间:2024-02-25 08:39
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class Test {
public static void main(String[] args) {
JFrame jf = new JFrame("简易计算器");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setBounds(0, 0, 400, 150);
jf.setLayout(null);
final JTextField text1 = new JTextField();
text1.setBounds(5, 5, 90, 30);
jf.add(text1);
final JTextField text2 = new JTextField();
text2.setBounds(150, 5, 90, 30);
jf.add(text2);
final JTextField text3 = new JTextField();
text3.setBounds(300, 5, 90, 30);
jf.add(text3);
final JComboBox comboBox = new JComboBox();
comboBox.setBounds(100, 5, 40, 30);
comboBox.addItem("+");
comboBox.addItem("-");
comboBox.addItem("×");
comboBox.addItem("÷");
jf.add(comboBox);
JButton button = new JButton("=");
button.setBounds(245, 5, 50, 30);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
int result = 0;
int in1 = Integer.parseInt(text1.getText());
int in2 = Integer.parseInt(text2.getText());
switch(comboBox.getSelectedIndex()) {
case 0 : //加法
result = in1 + in2; break;
case 1 : //减法
result = in1 - in2; break;
case 2 : //乘法
result = in1 * in2; break;
case 3 : //除法
result = in1 / in2; break;
}
text3.setText(result + "");
} catch(NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "不是有效数字");
}
}
});
jf.add(button);
jf.setVisible(true);
}
}
热心网友 时间:2024-02-25 08:39
用 swing 开发