我使用 GridLayout 方法在 java 中编写了一个计算器。我没有考虑到它无法设置不同大小的按钮这一事实。因此,我试图找到一种解决方法,因为我无法弄清楚如何将 GridBagLayout 实现到我的代码中。
目前我的代码的结果如下所示: My current JFrame Design
但是,我试图让它看起来像这样: How I want the design to look
public static void main(String[] args){
JFrame frame = new JFrame("Calculator");
Container content = frame.getContentPane();
ActionListener AL = new Calculator();
content.setLayout((new BorderLayout()));
JPanel panel1 = new JPanel(new BorderLayout());
panel1.add(new JLabel("CSC 20 Lab 08", JLabel.CENTER), BorderLayout.NORTH);
text = new JTextField("0.");
text.addActionListener(AL);
panel1.add( text, BorderLayout.SOUTH);
text.setHorizontalAlignment(JTextField.RIGHT);
content.add(panel1, BorderLayout.NORTH);
JPanel panel2 = new JPanel(new GridLayout(4, 5));
for (int i=1; i < 8; i = i + 3){
...adding numerical button in panel2...
...adding more buttons in panel2...
}
JPanel panel2b = new JPanel(new GridLayout(1, 2));
clearButton = new JButton("C");
panel2b.add(clearButton);
gridbag.setConstraints(clearButton, c);
...add "clear" functionality...
panel2.add(panel2b);
...adding more buttons in panel2...
content.add(panel2, BorderLayout.CENTER);
JPanel panel3 = new JPanel(new GridLayout(1, 3));
equalButton = new JButton("=");
panel3.add(equalButton);
equalButton.addActionListener(AL);
content.add(panel3, BorderLayout.SOUTH);
... more code
如何最轻松地实现此操作以更改“C”按钮大小?
最佳答案
这是您的案例的代码片段。解释在评论中。
// Creating a panel with Grid**Bag**Layout
final JPanel pane = new JPanel(new GridBagLayout());
// Setup constraints to future use
final GridBagConstraints c = new GridBagConstraints();
// Let columns to expand horizontally,
// while keeping the same width
c.weightx = 1;
// The same for rows
c.weighty = 1;
// Let the buttons to occupy entire cells
c.fill = GridBagConstraints.BOTH;
c.gridy = 0; // Starting the first row
pane.add(new JButton("1"), c);
pane.add(new JButton("2"), c);
pane.add(new JButton("3"), c);
pane.add(new JButton("+"), c);
c.gridy++; // Switching to next row
pane.add(new JButton("4"), c);
pane.add(new JButton("5"), c);
pane.add(new JButton("6"), c);
pane.add(new JButton("-"), c);
c.gridy++;
pane.add(new JButton("7"), c);
pane.add(new JButton("8"), c);
pane.add(new JButton("9"), c);
pane.add(new JButton("*"), c);
c.gridy++;
// Let the "C" button have double width
c.gridwidth = 2;
pane.add(new JButton("C"), c);
// Resets to default width for the following buttons
c.gridwidth = 1;
pane.add(new JButton("0"), c);
pane.add(new JButton("/"), c);
c.gridy++;
// Making "=" button have quadruple width
c.gridwidth = 4;
pane.add(new JButton("="), c);
更多信息请参见 How to Use GridBagLayout Java 教程部分。
关于java - 如何在 java 中实现 Flowlayout 以便我的 GridLayout 可以有不同大小的按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40459363/