基于Swing的简单界面设计
通过对GUI程序设计的了解,让我们来实现一下可视化简易计算器
设计思路:
1.创造计算机类
2.设置顶层容器窗口的属性:默认关闭时间,大小,布局,操作,输入的数据和结果
3.向顶层容器添加GUI组件:显示文本框,结果文本框,一些操作按钮
4.设置按钮的布局
5.可视化显示方程窗口和计算结果窗口
6.给按钮添加事件响应(成员内部类:匹配操作命令)
7.主入口应用SwingUtilities类中的invokeLater方法,传参:实现run方法
代码实现:
package shixun;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Calculator{
private JFrame frame;//窗口
private JTextField equationField;//显示文本框
private JTextField resultField;//结果文本框
private String operator;//操作属性
private double num1, num2, result;
public Calculator() {
createUI();
}
private void createUI() {
frame = new JFrame("计算器");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 250);
frame.setLayout(new BorderLayout());
equationField = new JTextField();
resultField = new JTextField();
equationField.setEditable(false);
resultField.setEditable(false);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4, 5, 5));
String[] buttonLabels = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", "CE", "=", "+"
};
for (String label : buttonLabels) {
JButton button = new JButton(label);
button.addActionListener(new ButtonClickListener());
buttonPanel.add(button);
}
//可视化显示方程窗口和计算结果窗口
frame.add(equationField, BorderLayout.NORTH);
frame.add(resultField, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.SOUTH);
frame.setVisible(true);
}
//给每个按钮添加事件监听(成员内部类)
private class ButtonClickListener implements ActionListener {
public void actionPerformed(ActionEvent e) {//ActionListener接口中包含的唯一一个方法,实现他可处理点击按键事件
String command = e.getActionCommand();
switch (command) {
case "CE"://
equationField.setText("");
resultField.setText("");
break;
case "=":
num2 = Double.parseDouble(resultField.getText());
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num1 / num2;
break;
}
resultField.setText(String.valueOf(result));
equationField.setText("");
break;
default://其他情况
//输入非法情况即命令不是运算符,是数字
if ("0123456789".contains(command)) {
resultField.setText(resultField.getText() + command);
} else {
operator = command;
num1 = Double.parseDouble(resultField.getText());
equationField.setText(resultField.getText() + " " + operator + " ");
resultField.setText("");
}
break;
}
}
}
public static void main(String[] args) {
//匿名内部类:SwingUtilities类中的invokeLater方法:
//在应用程序线程需要更新该 GUI 时使用。
SwingUtilities.invokeLater(new Runnable() {
public void run() {//新建运行对象并重写里面的run方法
new Calculator();//新建Work对象,让程序运行
}
});
}
}
注意点:
1、我们尽量把搭建Swing界面的代码封装到成员方法中,在我们的主方法中尽量减少代码的数量,以降低报错率。
2、去实现ActionListener事件监听类时,我们可以采用成员内部类的方式去重写ActionPerformed方法,以便用于外部类使用其属性。
3、在根容器Label中添加按钮时,你也可以逐个添加。我这里采用数组和增强for循环遍历时创建
按钮对象来添加。
4、一定要有Calculator空参构造方法(便于main方法中去运行创建Calculator对象)
补充:
在创建Calculator对象时,我们可以使用SwingUtilities类中的invokeLater方法去新建运行对象,并重写其方法,达到对象可视化。该方法详细内容可以查看API文档。