我正在尝试在using中使用GridBagLayout
10 (3x3 + 1) 。JButtons
JPanel
BoxLayout
但是我对胶盒或类似的东西所做的GridBagLayout
JPanel
一切都会占用BoxLayout
. 我可能遗漏了一些东西,或者这不可能吗?
我使用的一种解决方案是在 gridbaglayout 内使用扩展元素向上推动按钮。这会将按钮放在正确的位置,但边框看起来很大。
下面是我的示例代码:
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GridBagLayoutTest extends JFrame {
public GridBagLayoutTest(){
super();
this.setTitle("JVectorView");
this.setSize(300,300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = this.getContentPane();
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
content.add(new JLabel("Hello!"));
content.add(new Controls());
content.add(Box.createGlue());
this.setVisible(true);
}
private class Controls extends JPanel{
private static final int WIDTH = 3, HEIGHT = 3;
public Controls(){
GridBagConstraints constraints = new GridBagConstraints();
//this.setBorder(BorderFactory.createLineBorder(Color.red));
this.setBorder(BorderFactory.createTitledBorder("Some stuff"));
constraints.fill = GridBagConstraints.NONE;
this.setLayout(new GridBagLayout());
for(int row = 0; row < HEIGHT; row++){
for(int col = 0; col < WIDTH; col++){
constraints.gridx = col;
constraints.gridy = row;
this.add(new JButton("B"+(col+row*WIDTH)), constraints);
}
}
constraints.gridx = 1;
constraints.gridy = 3;
this.add(new JButton("B"+(10)), constraints);
}
}
public static void main(String[] args) {
new GridBagLayoutTest();
}
}
我希望按钮周围的边框很紧。是否有可能让 gridbaglayout 折叠在它的内容上,还是总是强制填充面板?