簡體   English   中英

在 java swing 中的面板中放置按鈕的布局

[英]Layout for placing buttons in a panel in java swing

我正在嘗試以類似於此處顯示的方式放置按鈕:

我試過使用GridLayout ,列和行之間有一些空格,但無濟於事。 我怎樣才能做到這一點?

根據您想要實現的目標,您可以通過多種方式實現這一目標,我個人會使用GridBagLayout ,但那是因為我喜歡它;)

紐扣

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = 2;
            //gbc.fill = GridBagConstraints.HORIZONTAL;

            gbc.gridx = 1;
            add(new JButton("Up"), gbc);
            gbc.gridx = 0;
            add(new JButton("Left"), gbc);
            gbc.gridx = 2;
            add(new JButton("Right"), gbc);
            gbc.gridx = 1;
            add(new JButton("Down"), gbc);
        }

    }
}

您也可以使用多個面板來做某事,但這取決於您的需求

暫無
暫無

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

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