【发布时间】:2021-08-02 18:33:03
【问题描述】:
我正在学习 JSwing,我发现了 GridBagLayout。
我正在尝试创建一个简单的计算器,我通过添加多个 JPanel 设置每个preferedSize 来做到这一点,但是当我调整窗口框架的大小时,面板也不会调整大小。 然后我发现了 GridBagLayout。
但这就是我得到的:Wrong calculator with GridBagLayout
import javax.swing.*;
import java.awt.*;
public class Calc extends JFrame {
private final int WIDTH = 300;
private final int HEIGHT = 450;
public Calc(){
setSize(WIDTH, HEIGHT);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.add(createButtons(), BorderLayout.SOUTH);
add(mainPanel);
}
private JPanel createButtons(){
JPanel panel = new JPanel();
GridBagLayout layout = new GridBagLayout();
panel.setLayout(layout);
GridBagConstraints g = new GridBagConstraints();
g.gridx = 0;
g.gridy = 0;
for(int i = 0; i < 9; i++){
panel.add(new JButton(""+i), g);
g.gridx++;
if(g.gridx == 3) {
g.gridx = 0;
g.gridy++;
}
}
return panel;
}
public static void main(String... args){
Calc calc = new Calc();
calc.setVisible(true);
}
}
应该是这样的: Right calculator
我试过了:
- 设置锚点...但它不起作用,
- 创建多个 JPanel(一个带有 GridLayout)但不起作用
如果你不想用勺子编码,没关系.. 但我应该从哪里开始呢?
编辑: 我弄清楚如何排列按钮......但我无法将标题设置为填充所有 x 轴: 代码:
import javax.swing.*;
import java.awt.*;
public class ButtonPanel extends JPanel {
JPanel top;
JPanel left;
JPanel right;
private class CButton extends JButton{
private Operation operation;
public CButton(){
}
}
public ButtonPanel(){
initComponent();
initLayout();
}
private void initLayout() {
GridBagLayout layout = new GridBagLayout();
this.setLayout(layout);
layout.columnWeights = new double[] {3,1};
layout.rowWeights = new double[] {1, 1};
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.BOTH;
c.weightx = 5;
this.add(top, c);
c.gridy++;
c.weighty=1;
this.add(left, c);
c.gridx++;
this.add(right, c);
}
private void initComponent() {
top = new JPanel();
top.setLayout(new GridLayout(1, 3));
for(int i = 0; i < 3; i++){
top.add(new JButton("bbb"));
}
left = new JPanel();
left.setLayout(new GridLayout(3,3));
for(int i = 0; i < 9; i++){
left.add(new JButton(""+i));
}
right = new JPanel();
right.setLayout(new GridLayout(3,1));
for(int i = 0; i < 3; i++){
JButton btn = new JButton("aa");
right.add(btn);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("test");
frame.setLayout(new BorderLayout());
frame.add(new ButtonPanel(), BorderLayout.SOUTH);
frame.setSize(300, 450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
应该是:Image
【问题讨论】:
标签: java swing layout-manager gridbaglayout