简体   繁体   中英

Layout for placing buttons in a panel in java swing

I'm trying to place my buttons in a manner similar to what has been shown here:

I've tried using the GridLayout , with some amount of spaces between columns and rows, but to no avail. How can I achieve this?

There are a number of ways you might achieve this depending on what you want to achieve, personally, I'd use a GridBagLayout , but that's because I like it;)

纽扣

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);
        }

    }
}

You could also do something using multiple panels, but that would depend on your desired needs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM