Java作业二(下)

题目

编写一个应用程序,有一个标题为“计算”的窗口,窗口布局为FlowLayout布局,设计4个按钮,分别命名为“加”、“减”、”乘”、“除”,另外窗口中还有3个文本框。单击相应的按钮,将两个文本框中的数字做运算,第三个文本框中显示结果。要求处理NumberFormatException异常。(即P280 3编程题的第(2)题)

代码

package homework;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

class Window extends JFrame implements ActionListener{
	JButton jia;
	JButton jian;
	JButton cheng;
	JButton chu;
	JTextField text1;
	JTextField text2;
	JTextField text3;
	public Window() {
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		jia = new JButton("加");
		jian = new JButton("减");
		cheng = new JButton("乘");
		chu = new JButton("除");
		text1 = new JTextField(4);
		text2 = new JTextField(4);
		text3 = new JTextField(8);
		add(jia);
		add(jian);
		add(cheng);
		add(chu);
		add(text1);
		add(text2);
		add(text3);
		jia.addActionListener(this);
		jian.addActionListener(this);
		cheng.addActionListener(this);
		chu.addActionListener(this);
	}
	public void actionPerformed(ActionEvent e) {
		try {
			Double a = Double.parseDouble(text1.getText());
			Double b = Double.parseDouble(text2.getText());
			if(e.getSource() == jia) { 
				String result = String.valueOf(a+b);
				text3.setText(result);
			}else if(e.getSource() == jian) {
				String result = String.valueOf(a-b);
				text3.setText(result);
			}else if(e.getSource() == cheng) {
				String result = String.valueOf(a*b);
				text3.setText(result);
			}else if(e.getSource() == chu) {
				String result = String.valueOf(a/b);
				text3.setText(result);
			}
		}
		catch(NumberFormatException e1){
			JOptionPane.showMessageDialog(null, "有非法字符");
		}
	}
}
public class Work_2 {
	public static void main(String[] args) {
		Window win = new Window();
		win.setLayout(new FlowLayout());
		win.setTitle("计算");
		win.setVisible(true);
		win.setSize(360,250);
	}
}

 

1.腾龙梦屋文章内容无特殊注明皆为源儿原创,转载请注明来源,谢谢!
2.若有相关文章侵犯您的权益,请联系源儿删除,谢谢!
3.相关软件、资料仅供学习参考使用,在24h内务必删除!
腾龙梦屋 » Java作业二(下)
加速支持