Java - GUI -计算器界面(附效果图)
设计图
下面大部分都标好了注释,话不多说,上代码,需要的小伙伴自己复制(适合菜鸟,大佬划走)
public class Computer2 extends JFrame{ private JTextField textField; //显示操作结果的文本框 JTextField txfM;//显示记忆的索引值的文本框 Double dM = 0d;//存储数据 public Computer2(){ super("简易计算器"); /*文本框设置*/ textField = new JTextField("0",30); textField.setBackground(Color.WHITE); //文本框颜色 textField.setHorizontalAlignment(JTextField.RIGHT); //文本靠右显示 textField.setEditable(false); //文本框不可编辑,只可读 JPanel ResultTextPanel = new JPanel(); //放置文本框的面板 ResultTextPanel.add(textField); //把文本框放置到面板当中 /* 数字和运算符*/ String dcKey[] = {"1","2","3","Backspace","4","5","6","+","7","8","9","-", "0","*","/","="}; JPanel dcKeyPanel = new JPanel(); //放置字符键盘的面板 dcKeyPanel.setLayout(new GridLayout(4,4)); //利用for循环放好所有键 for (int i=0;i< 16;i++){ JButton b = new JButton(dcKey[i]); dcKeyPanel.add(b); } Container ct = this.getContentPane();//窗体内容面板对象 ct.setLayout(new BorderLayout()); ct.add(ResultTextPanel, BorderLayout.NORTH); ct.add(dcKeyPanel, BorderLayout.SOUTH); pack(); setVisible(true); //窗口可见 // setResizable(false);//禁止最大化 setLocationRelativeTo(null);//居中显示 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //窗口可关闭 } public static void main(String[] args) { new Computer2(); } }
键无实际功能,下次把设置好监听器的代码分享给大家(还在学习)
运行效果: