簡體   English   中英

在 Java Swing 中從左上角啟動 GridBagLayout

[英]Starting GridBagLayout from top left corner in Java Swing

我是 Java Swing 的新手,我一直在努力從左上角啟動 GridBagLayout,以便 c.gridx=0 c.gridy=0 將我的對象放在左上角。

如果您能告訴我在此之后需要做什么來幫助我,我將不勝感激:

    JPanel panel = new JPanel(new GridBagLayout());
    frame.add(panel);
    GridBagConstraints c = new GridBagConstraints();

我知道我必須使用 NORTHWEST 或 FIRST_LINE_START 常量,但我不知道如何使用。 我試圖這樣做'但它沒有意識到常數。

    frame.getContentPane().add(panel, BorderLayout.NORTHWEST);

謝謝你的幫助。

閱讀 Swing 教程中關於如何使用 GridBagLayout 的部分 “weightx,weighty”部分指出:

除非您為 weightx 或 weighty 指定至少一個非零值,否則所有組件都會聚集在其容器的中心。

您需要使用GridBagConstraintsanchor屬性。 這應該為你做:

frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTHWEST;
frame.add(panel, gbc);

我不保證您不必設置約束對象的其他屬性來獲得您想要的布局。 特別是,您可能需要將weightxweighty設置為1以便面板占用為其提供的所有可用空間。

對於那些使用 IDE(例如 NetBeans)的人,我終於找到了一個不錯的技巧:如果您想將組件添加到頂部並使用它們的首選大小:添加另一個 weighty = 1.0 的空面板。 從自動生成的代碼 (NetBeans) 復制:

gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.weighty = 1.0;
jPanelOptions.add(jPanelFiller, gridBagConstraints);

一種快速而簡單的方法:

將空白 JLabel 添加到頁面末尾:

    // your code goes here
    gbc.weightx = 1;
    gbc.weighty = 1;

    bg.add(new JLabel(" "), gbc);  // blank JLabel

有一個解決方法。 您可以使用 BorderLayout.NORTH 將 GridBagLayout 面板放在 BorderLayout 面板中。 然后 GridBagLayout 面板中的組件將從頂部位置開始。

static void test4(){
    JFrame frame = new JFrame("Test");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(480, 360);

    JPanel borderLayoutPanel=new JPanel(new BorderLayout());
    JPanel gridBagLayoutPanel = new JPanel(new GridBagLayout());
    borderLayoutPanel.add(gridBagLayoutPanel, BorderLayout.NORTH);
    frame.add(borderLayoutPanel);

    JButton testButton=new JButton("test button");
    GridBagConstraints c = new GridBagConstraints();
    c.gridx=0;
    c.gridy=0;
    gridBagLayoutPanel.add(testButton, c);

    frame.setVisible(true);
}

在此處輸入圖片說明

如果您希望網格一直到頂部,只需將所有 weighty = 0 設置為最后一項,將其設置為大於 0 的任何數字,它將有效地將其余按鈕推到頂部。

不要忘記還增加按鈕的網格值。

否則會居中。 (如果您不使用 c.fill = GridBagConstraints.HORIZONTAL 屬性,則可以使用 gridx 和 weightx 值完成相同的操作。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM