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:
Now I select the grid cell where I want to add the relevant candidates in the left-most pane.
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));
buttonPanel.add(undoButton);
buttonPanel.add(redoButton);
buttonPanel.add(eraseButton);
buttonPanel.add(hintButton);
JPanel cellPanel = new JPanel();
cellPanel.setName("cellPanel");
cellPanel.setLayout(new GridLayout(pSize, pSize, 0, 0));
JPanel numPanel = new JPanel();
numPanel.setName("numPanel");
numPanel.setLayout(new GridLayout(1,1,5,5));
numPanel.setPreferredSize((new Dimension(50,60)));
JPanel candPanel = new JPanel();
candPanel.setName("candidatesPanel");
JLabel candidates = new JLabel("Candidates");
candidates.setFont(new Font("Courier New", Font.ITALIC, 14));
candidates.setForeground(Color.GRAY);
candPanel.setLayout(new GridLayout(0,1));
candPanel.add(candidates);
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());
content.add(numPanel,pos.nextCol().expandW());
All buttons are generated at runtime and added to the CandPanel in an action listener.
source to share
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());
content.add(numPanel,pos.nextCol().expandW());
source to share