JAVA图形用户界面

设计要求:用户自己输入两数,选择加减乘除中的一种算法,由计算机计算出答案。在出错的时候,如输入的不是有效数值,设计弹出对话框给出相应的提示。

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);

}

}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-04-07
用 swing 开发
相似回答