第一次接触Swing,应付一下作业
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* @author feng
* @version 1.0
* <span>基于Swing的简单GUI四则运算器</span>
*/
public class Main {
public static class JFrameCal extends JFrame implements ActionListener {
/**
* 按钮
*/
private JButton []buttons={
new JButton("+"),
new JButton("-"),
new JButton("*"),
new JButton("\\"),
new JButton("重置")
};
/**
* 文本框
*/
private JTextField []textFields={
new JTextField("左操作数:",5),new JTextField(10),
new JTextField("右操作数:",5),new JTextField(10),
new JTextField("计算结果:",5),new JTextField(10)
};
private Container container = getContentPane();
/**
* 构造方法
*/
public JFrameCal(){
super("计算器");
container.setLayout(new FlowLayout());
for (JTextField i:textFields){
i.setEditable(false);
i.setPreferredSize(new Dimension(150,30));//设置大小
container.add(i);
}
textFields[1].setEditable(true);//用户输入框
textFields[3].setEditable(true);//用户输入框
for (JButton b:buttons){
b.addActionListener(this);//监听按钮
container.add(b);
}
buttons[4].setPreferredSize(new Dimension(180,30));//设置重置按钮大小
}
/**
* @param actionEvent
*/
@Override
public void actionPerformed(ActionEvent actionEvent) {
JButton source=(JButton)actionEvent.getSource();
if (source == buttons[0]){//加法运算
Double res = Double.parseDouble(textFields[1].getText())+Double.parseDouble(textFields[3].getText());
textFields[5].setText(res.toString());
} else if (source == buttons[1]){//减法运算
Double res = Double.parseDouble(textFields[1].getText())-Double.parseDouble(textFields[3].getText());
textFields[5].setText(res.toString());
} else if(source == buttons[2]){//乘法运算
Double res = Double.parseDouble(textFields[1].getText())*Double.parseDouble(textFields[3].getText());
textFields[5].setText(res.toString());
} else if(source == buttons[3]){//除法运算
//判断除法是否为0
if (Double.parseDouble(textFields[3].getText()) == 0){
textFields[5].setText("除数不能为0!");
} else {
Double res = Double.parseDouble(textFields[1].getText())+Double.parseDouble(textFields[3].getText());
textFields[5].setText(res.toString());
}
} else{//重置
textFields[1].setText("");
textFields[3].setText("");
textFields[5].setText("");
}
}
}
public static void main(String[] args) {
JFrameCal app = new JFrameCal();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setSize(200,250);
app.setVisible(true);
}
}
运行截图:
深度截图_选择区域_20181221211728.png
网友评论