GridBagLayout计算器界面设计
时间: 2024-05-10 19:18:42 浏览: 131
GridBagLayout是Java Swing中的一种布局管理器,它可以用于创建复杂的用户界面。下面是一个简单的计算器界面设计示例:
```java
import javax.swing.*;
import java.awt.*;
public class CalculatorUI extends JFrame {
private JPanel mainPanel;
private JTextField displayField;
public CalculatorUI() {
setTitle("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 400);
mainPanel = new JPanel(new GridBagLayout());
add(mainPanel);
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
gbc.fill = GridBagConstraints.BOTH;
displayField = new JTextField(15);
displayField.setEditable(false);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 4;
mainPanel.add(displayField, gbc);
JButton button7 = new JButton("7");
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 1;
mainPanel.add(button7, gbc);
JButton button8 = new JButton("8");
gbc.gridx = 1;
gbc.gridy = 1;
mainPanel.add(button8, gbc);
JButton button9 = new JButton("9");
gbc.gridx = 2;
gbc.gridy = 1;
mainPanel.add(button9, gbc);
JButton buttonDivide = new JButton("/");
gbc.gridx = 3;
gbc.gridy = 1;
mainPanel.add(buttonDivide, gbc);
JButton button4 = new JButton("4");
gbc.gridx = 0;
gbc.gridy = 2;
mainPanel.add(button4, gbc);
JButton button5 = new JButton("5");
gbc.gridx = 1;
gbc.gridy = 2;
mainPanel.add(button5, gbc);
JButton button6 = new JButton("6");
gbc.gridx = 2;
gbc.gridy = 2;
mainPanel.add(button6, gbc);
JButton buttonMultiply = new JButton("*");
gbc.gridx = 3;
gbc.gridy = 2;
mainPanel.add(buttonMultiply, gbc);
JButton button1 = new JButton("1");
gbc.gridx = 0;
gbc.gridy = 3;
mainPanel.add(button1, gbc);
JButton button2 = new JButton("2");
gbc.gridx = 1;
gbc.gridy = 3;
mainPanel.add(button2, gbc);
JButton button3 = new JButton("3");
gbc.gridx = 2;
gbc.gridy = 3;
mainPanel.add(button3, gbc);
JButton buttonMinus = new JButton("-");
gbc.gridx = 3;
gbc.gridy = 3;
mainPanel.add(buttonMinus, gbc);
JButton button0 = new JButton("0");
gbc.gridx = 0;
gbc.gridy = 4;
gbc.gridwidth = 2;
mainPanel.add(button0, gbc);
JButton buttonDecimal = new JButton(".");
gbc.gridx = 2;
gbc.gridy = 4;
gbc.gridwidth = 1;
mainPanel.add(buttonDecimal, gbc);
JButton buttonPlus = new JButton("+");
gbc.gridx = 3;
gbc.gridy = 4;
mainPanel.add(buttonPlus, gbc);
JButton buttonClear = new JButton("C");
gbc.gridx = 0;
gbc.gridy = 5;
gbc.gridwidth = 2;
mainPanel.add(buttonClear, gbc);
JButton buttonEquals = new JButton("=");
gbc.gridx = 2;
gbc.gridy = 5;
gbc.gridwidth = 2;
mainPanel.add(buttonEquals, gbc);
setVisible(true);
}
public static void main(String[] args) {
CalculatorUI calculator = new CalculatorUI();
}
}
```
上述代码中,我们创建了一个CalculatorUI类,继承自JFrame类,并在构造函数中设置了窗口标题、关闭操作和大小。然后,我们创建了一个GridBagLayout布局管理器,并将其设置为主面板的布局管理器。
接下来,我们使用GridBagConstraints类来设置每个组件的位置和大小。例如,我们使用gbc.gridx和gbc.gridy属性来设置每个组件的行和列。我们使用gbc.gridwidth和gbc.gridheight属性来设置每个组件的宽度和高度。
最后,我们将每个组件添加到主面板中,并将窗口设置为可见。
这个示例界面只是一个简单的计算器,但是你可以根据自己的需求添加更多的组件和功能。
阅读全文