我无法将任何相关帖子转移到我的简单问题上。 为了进入GridBagLayout,我写了一个简单的例子:
JFrame frame = new JFrame();
JPanel main =new JPanel();
frame.setContentPane(main);
GridBagLayout gbl=new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
main.setLayout(gbl);
JButton btn1 = new JButton("1");
JButton btn2 = new JButton("2");
gbc.gridx=0;
gbc.gridy=0;
gbc.gridheight=1;
gbc.gridwidth=1;
gbc.fill=GridBagConstraints.WEST;
gbl.setConstraints(btn1, gbc);
gbc.gridx=0;
gbc.gridy=1;
gbl.setConstraints(btn2, gbc);
frame.setSize(new Dimension(200,100));
main.add(btn1);
main.add(btn2);
frame.setVisible(true);
这里我的问题是.fill和GBConstrains的任何其他参数都没有工作。我曾经在窗口中间拿到两个按钮。
事先提前答案 0 :(得分:2)
您的GridBagConstraint
配置不正确:
fill
只能采取:NONE
,VERTICAL
,HORIZONTAL
或BOTH
。anchor
可以使用“单元格”中的相对位置fill
和anchor
几乎总是需要使用weightx/weighty
gridx
和gridy
,因为它们很难维护。而是使用其默认值(RELATIVE
),您可以更改gridwidth
/ gridheight
的值,将其设置为1
(如果需要,可以设置更多)和{{1}使布局换行到下一行/列(然后按照将它们添加到容器中的顺序定位组件。这是你的工作代码(虽然我不确定你所针对的确切布局):
REMAINDER
答案 1 :(得分:1)
编辑:我制作了一个示例应用程序,演示了如何使用重用约束的GridBadLayout:
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Test1 {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test1 window = new Test1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Test1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0, 0};
gridBagLayout.rowHeights = new int[]{0, 0};
gridBagLayout.columnWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, Double.MIN_VALUE};
frame.getContentPane().setLayout(gridBagLayout);
JButton btnTest = new JButton("Test1");
GridBagConstraints gbc_btnTest = new GridBagConstraints();
gbc_btnTest.insets = new Insets(0, 0, 0, 5);
gbc_btnTest.gridx = 0;
gbc_btnTest.gridy = 0;
frame.getContentPane().add(btnTest, gbc_btnTest);
JButton btnTest_1 = new JButton("Test2");
gbc_btnTest.gridx = 1;
gbc_btnTest.gridy = 0;
frame.getContentPane().add(btnTest_1, gbc_btnTest);
}
}