动态创建jCheckBox并添加到jScrollPane [英] Dynamically create jCheckBox and add to a jScrollPane

查看:806
本文介绍了动态创建jCheckBox并添加到jScrollPane的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:使用下面介绍的解决方案,我已经将代码更改为在JScrollPane中有一个JPanel。使用JButton我将JCheckBoxes添加到JScrollPane内的JPanel中。这是一个解决的问题,因为JScrollPanecan只需要一个JComponent。其余的问题已经解决了将Gridlayout设置为JScrollPane内的JPanel。我已经把这个原来的问题留在了后代:



ORIGINAL QUESTION:我试图动态创建JCheckBox并将它们添加到JScrollPane中,但是我可以几乎没有成功。我已将其简化为一个概念验证实现。



我在JFrame内有一个JScrollPaneon一个JPanel。另外在JPanel上,我添加了一个按钮,它应该在JScrollPane中添加一个JCheckBox。应该够简单按钮中的代码如下:

  private void addCheckBoxActionPerformed(java.awt.event.ActionEvent evt){

JCheckBox cb = new JCheckBox(New CheckBox);

jScrollPaneCheckBoxes.add(cb);
jScrollPaneCheckBoxes.revalidate();
}

代码运行似乎没有错误。我没有例外,使用调试器显示JCheckBox实际上已经添加到JScrollPane。不幸的是,应用程序中没有显示任何内容我需要向哪里寻找问题的方向。



这是一个快速的代码,你可以运行。不幸的是,我使用Netbeans和它的GUI设计器一起投入使用,因此它比它需要的时间要长一些,特别是生成的代码。专注于方法jButton1ActionPerformed,这就是上面的代码取自的地方。



编辑:这段代码现在完成了我所需要的。 : - )

  package dynamiccheckboxsscce; 

import javax.swing.JCheckBox;

public class Main extends javax.swing.JFrame {

/ **
*创建新窗体Main
* /
public Main (){
initComponents();


@SuppressWarnings(unchecked)
private void initComponents(){

jScrollPane1 = new javax.swing.JScrollPane();
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jScrollPane1.setHorizo​​ntalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_​​NEVER);
jScrollPane1.setPreferredSize(new java.awt.Dimension(250,250));

jPanel1.setPreferredSize(new java.awt.Dimension(300,250));
jPanel1.setLayout(new java.awt.GridLayout(0,2,10,10));
jScrollPane1.setViewportView(jPanel1);

jButton1.setText(添加复选框);
jButton1.addActionListener(new java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent evt){
jButton1ActionPerformed(evt);
}
});

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane()。setLayout(layout);
layout.setHorizo​​ntalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1,javax.swing.GroupLayout.DEFAULT_SIZE,309,Short。 MAX_VALUE)
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,layout.createSequentialGroup()
.addGap(0,0,Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(112,112,112)))));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1,javax.swing.GroupLayout.DEFAULT_SIZE,javax.swing.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement。相关,11,Short.MAX_VALUE)
.addComponent(jButton1)
.addContainerGap()));

pack();
}

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
JCheckBox cb = new JCheckBox(New CheckBox);

jPanel1.add(cb);
jPanel1.revalidate();
jPanel1.repaint();
}

/ **
* @param args命令行参数
* /
public static void main(String args []){
/ *
*设置Nimbus外观和感觉
* /
尝试{
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){
java.util.logging.Logger.getLogger(Main.class.getName())。log(java.util。 logging.Level.SEVERE,null,ex);
} catch(InstantiationException ex){
java.util.logging.Logger.getLogger(Main.class.getName())。log(java.util.logging.Level.SEVERE,null,ex) ;
} catch(IllegalAccessException ex){
java.util.logging.Logger.getLogger(Main.class.getName())。log(java.util.logging.Level.SEVERE,null,ex) ;
} catch(javax.swing.UnsupportedLookAndFeelException ex){
java.util.logging.Logger.getLogger(Main.class.getName())。log(java.util.logging.Level.SEVERE, null,ex);
}

/ *
*创建并显示窗体
* /
java.awt.EventQueue.invokeLater(new Runnable(){
public void run(){
new Main()。setVisible(true);
}
});
}
private javax.swing.JButton jButton1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
}

提前感谢。

解决方案


  • 不发布 SSCCE 你必须接受 JScrollPane 被指定只嵌套一个 JComponent


  • 添加一个 JComponent JScrollPane ,放在那里 JPanel ,然后添加一个新的 JComponent code> JPanel 而不是 JScrollPane


  • a href =https://stackoverflow.com/a/6989230/714968>如何动态添加/删除JComponents




编辑




  • 您必须将适当的LayoutManager设置为JPanel


  • 你要添加JPanel到JScrollPane


  • (没有使用built_in设计器,甚至安全的时间...,需要关于使用SwingFramework和Swing的最佳知识,我是满足普通的秋千)




代码

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


EDIT: Using the solutions presented below, I have changed the code to have a JPanel inside a JScrollPane. Using a JButton i add JCheckBoxes to the JPanel inside the JScrollPane. This was one problem solved, as the a JScrollPanecan only take one JComponent. The rest of the issues were solved setting a gridlayout to the JPanel inside JScrollPane. I have kept my original question here for the sake of posterity:

ORIGINAL QUESTION: I'm trying to dynamically create JCheckBox and add them to a JScrollPane, but alas i am achieving little success. I have reduced this to a single proof-of-concept implementation.

I have a JScrollPaneon a JPanel inside a JFrame. Also on the JPanel, i have added a button that is supposed to add a JCheckBox to the JScrollPane when clicked. Should be simple enough. The code inside the button is as follows:

 private void addCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {

    JCheckBox cb = new JCheckBox("New CheckBox");        

    jScrollPaneCheckBoxes.add(cb);
    jScrollPaneCheckBoxes.revalidate();
 }

The code runs seemingly without error. I have no exceptions and using the debugger shows that the JCheckBox is in fact added to the JScrollPane . Unfortunately, nothing is displayed in the application. I need direction as to where to look for the problem.

Here is a quick piece of code that you can just run. Unfortunately i threw this together using Netbeans and it's GUI designer and as such it's a bit longer than it needs to be, especially the generated code. Focus on the method jButton1ActionPerformed, that's where the above code is taken from.

EDIT: This code now does what i need it to. :-)

package dynamiccheckboxsscce;

import javax.swing.JCheckBox;

public class Main extends javax.swing.JFrame {

    /**
     * Creates new form Main
     */
    public Main() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        jScrollPane1.setPreferredSize(new java.awt.Dimension(250, 250));

        jPanel1.setPreferredSize(new java.awt.Dimension(300, 250));
        jPanel1.setLayout(new java.awt.GridLayout(0, 2, 10, 10));
        jScrollPane1.setViewportView(jPanel1);

        jButton1.setText("Add Checkbox");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 309, Short.MAX_VALUE)
                .addContainerGap())
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(112, 112, 112)))));
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addContainerGap()));

        pack();
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        JCheckBox cb = new JCheckBox("New CheckBox");

        jPanel1.add(cb);
        jPanel1.revalidate();
        jPanel1.repaint();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        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) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
            }
        });
    }
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
}

Thanks in advance.

解决方案

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

这篇关于动态创建jCheckBox并添加到jScrollPane的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆