【问题标题】:Creating Buttons during runtime in Java在 Java 运行时创建按钮
【发布时间】:2020-11-16 23:43:42
【问题描述】:
我想基于数组向我的 Java 应用程序添加一些按钮。假设一个数组中有 10 个对象,我想创建 10 个按钮。如果我删除数组中的 2 个对象,按钮也应该被删除。我想了 3 件事来解决这个问题。
一个 for 循环 - 但我认为按钮只会存在于循环内,而且我也不知道如何命名按钮(变量名而不是标签)。
一个线程
一个单独的类
我不知道我会怎么做。
我真的可以通过循环命名变量吗?
我的任何想法是否可行?
【问题讨论】:
标签:
java
button
dynamic
runtime
creation
【解决方案1】:
如果您将按钮添加到 JPanel,它将在 for 循环之外继续存在,所以不用担心。仅为您的按钮创建一个JPanel,并使用ArrayList<JButton> 跟踪您添加的那些,这样您就可以根据需要删除它们。要从面板中删除它们,请参阅this 答案。记得重新绘制(=刷新)JPanel。
JButton button1 = ...;
// Add it to the JPanel
// https://stackoverflow.com/questions/37635561/how-to-add-components-into-a-jpanel
ArrayList<JButton> buttons = new ArrayList<>();
buttons.add(button1);
// Other stuff...
// It's time to get rid of the button
JButton theButtonIWantToRemove = buttons.get(0);
buttons.remove(0);
//Get the components in the panel
Component[] componentList = panel.getComponents();
//Loop through the components
for(Component c : componentList){
//Find the components you want to remove
if(c == theButtonIWantToRemove){
//Remove it
panel.remove(c);
}
}
//IMPORTANT
panel.revalidate();
panel.repaint();