新J复选框不会出现在彼此之下

时间:2014-04-13 03:52:21

标签: java layout actionlistener jcheckbox

我正在尝试创建一个基本程序,无论何时按下按钮,都会生成JCheckbox并在面板上的另一个JCheckbox下方添加JCheckbox。我想出了如何使用ActionListener生成 box.setVisible(true); _p.add(box); int i = 0; int u = i++; box.setAlignmentX(0); box.setAlignmentY(u); ,但我无法弄清楚如何让每个新复选框显示在上一个复选框下方。其他一切似乎都在起作用,但我无法让这个位置工作。

{{1}}

以下是我的代码示例。我一直坚持这个问题很长一段时间,非常感谢任何和所有的帮助。

2 个答案:

答案 0 :(得分:2)

查看Using Layout Managers上的Swing教程。您可以使用垂直BoxLayoutGridBagLayoutGridLayout

无论您选择使用哪种布局,都可以使用基本代码向可见GUI添加组件:

panel.add(...);
panel.revalidate();
panel.repaint();

您的代码中的其他语句不是必需的:

//box.setVisible(true); // components are visible by default

以下方法不设置网格位置。

//box.setAlignmentX(0);
//box.setAlignmentY(u);

答案 1 :(得分:1)

JCheckbox位于像JPanel这样的容器中(这意味着您向面板添加了复选框)。 JPanel有一个layoutManager。看看Using Layout Managers

您可以将BoxLayout与Y_AXIS方向一起使用,或GridLayout使用1列和n行。

示例:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class CheckBoxTest {

    private JPanel panel;
    private int counter=0;

    public CheckBoxTest(){
        panel = new JPanel();
        panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
        JButton button = new JButton(" Add checkbox ");
        button.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent evt){
                panel.add(new JCheckBox("CheckBox"+Integer.toString(counter++)));
                //now tell the view to show the new components added
                panel.revalidate();
                panel.repaint();
                //optional sizes the window again to show all the checkbox
                SwingUtilities.windowForComponent(panel).pack();
            }
        });
        panel.add(button);
    }


    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("Checkbox example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        frame.setLocationByPlatform(Boolean.TRUE);
        CheckBoxTest test = new CheckBoxTest();
        frame.add(test.panel);

        //sizes components
        frame.pack();
        frame.setVisible(Boolean.TRUE);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }


}