我的GridBagLayout出現了一些問題。我創建了一個JPanel(在這種情況下稱爲mainPanel),其佈局設置爲GridBagLayout。我已經爲每個JButton指定了約束,並將約束添加到每個按鈕。現在,當我運行我的代碼時,按鈕總是彼此相鄰,而不管我在約束中指出的gridx/gridy值如何。此外,按鈕總是在JFrame的中心,當我想要一個按鈕出現在右上角,左上角和南側時。當我將它添加到JFrame中時,GridBagLayout不工作
import javax.swing.*;
import java.awt.*;
public class test {
public static void main (String[] args) {
myJFrame test = new myJFrame();
}
}
class myJFrame extends JFrame {
public myJFrame() {
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel myPanel = new mainPanel();
add(myPanel);
setVisible(true);
}
}
class mainPanel extends JPanel {
public mainPanel(){
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.NORTHWEST;
c.gridx = 1000;
c.gridy= 1;
add(new JButton("1"),c);
c.anchor = GridBagConstraints.NORTHEAST;
c.gridx = 100;
c.gridy= 1;
add(new JButton("2"),c);
c.anchor = GridBagConstraints.SOUTH;
c.gridx = 200;
c.gridy= 1;
add(new JButton("3"),c);
}
}
This is what i get when i run the code
謝謝!事實上,你是對的,這是一個權重問題 - 一旦我修改了這個,我就能夠得到我期待的行爲。至於x位置,只是表明不管x座標中位置的大小如何,這些項目都是彼此相鄰的。謝謝! – newbieJavaDev
@newbieJavaDev,很高興它有幫助。不要忘了單擊複選標記以「接受」答案,以便人們知道問題已解決。 – camickr