gpt4 book ai didi

java - 去除gridBagLayout中组件之间的间隙

转载 作者:行者123 更新时间:2023-12-02 05:48:25 27 4
gpt4 key购买 nike

这是我的课:

public class Main extends JFrame{
private Container container;
private GridBagConstraints cons;
private JPanel panelDisplay;
private int curX = 0, curY = 0;

public Main() {
initComp();
}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Main ex = new Main();
ex.setVisible(true);
}
});
}

private void initComp()
{
container = this.getContentPane();
container.setLayout(new GridBagLayout());
cons = new GridBagConstraints();

cons.gridx = 0;
cons.gridy = 0;
container.add(new PanelNot(), cons);


panelDisplay = new JPanel();
panelDisplay.setBackground(Color.blue);
panelDisplay.setPreferredSize(new Dimension(600, 400));
panelDisplay.setLayout(new GridBagLayout());
cons.gridx = 1;
cons.gridy = 0;
container.add(panelDisplay, cons);

for (int i = 0; i < 15; i++) // display 15 components
{
displayNot();
}


this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //setting the default close operation of JFrame
this.pack();
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setVisible(true);

}

private void displayNot()
{
setLocGrid();
panelDisplay.add(new Not1(), cons);
}

private void setLocGrid()
{
if(curX==11) // maximum component to be display in 1 row is 11
{
curY += 1;
curX = 0;
}

cons.gridx = curX;
cons.gridy = curY;
cons.anchor = GridBagConstraints.FIRST_LINE_START;
cons.weightx = 1.0;
cons.weighty = 1.0;

curX += 1;
}

}

这是输出:enter image description here

忽略左侧面板。我的问题出在右侧面板中,即一个组件(组件:Not1)与另一个组件之间存在间隙。我已将每个组件的 PreferredSize 设置为 x=20 和 y=30,正如您在每个组件的背景中看到的,颜色为灰色。所以我的问题是,如何让差距消失?

更新:我的期望: enter image description here

最佳答案

首先删除 cons.weightxcons.weightx

private void setLocGrid() {
if (curX == 11) // maximum component to be display in 1 row is 11
{
curY += 1;
curX = 0;
}

cons.gridx = curX;
cons.gridy = curY;
cons.anchor = GridBagConstraints.FIRST_LINE_START;
//cons.weightx = 1.0;
//cons.weighty = 1.0;

curX += 1;
}

这会给你带来类似...

Example 01

现在,您需要某种填充物,可以将组件推到顶部/左侧位置,例如......

for (int i = 0; i < 15; i++) // display 15 components
{
displayNot();
}

cons.gridy++;
cons.gridx = 12; // Based on you conditions in setLocGrid
cons.weightx = 1;
cons.weighty = 1;
JPanel filler = new JPanel();
filler.setOpaque(false);
panelDisplay.add(filler, cons);

这会给你一些类似...

Example 2

关于java - 去除gridBagLayout中组件之间的间隙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23822127/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com