一个简单的计算器界面实现

时间:2022-12-29 14:30:48
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 backSpaceclearUp;

    
JTextField display;

    
JPanel p1p2;

    
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(45));
        
String buttons "779/a456*b123-%0.c+=";
        
for (int 0buttons.length(); i++)
        {
            
char temp buttons.charAt(i);
            
addButton(p2temp);
        }
        
this.addWindowListener(new WindowAdapter()
        {
            
@Override
            
public void windowClosing(WindowEvent e)
            {
                
System.exit(0);
            }
        });
        
this.setTitle("Calculater");
        
this.setLayout(new BorderLayout());
        
this.add(displayBorderLayout.NORTH);
        
this.add(p1BorderLayout.CENTER);
        
this.add(p2BorderLayout.SOUTH);
        
this.pack();
        
this.setResizable(false);
        
this.setVisible(true);
    }

    
private void addButton(Container cchar 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();
    }
}