How do I position JButtons vertically one after an

2019-07-20 09:11发布

问题:

I used a CardLayout to create 2 panels. The one on the left hosts JButtons, which when clicked, opens the corresponding website in the right panel. The problem is that I'm unable to place the buttons one on top of the other.

Please observe the screenshot below :-

回答1:

"The problem is that I'm unable to place the buttons one after the other."

You could use a Box set vertically

JButton jbt1 = new JButton("Button1");
JButton jbt2 = new JButton("Button2");
JButton jbt3 = new JButton("Button3");
JButton jbt4 = new JButton("Button4");

public BoxTest(){
    Box box = Box.createVerticalBox();    // vertical box
    box.add(jbt1);
    box.add(jbt2);
    box.add(jbt3);
    box.add(jbt4);

    add(box);  
}

Run this example to see

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class BoxTest extends JPanel{

    JButton jbt1 = new JButton("Button1");
    JButton jbt2 = new JButton("Button2");
    JButton jbt3 = new JButton("Button3");
    JButton jbt4 = new JButton("Button4");

    public BoxTest(){
        Box box = Box.createVerticalBox();
        box.add(jbt1);
        box.add(jbt2);
        box.add(jbt3);
        box.add(jbt4);

        add(box);  
    }

    public static void createAndShowGui(){
        JFrame frame = new JFrame();
        frame.add(new BoxTest());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationByPlatform(true);
        frame.pack();
        frame.setVisible(true);

    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run(){
                createAndShowGui();
            }
        });
    }
}

Edit:

"How about if I want to leave gaps between the buttons ?"

To add space int between use createVerticleStrut() in between the components

    Box box = Box.createVerticalBox();
    box.add(jbt1);
    box.add(Box.createVerticalStrut(10));  <-- 10 being the space
    box.add(jbt2);
    box.add(Box.createVerticalStrut(10));
    box.add(jbt3);
    box.add(Box.createVerticalStrut(10));
    box.add(jbt4);
    box.add(Box.createVerticalStrut(10));