[英]Add checkbox dynamically in java
I wonder how to add checkboxes
and name dynamically . 我想知道如何动态添加
checkboxes
和名称。
The number of checkboxes
is follow the number of row in MySQL
and the name is retrieved from MySQL
. checkboxes
的数量跟随MySQL
的行数,并从MySQL
检索名称。 Assume I have three data in MySQL
, so I would get output as image above. 假设我在
MySQL
有三个数据,所以我将输出为上面的图像。
This is my code for class A 这是我的A类代码
checkAPI api= new checkAPI();
try
{
num = api.displayCheckBoxAndLabel(); // get 3
List<String> allName= api.displayName(); // [John,Tony,Kik]
}
catch (Exception e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
deleteAdmin delete = new deleteAdmin(num,allName);
delete.setVisible(true);
setVisible(false);
dispose();
}
Then pass the two parameters to class deleteAdmin 然后将两个参数传递给类deleteAdmin
public class deleteAdmin extends JFrame {
private JPanel contentPane;
private JTextField userText;
private JTextField txtpassword;
JFrame f= new JFrame(" Add Admin");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
button frame = new button();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public deleteAdmin(int num, List<String> names)
{
super("Delete Admin");
setBounds(100, 200, 340, 229);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(35, 19, 242, 146);
contentPane.add(panel);
panel.setLayout(null);
JCheckBox[] checkBoxList = new JCheckBox[num];
for(int i = 0; i < num; i++) {
checkBoxList[i] = new JCheckBox("CheckBox" + i);
contentPane.add(checkBoxList[i]);
}
}
}
However, I get this kind of output. 但是,我得到了这种输出。 No checkboxes shown :(
没有显示的复选框:(
From a quick look there are at least two possible oddities in your code. 从快速看一下,代码中至少有两个可能的奇怪之处。
Swing components must be created and manipulated exclusively on the event dispatch thread. 必须在事件派发线程上专门创建和操作Swing组件。 So if your code
所以如果你的代码
deleteAdmin delete= new deleteAdmin(num,allName); delete.setVisible(true); setVisible(false); dispose();
Runs in the EDT because it is inside some button handler or like that it is ok, otherwise you need to use invokeLater()
to do that stuff. 在EDT中运行,因为它在某个按钮处理程序内部或类似于它可以,否则你需要使用
invokeLater()
来执行这些操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.