使用流布局垂直添加控件而不是水平添加

ade*_*esh 47 java layout swing jpanel

我正在水平添加复选框JPanel中添加复选框FlowLayout.

我想在Panel上垂直添加复选框.什么是可能的解决方案?

Sun*_*tel 44

我希望你想要实现的是这样的.为此,请使用Box布局.

package com.kcing.kailas.sample.client;

import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;

public class Testing extends JFrame {

    private JPanel jContentPane = null;

    public Testing() {
        super();
        initialize();
    }

    private void initialize() {
        this.setSize(300, 200);
        this.setContentPane(getJContentPane());
        this.setTitle("JFrame");
    }

    private JPanel getJContentPane() {
        if (jContentPane == null) {
            jContentPane = new JPanel();
            jContentPane.setLayout(null);

            JPanel panel = new JPanel();

            panel.setBounds(61, 11, 81, 140);
            panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
            jContentPane.add(panel);

            JCheckBox c1 = new JCheckBox("Check1");
            panel.add(c1);
            c1 = new JCheckBox("Check2");
            panel.add(c1);
            c1 = new JCheckBox("Check3");
            panel.add(c1);
            c1 = new JCheckBox("Check4");
            panel.add(c1);
        }
        return jContentPane;
    }

    public static void main(String[] args) throws Exception {
        Testing frame = new Testing();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • ...而基本方法(使用BoxLayout)与@AbstractChaos早期的答案有所不同...... 除了更糟:contentpane中的null布局?手动上浆/定位面板?nononono,不要.什么是updateComponentTreeUI应该在这里实现? (5认同)
  • 这个答案是正确的,但太复杂,问题的焦点外 (2认同)

Nak*_*kar 42

我用了一个BoxLayout并设置了它的第二个参数BoxLayout.Y_AXIS,它对我有用:

panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
Run Code Online (Sandbox Code Playgroud)

  • 如何将单个元素向右对齐并使所有其他元素居中? (2认同)

Abs*_*aos 10

正如我在评论中所述,我将使用盒子布局.

JPanel panel = new JPanel();
panel.setLayout(new BoxLayout());

JButton button = new JButton("Button1");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(button);

button = new JButton("Button2");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(button);

button = new JButton("Button3");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(button);

add(panel);
Run Code Online (Sandbox Code Playgroud)

  • 这个没有编译 (4认同)

小智 5

JPanel testPanel = new JPanel();
testPanel.setLayout(new BoxLayout(testPanel, BoxLayout.Y_AXIS));
/*add variables here and add them to testPanel
        e,g`enter code here`
        testPanel.add(nameLabel);
        testPanel.add(textName);
*/
testPanel.setVisible(true);
Run Code Online (Sandbox Code Playgroud)