Dynamically create jCheckBox and add to a jScrollPane

爱⌒轻易说出口 提交于 2019-12-05 08:06:47
mKorbel

EDIT

  • you have to set proper LayoutManager to the JPanel

  • you ahve to add JPanel to the JScrollPane

  • for example (without using built_in designer, even safe time for ..., required best knowledge about used SwingFramework and Swing too, I'm satisfied with plain Swing)

code

import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class AddJCheckBoxToJScrollPane {

    private static final long serialVersionUID = 1L;
    private JFrame frame = new JFrame();
    private JButton jButton1;
    private JPanel jPanel1;
    private JScrollPane jScrollPane1;

    public AddJCheckBoxToJScrollPane() {
        jPanel1 = new JPanel();
        jPanel1.setLayout(new GridLayout(0, 2, 10, 10));
        jScrollPane1 = new JScrollPane(jPanel1);
        jButton1 = new JButton("Add Checkbox");
        jButton1.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JCheckBox cb = new JCheckBox("New CheckBox");
                jPanel1.add(cb);
                jPanel1.revalidate();
                jPanel1.repaint();
            }
        });
        frame.add(jScrollPane1);
        frame.add(jButton1, BorderLayout.SOUTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        //frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String args[]) {

        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
        } catch (InstantiationException ex) {
        } catch (IllegalAccessException ex) {
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        }
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new AddJCheckBoxToJScrollPane();
            }
        });
    }
}
Charles

You should be calling repaint() instead of revalidate().

See Revalidate vs. Repaint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!