2012-10-16 42 views
1

我开发一个简单的“任务列表”的应用程序,包括获得“事做”的 某一天从数据库和面板搁在一个上显示它们的复选框文本frame.There是一个按钮“完成”,可用于去除 的勾选复选框后任务完成。在Java中,NetBeans的动态创建dcheckbox

我用于动态创建的复选框的代码如下所示:

//cnt-variable used to store the number of tasks for a day  
//rs1-ResultSet variable into which the task description is read into.  
//DATA-variable with 'to-do' description 

for(int i=0;i<cnt&&rs1.next();i++) 
{ 
    String s2=rs1.getString("DATA"); 
    JCheckBox cb = new JCheckBox("New CheckBox"); 
    cb.setText(s2); 
    cb.setVisible(true); 

    jPanel1.add(cb); 
    jPanel1.validate(); 
} 

在运行代码中的所有它显示是与面板的空帧。可能有人帮助我弄清楚为什么没有被显示的复选框? 在此先感谢。

+0

如何'创建jPanel1'和它在哪儿被添加到? – MadProgrammer

+0

@MadProgrammer \t JPANEL1是在运行时GUI creation..not期间下降,在帧 – user1748910

回答

3

试试这个。这允许您创建的复选框的随机数...

enter image description here

public class TestCheckboxes { 

    public static void main(String[] args) { 
     new TestCheckboxes(); 
    } 

    public TestCheckboxes() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException ex) { 
       } catch (InstantiationException ex) { 
       } catch (IllegalAccessException ex) { 
       } catch (UnsupportedLookAndFeelException ex) { 
       } 

       JFrame frame = new JFrame(); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setLayout(new BorderLayout()); 
       frame.add(new CheckBoxPane()); 
       frame.setSize(400, 400); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 

     }); 
    } 

    public class CheckBoxPane extends JPanel { 

     private JPanel content; 

     public CheckBoxPane() { 
      setLayout(new GridBagLayout()); 
      GridBagConstraints gbc = new GridBagConstraints(); 
      gbc.gridx = 0; 
      gbc.gridy = 0; 
      gbc.weightx = 1; 
      gbc.weighty = 1; 
      gbc.anchor = GridBagConstraints.CENTER; 
      content = new JPanel(new GridBagLayout()); 
      add(content, gbc); 

      JButton more = new JButton("More"); 
      more.addActionListener(new ActionListener() { 
       @Override 
       public void actionPerformed(ActionEvent e) { 
        GridBagConstraints gbc = new GridBagConstraints(); 
        gbc.gridx = 0; 
        gbc.gridy = 0; 

        content.removeAll(); 
        int count = 10 + (int) Math.round(Math.random() * 90); 
        System.out.println(count); 
        for (int index = 0; index < count; index++) { 
         gbc.gridx++; 
         if (index % 8 == 0) { 
          gbc.gridx = 0; 
          gbc.gridy++; 
         } 
         content.add(new JCheckBox(Integer.toString(index)), gbc); 
        } 

        content.revalidate(); 
        repaint(); 

       } 

      }); 

      gbc.gridy++; 
      gbc.weightx = 0; 
      gbc.weighty = 0; 

      add(more, gbc); 
     } 
    } 
}