Reputation: 854
This is my class:
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;
}
}
this is the output:
Just ignore the left panel. My problem is in the right panel which is, there is a gap between one component (component: Not1) to the other. i have set the preferedSize of each component to x=20 and y=30 as you can see in every component's background where the color is gray. So my question is, how to make the gap disappear?
UPDATE : my expectation:
Upvotes: 1
Views: 4694
Reputation: 347184
Start by getting rid of cons.weightx
and cons.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;
}
This will get you something like...
Now, you need some kind of filler that can push the components to the top/left position, for example...
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);
Which will give you something like...
Upvotes: 3