实现代码:
package test;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener {
JTextField jtf = new JTextField();
public Calculator() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jtf.setHorizontalAlignment(JTextField.RIGHT);
Container c = this.getContentPane();
JPanel jpl = new JPanel();
c.add(jtf, BorderLayout.NORTH);
c.add(jpl, BorderLayout.CENTER);
jpl.setLayout(new GridLayout(4, 4));
JButton b = null;
b = new JButton("1");
b.addActionListener(this);
jpl.add(b);
b = new JButton("2");
b.addActionListener(this);
jpl.add(b);
b = new JButton("3");
b.addActionListener(this);
jpl.add(b);
b = new JButton("+");
b.addActionListener(this);
jpl.add(b);
b = new JButton("4");
b.addActionListener(this);
jpl.add(b);
b = new JButton("5");
b.addActionListener(this);
jpl.add(b);
b = new JButton("6");
b.addActionListener(this);
jpl.add(b);
b = new JButton("-");
b.addActionListener(this);
jpl.add(b);
b = new JButton("7");
b.addActionListener(this);
jpl.add(b);
b = new JButton("8");
b.addActionListener(this);
jpl.add(b);
b = new JButton("9");
b.addActionListener(this);
jpl.add(b);
b = new JButton("*");
b.addActionListener(this);
jpl.add(b);
b = new JButton("0");
b.addActionListener(this);
jpl.add(b);
b = new JButton(".");
b.addActionListener(this);
jpl.add(b);
b = new JButton("=");
b.addActionListener(this);
jpl.add(b);
b = new JButton("/");
b.addActionListener(this);
jpl.add(b);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Starting TestMyButton...");
Calculator mainFrame = new Calculator();
mainFrame.setSize(400, 400);
mainFrame.setTitle("TestButton");
mainFrame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
jtf.setText(jtf.getText() + e.getActionCommand());
}
}
运行结果:
此程序还可以使用BoxLayout布局管理器实现,此程序只实现了界面,没有实现运算。