How do I position JButtons vertically one after an

2019-07-20 09:12发布

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 :-

Screen Shot

1条回答
放荡不羁爱自由
2楼-- · 2019-07-20 09:53

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

enter image description here

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

enter image description here

查看更多
登录 后发表回答