Vertically aligning jpanels components using GridLayout

I am making KenKen as my term project using Java Swing library. I used gridbag and gridlayout for alignment, but now I want to add another JPanel component to the UI. These screenshots will clarify the problem:

Before I click on the button in the lowest panel below

Now I select the grid cell where I want to add the relevant candidates in the left-most pane.

This is what happens when I click the number buttons 2, 3, 4

This interferes with adjacent grid and panel alignments.

Here are the panels with their respective layouts:

 JPanel buttonPanel = new JPanel();
 buttonPanel.setLayout(new GridLayout(1, 4, 5, 5));
 buttonPanel.setPreferredSize(new Dimension(20,40));

 JPanel cellPanel = new JPanel();
 cellPanel.setLayout(new GridLayout(pSize, pSize, 0, 0));

 JPanel numPanel = new JPanel();
 numPanel.setLayout(new GridLayout(1,1,5,5));
 numPanel.setPreferredSize((new Dimension(50,60)));

 JPanel candPanel = new JPanel();
 JLabel candidates = new JLabel("Candidates");
 candidates.setFont(new Font("Courier New", Font.ITALIC, 14));
 candPanel.setLayout(new GridLayout(0,1));


Then it all goes into the content pane:

 content.add(buttonPanel, pos.nextCol().expandW());
 content.add(candPanel, pos.nextRow());
 content.add(new Gap(GAP) , pos.nextRow());  // Add a gap below
 content.add(cellPanel, pos.nextCol());


All buttons are generated at runtime and added to the CandPanel in an action listener.


source to share

1 answer

You seem to be using a subclass of GridBagConstraints, which I am not aware of (variable pos

), although I can guess its function from the context.

Assuming your problem is that you want the pane to be to the candidates

left of cellPanel

and not above it, you need to swap the places that add candPanel

and new Gap(GAP)

as shown below

content.add(buttonPanel, pos.nextCol().expandW());
content.add(new Gap(GAP), pos.nextRow());   // These two lines
content.add(candPanel, pos.nextRow());      // swapped over
content.add(cellPanel, pos.nextCol());




All Articles