我正在使用Java Swing库制作KenKen术语项目。为了对齐,我使用了GridBag和GridLayout,但现在我想将另一个JPanel组件添加到UI中。这些屏幕截图将更清楚地说明问题:
现在我选择左侧面板中要添加相应候选项的网格单元格。 它会干扰网格和面板之间的相邻对齐。以下是具有各自布局的面板:
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);
然后所有内容都进入内容面板:
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());
按钮都是在运行时生成的,并且它们会在操作监听器中添加到candPanel。