[英]How to align a gridbaglayout with components to the top left of the JPanel they are in
[英]How to place components in GridBaglayout from top left and then vertically?
我想像PIC 2中那樣放置我的按鈕,但最終卻像PIC 1中那樣放置它們。(PIC 2在繪畫中進行了編輯)。 有人知道我在做什么錯嗎? 然后如何從左上角開始放置,然后將下一個放置在該下面,依此類推?
PICS:
這是我的代碼:
public class TestTwo extends JFrame implements ActionListener {
JPanel p1 = new JPanel();
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
public static void main(String[] args){
new TestTwo();
}
public TestTwo(){
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
p1.setLayout(gbl);
add(p1, BorderLayout.WEST);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0;
gbc.weighty = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.NORTHWEST;
p1.add(b1, gbc);
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 1;
p1.add(b2, gbc);
setLocationRelativeTo(null);
setResizable(true);
setSize(200, 200);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
// do nothing
}
}
請參閱本頁面以獲取更多的指令,實例等,對如何使用GBL。 這對我有用,希望對您有所幫助!
public TestTwo() {
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(gbl);
p1.setLayout(gbl);
gbc = new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0,
GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(
0, 0, 0, 0), 0, 0);
add(p1, gbc); //add p1 in a GBL too, so it ends up in the northwest corner
p1.add(b1, gbc);
gbc.gridy = 1;
p1.add(b2, gbc);
setLocationRelativeTo(null);
setResizable(true);
setSize(200, 200);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.