英文:
Creating Buttons during runtime in Java
问题
我想根据一个数组在我的Java应用程序中添加一些按钮。例如,如果数组中有10个对象,我想创建10个按钮。如果我删除数组中的2个对象,按钮也应该被删除。我考虑了三种方法来解决这个问题。
- 使用for循环 - 但我认为按钮只会存在于循环内部,而且我不知道如何为按钮命名(变量名,而不是标签)。
- 使用线程。
- 使用一个单独的类。
不过,我不知道如何实现这些方法。我能够通过循环来为变量命名吗?我的任何想法都可行吗?
英文:
I want to add a number of Buttons to my Java application based on an array. Say if there are 10 objects in an array, I want to create 10 buttons. If I delete 2 objects in the array the buttons should also get deleted. I thought about 3 things to go on about this problem.
A for loop - but I think the buttons would just exist inside the loop and also I would not know how to name the buttons (the variable name not the label).
A Thread
A seperate class
I have no idea how I would do that though.
Can I actually name variables through loops?
Are any of my ideas practicable?
答案1
得分: 0
If you add a button to a JPanel
, it will survive outside the for loop, so don't worry about it. Create a JPanel
just for your buttons and keep track of those you add using an ArrayList<JButton>
, so you'll be able to delete them as you need. To delete them from the panel, refer to this answer. Remember to repaint (=refresh) the JPanel.
JButton button1 = ...;
// Add it to the JPanel
// https://stackoverflow.com/questions/37635561/how-to-add-components-into-a-jpanel
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();
英文:
If you add a button to a JPanel
it will survive outside the for loop, so don't worry about it. Create a JPanel
just for your buttons and keep track of those you add using an ArrayList<JButton>
, so you'll be able to delete them as you need. To delete them from the panel, refer to this answer. Remember to repaint (=refresh) the 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();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论