我想在每次单击按钮时创建一个新的 JPanel,并在面板上创建对象(按钮和/或标签)。该部分似乎在技术上有效,但是在尝试一次删除面板(从最后添加到第一个)时遇到问题。
尽管我留在了一个未使用的数组中,但我已尝试尽可能地精简代码,因为我认为这就是我想使这项工作发挥作用的方式。任何建议将不胜感激。如果有什么太含糊,也让我知道,试图用语言表达我的问题比我想象的要难。
免责声明:抱歉,至少有一些最佳实践被忽略了。
public class CreatePanelsTest{
JPanel totalGUI;
GridLayout grid = new GridLayout(0,1);
int panelX = 10;
public JPanel createContentPane (){
//create a bottom JPanel to place everything on.
totalGUI = new JPanel();
//set the Layout Manager to null, manually place objects
totalGUI.setLayout(null);
JPanel controlPanel = new JPanel();
controlPanel.setLocation(50, 220);
controlPanel.setSize(200, 40);
JButton addSet = new JButton("add set");
addSet.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
newSetActionPerformed(evt);
}
});
JButton removeSet = new JButton("remove set");
removeSet.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeSetActionPerformed(evt);
}
});
controlPanel.add(addSet);
controlPanel.add(removeSet);
totalGUI.add(controlPanel);
totalGUI.revalidate();
return totalGUI;
}
private void newSetActionPerformed(java.awt.event.ActionEvent evt) {
//on button click adds group
JPanel newPanel = new JPanel(grid);
newPanel.setLocation(panelX, 10);
newPanel.setSize(50,200);
JButton button1 = new JButton("1");
JButton button2 = new JButton("2");
newPanel.add(button1);
newPanel.add(button2);
totalGUI.add(newPanel);
totalGUI.validate();
totalGUI.repaint();
panelX = panelX+50;
}
private void removeSetActionPerformed(java.awt.event.ActionEvent evt) {
//this is suppose to remove one panel at a time
//totalGUI.remove(newPanel);
//totalGUI.validate();
//totalGUI.repaint();
//panelX = panelX-50;
}
public JPanel[] autoArray(){
//was hoping to make this method work for me, unused atm
int n = 6;
//can i change the value of "n" later or will it break stuff?
JPanel[] panels = new JPanel[n];
for (int i = 0; i<n; i++){
panels[i] = new JPanel(grid);
}
return panels;
}