import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Calculator extends JFrame
{
JButton backSpace, clearUp;
JTextField display;
JPanel p1, p2;
public Calculator()
{
backSpace = new JButton("BackSpace");
clearUp = new JButton("ClearUp");
backSpace.setForeground(Color.RED);
clearUp.setForeground(Color.RED);
display = new JTextField("0");
display.setEditable(false);
display.setBackground(Color.WHITE);
display.setHorizontalAlignment(JTextField.RIGHT);
p1 = new JPanel();
p1.setLayout(new FlowLayout());
p1.add(backSpace);
p1.add(clearUp);
p2 = new JPanel();
p2.setLayout(new GridLayout(4, 5));
String buttons = "779/a456*b123-%0.c+=";
for (int i = 0; i < buttons.length(); i++)
{
char temp = buttons.charAt(i);
addButton(p2, temp);
}
this.addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
this.setTitle("Calculater");
this.setLayout(new BorderLayout());
this.add(display, BorderLayout.NORTH);
this.add(p1, BorderLayout.CENTER);
this.add(p2, BorderLayout.SOUTH);
this.pack();
this.setResizable(false);
this.setVisible(true);
}
private void addButton(Container c, char temp)
{
String bText = null;
switch (temp)
{
case 'a':
bText = "Sqrt";
break;
case 'b':
bText = "1/x";
break;
case 'c':
bText = "-/+";
break;
default:
bText = String.valueOf(temp);
break;
}
JButton b = new JButton(bText);
b.setForeground(Color.blue);
c.add(b);
}
public static void main(String[] args)
{
new Calculator();
}
}
一个简单的计算器界面实现
最新推荐文章于 2022-07-12 14:43:25 发布