Я пытаюсь использовать GridBagLayout
, но я не понимаю, что я ожидал, и я не могу найти ошибку в этом коде:Java GridBagLayout не работает
public class GridBagEx1 extends JPanel {
private static final long serialVersionUID = 1L;
protected void makebutton(String name, GridBagLayout gridbag, GridBagConstraints c) {
JButton button = new JButton(name);
gridbag.setConstraints(button, c);
add(button);
}
public void init() {
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
setLayout(gridbag);
c.fill = BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
c.anchor = CENTER;
c.insets.top = 5;
c.insets.bottom = 5;
c.insets.left = 5;
c.insets.right = 5;
c.gridx = 0;
c.gridy = 0;
c.gridheight = 1;
c.gridwidth = 2;
makebutton("Button1", gridbag, c);
c.gridx = 2;
c.gridy = 0;
c.gridheight = 1;
c.gridwidth = 1;
makebutton("Button2", gridbag, c);
c.gridx = 3;
c.gridy = 0;
c.gridheight = 2;
c.gridwidth = 2;
makebutton("Button3", gridbag, c);
c.gridx = 0;
c.gridy = 1;
c.gridheight = 1;
c.gridwidth = 1;
makebutton("Button4", gridbag, c);
c.gridx = 1;
c.gridy = 1;
c.gridheight = 1;
c.gridwidth = 2;
makebutton("Button5", gridbag, c);
c.gridx = 0;
c.gridy = 2;
c.gridheight = 1;
c.gridwidth = 1;
makebutton("Button6", gridbag, c);
c.gridx = 1;
c.gridy = 2;
c.gridheight = 1;
c.gridwidth = 2;
makebutton("Button7", gridbag, c);
c.gridx = 3;
c.gridy = 2;
c.gridheight = 1;
c.gridwidth = 1;
makebutton("Button8", gridbag, c);
c.gridx = 4;
c.gridy = 2;
c.gridheight = 1;
c.gridwidth = 1;
makebutton("Button9", gridbag, c);
}
public static void main(String args[]) {
JFrame frame = new JFrame();
GridBagEx1 ex1 = new GridBagEx1();
ex1.init();
frame.add(ex1);
frame.pack();
frame.setVisible(true);
}
}
Эта фотография иллюстрировать то, что мне нужно:
Желтый: имя кнопки, красный являются строки и столбцы.
Это то, что происходит на самом деле:
Может кто-нибудь объяснить, что неправильно в моем коде?
Я не могу объяснить этот вопрос пока нет, но приходится констатировать, что ваш вопрос очень хорошо представлен , спасибо и 1+. –
@HovercraftFullOfEels Спасибо – Emax
'c.fill = BOTH;' должен быть 'c.fill = GridBagConstraints.BOTH;' и тот же для 'c.anchor = CENTER;' для компиляции кода. – user1803551