Java Swing Gridbag面板不支持colspan
据我所知,Swing Gridbag.gridwidth=2;应该完全像HTML中的colspan一样工作,即强制一个列在下一行上延伸,提供一个列,在下一行上分成两个,等等 然而,我的矿柱似乎将它下面的两根柱子压缩成一根,迫使它们彼此重叠Java Swing Gridbag面板不支持colspan,java,swing,html-table,layout-manager,gridbaglayout,Java,Swing,Html Table,Layout Manager,Gridbaglayout,据我所知,Swing Gridbag.gridwidth=2;应该完全像HTML中的colspan一样工作,即强制一个列在下一行上延伸,提供一个列,在下一行上分成两个,等等 然而,我的矿柱似乎将它下面的两根柱子压缩成一根,迫使它们彼此重叠 public class MainClass extends JFrame { public static void main(String args[]) { new MainClass(); } public MainClass() {
public class MainClass extends JFrame {
public static void main(String args[]) {
new MainClass();
}
public MainClass() {
JPanel panel = new JPanel(new GridBagLayout());
this.getContentPane().add(panel);
final JTextField nameInput = new JTextField();
final JLabel headerImage = new JLabel("test");
final JTextField volunteerID = new JTextField();
TitledBorder nameLabel;
nameLabel = BorderFactory.createTitledBorder("Name");
nameInput.setBorder(nameLabel);
TitledBorder fileNameLabel;
fileNameLabel = BorderFactory.createTitledBorder("Volunteer ID/ FileName");
volunteerID.setBorder(fileNameLabel);
JPanel constructorPanel = new JPanel();
constructorPanel.add(nameInput);
JPanel resultsPanel = new JPanel();
resultsPanel.add(volunteerID);
JPanel imagePanel = new JPanel();
imagePanel.add(headerImage);
GridBagConstraints gbc = new GridBagConstraints();
// Constructors
[[additional code]] //see below
gbc.gridx = 0;
gbc.gridy = 1;
panel.add(constructorPanel, gbc);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.NORTH;
panel.add(resultsPanel, gbc);
nameInput.setColumns(15);
volunteerID.setColumns(15);
this.pack();
this.setTitle("GiGgle Pics Settings Constructor");
this.setVisible(true);
this.setResizable(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
上述情况产生以下结果:
但是,当我在上面标记为[[additional code]]的空格中添加以下代码时
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
gbc.weightx = 1.0;
gbc.fill = WIDTH;
panel.add(imagePanel, gbc);
我明白了:
任何帮助都会很好找到它
我在GridBagLayout中添加组件的顺序是打赌
gbc.gridx = 0;
gbc.gridy = 1;
panel.add(constructorPanel, gbc);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.NORTH;
panel.add(resultsPanel, gbc);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
panel.add(imagePanel, gbc);
通过在底部添加colspan gbc,可确保其设置不会传输到其他设置
另一个解决方案是重置gbc.gridwidth=2;在每个上,为了更快地获得更好的帮助,请发布一个.删除尽可能多的代码,请阅读链接文章(而不是猜测其含义,或只是浏览一眼)。我的意思不是让它变短,而是其他部分..
gridwidth=2
只意味着组件可以使用两列,而不一定意味着它可以填充它们。您还需要设置weightx=1.0
和fill=HORIZONTAL
,以便组件实际使用可用空间。编辑,感谢您的评论,但它不起作用很高兴您对其进行了排序。:)