如何使用java编写一个简易计算器面板
1个回答
展开全部
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Calculator2 extends JPanel{
String[][] lables = {
{"CE","C","Back","%"},
{"7","8","9","/"},
{"4","5","6","*"},
{"1","2","3","+"},
{"0",".","=","-"}
};
JTextField display;
String commands = "CEBack%/*+-=";
private double result;
private String lastCommand;
private boolean start;
public static void main(String[] args) {
JFrame f = new JFrame("Test");
f.setContentPane(new Calculator2());
f.pack();
f.setVisible(true);
f.setDefaultCloseOperation(3);
}
public Calculator2(){
result = 0;
lastCommand = "=";
start = true;
GridBagLayout layout = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
this.setLayout(layout);
gbc.insets = new Insets(1, 1, 1, 1);
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.BOTH;
Dimension dimension = new Dimension(70, 30);
gbc.gridwidth = 4;
display = new JTextField();
display.setPreferredSize(dimension);
display.setHorizontalAlignment(JTextField.RIGHT);
this.add(display, gbc);
ActionListener insert = new InsertAction();
gbc.gridwidth = 1;
for (int i = 0; i < lables.length; i++) {
for (int j = 0; j < lables[0].length; j++) {
gbc.gridx = j;
gbc.gridy = i+1;
JButton b = new JButton(lables[i][j]);
if (j==3)
b.setForeground(Color.RED);
b.setPreferredSize(dimension);
b.addActionListener(insert);
this.add(b,gbc);
}
}
}
private class InsertAction implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
String input = e.getActionCommand();
if(commands.contains(input)){
if(start){
if(input.equals("-")){
display.setText(input);
start =false;
}
} else {
calculate(Double.parseDouble(display.getText()));
lastCommand = input;
start = true;
}
} else {
if(start){
display.setText("");
start = false;
}
display.setText(display.getText() + input);
}
}
}
private void calculate(double x) {
if (lastCommand.equals("+")) result +=x;
else if (lastCommand.equals("-")) result -=x;
else if (lastCommand.equals("*")) result *=x;
else if (lastCommand.equals("/")) result /=x;
else if (lastCommand.equals("=")) result =x;
display.setText("" + result);
}
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询