java编写一个简单计算器的界面
时间: 2024-05-04 21:19:20 浏览: 55
java编写的一个简单计算器
以下是一个简单的计算器界面的 Java 代码示例:
```java
import javax.swing.*;
import java.awt.*;
public class Calculator extends JFrame {
private JTextField display;
private JButton button1, button2, button3, button4, button5, button6, button7, button8, button9, button0, buttonPlus, buttonMinus, buttonMultiply, buttonDivide, buttonEquals;
public Calculator() {
super("Calculator");
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
display = new JTextField("");
display.setHorizontalAlignment(JTextField.RIGHT);
display.setEditable(false);
add(display, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4));
button7 = new JButton("7");
buttonPanel.add(button7);
button8 = new JButton("8");
buttonPanel.add(button8);
button9 = new JButton("9");
buttonPanel.add(button9);
buttonPlus = new JButton("+");
buttonPanel.add(buttonPlus);
button4 = new JButton("4");
buttonPanel.add(button4);
button5 = new JButton("5");
buttonPanel.add(button5);
button6 = new JButton("6");
buttonPanel.add(button6);
buttonMinus = new JButton("-");
buttonPanel.add(buttonMinus);
button1 = new JButton("1");
buttonPanel.add(button1);
button2 = new JButton("2");
buttonPanel.add(button2);
button3 = new JButton("3");
buttonPanel.add(button3);
buttonMultiply = new JButton("*");
buttonPanel.add(buttonMultiply);
button0 = new JButton("0");
buttonPanel.add(button0);
buttonEquals = new JButton("=");
buttonPanel.add(buttonEquals);
buttonDivide = new JButton("/");
buttonPanel.add(buttonDivide);
add(buttonPanel, BorderLayout.CENTER);
setVisible(true);
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
}
}
```
这个界面有一个文本框和一个包含数字和操作符按钮的面板。你可以在需要的位置添加事件监听器来实现计算器的功能。
阅读全文