簡體   English   中英

GridBagLayout問題

[英]GridBagLayout issue

我正在嘗試使用GridBagLayout。 我需要一個垂直和水平居中放置的JLabel-這很容易,我什至不必創建任何GridBagConstraints。 我也想在右下角放置一個JButton,當我嘗試這樣做時,居中的面板向左移動或按鈕向上移動。

EXPECTING     GETTING THIS  OR THIS
+-----------+ +-----------+ +-----------+
|           | |           | |           |
|           | |           | |           |
|           | |           | |           |
|   +---+   | | +---+     | | +---+     |
|   |   |   | | |   |     | | |   |     |
|   +---+   | | +---+     | | +---++---+|
|           | |           | |      |   ||
|           | |           | |      +---+|
|       +---+ |       +---+ |           |
|       |   | |       |   | |           |
+-------+---+ +-------+---+ +-----------+

bigPanel = new JPanel();
bigPanel.setPreferredSize(new Dimension(320, 640));
bigPanel.setLayout(new GridBagLayout());

label = new JLabel();
label.setPreferredSize(new Dimension(100,95));

button = new JButton();
button.setPreferredSize(new Dimension(100,25));

GridBagConstraints c = new GridBagConstraints();

c.anchor = GridBagConstraints.CENTER;
bigPanel.add(label, c);

c.anchor = GridBagConstraints.LAST_LINE_END;
bigPanel.add(button, c);

我也在嘗試使用其他約束,但在每次出現問題時,都可以在此處描述其他約束,例如http://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html

如果組件未填充單元格,則anchor將組件位置設置在其單元格內。

您尚未定義布局的網格。 默認行為是從左到右添加組件。

這是一個使用GridBagLayout實現您想要的示例。 標簽和按鈕放置在填充面板的同一單元格中。

public class Test extends JPanel {
    public Test() {
        super();
        GridBagLayout gridBagLayout = new GridBagLayout();
        gridBagLayout.columnWeights = new double[] { 1.0 }; // expands the  1rst cell of the layout on the vertical axis
        gridBagLayout.rowWeights = new double[] { 1.0 }; // expands the 1rst cell of the layout on the horizontal axis
        setLayout(gridBagLayout);

        JLabel label = new JLabel("test");          
        label.setOpaque(true);
        label.setBackground(Color.RED);
        label.setPreferredSize(new Dimension(100, 95));
        GridBagConstraints gbc_label = new GridBagConstraints();
        gbc_label.gridx = 0; // set label cell (0,0)
        gbc_label.gridy = 0;
        gbc_label.insets = new Insets(0, 0, 5, 5);

        add(label, gbc_label);

        JButton button = new JButton("button");
        GridBagConstraints gbc_button = new GridBagConstraints();
        gbc_button.gridx = 0; // set buttoncell (0,0)
        gbc_button.gridy = 0;
        gbc_button.anchor = GridBagConstraints.SOUTHEAST;

        add(button, gbc_button);
        button.setPreferredSize(new Dimension(100, 25));
    }
}

暫無
暫無

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

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