目录
1、算数运算
编写一个应用程序,设计一个窗体,其中有一个JCombox组件(+、-、*、/),以及2个文本框和一个富文本框,单击相应的按钮,将两个文本框的数字做算术运算,在第3个文本框中显示结果。要求处理NumberFormatException。
package OOP.work.Test8.T1;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
public class JCombox extends JFrame {
public JCombox(String str){
setTitle(str);
init();
}
public void init(){
setSize(500,500);
JButton button=new JButton("计算");
JPanel jPanel=new JPanel();
JTextField s1=new JTextField(10);//定义文本框
JComboBox <String> comboBox=new JComboBox<>();
add(jPanel,BorderLayout.PAGE_START);
comboBox.addItem("+");
comboBox.addItem("-");
comboBox.addItem("*");
comboBox.addItem("/");
JTextField s2=new JTextField(10);//定义文本框
JTextArea fu=new JTextArea(10,20);
setLayout(new FlowLayout());
add(s1);
add(comboBox);
add(s2);
add(button);
add(fu);
button.addActionListener(new AbstractAction() {
//输出相应事件
@Override
public void actionPerformed(ActionEvent e) {
String shu1=s1.getText();
String shu2=s2.getText();
try{
int sh1=Integer.parseInt(shu1);
int sh2=Integer.parseInt(shu2);
String fuhao=(String)comboBox.getSelectedItem();
int sum = 0;
//两种判断语句,哪种都可以
/*if(fuhao == "+"){
sum=sh1+sh2;
}else if (fuhao == "-"){
sum=sh1-sh2;
}else if (fuhao == "*"){
sum=sh1*sh2;
}else if (fuhao == "/"){
sum= sh1 / sh2 ;
}*/
switch (fuhao){
case "+":
sum=sh1+sh2;
break;
case "-":
sum=sh1-sh2;
break;
case "*":
sum=sh1*sh2;
break;
case "/":
sum=sh1/sh2;
break;
}
String result=shu1+fuhao+shu2+"="+sum;
String dou=fu.getText();
fu.setText(dou+"\n"+result);
//fu.setText(shu1+fuhao+shu2+"="+sum);
}catch (NumberFormatException ne){
ne.printStackTrace();
}
}
});
setVisible