[英]Creating dcheckbox dynamically in Java-NetBeans
我正在開發一個簡單的“待辦事項列表”應用程序,該應用程序涉及從數據庫中獲取特定日期的“要做的事情”,並將其作為復選框文本顯示在框架上的面板上。有一個按鈕“完成”可以用於在任務完成后刪除勾選的復選框。
我用於動態創建復選框的代碼如下所示:
//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();
}
在運行代碼時,它顯示的是帶有面板的空框架。 有人可以幫我弄清楚為什么沒有顯示復選框? 提前致謝。
嘗試這個。 這允許您創建一個隨機數量的復選框...
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);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.