I have a panel that has a button above it to add a new category to a list and then I want to display that list below that button.
`
public class ConfigCategories extends JPanel {
public final List categories = new ArrayList<>();
public ConfigCategories() {
super();
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setOpaque(false);
setBorder(BorderFactory.createTitledBorder(L10N.t("elementgui.config.categories.title")));
setMaximumSize(new Dimension(getPreferredSize().width, 50));
JButton addCategory = new JButton("Add New Category");
addCategory.setOpaque(false);
addCategory.setMaximumSize(new Dimension(Integer.MAX_VALUE, addCategory.getPreferredSize().height));
addCategory.setBackground(Theme.current().getBackgroundColor());
addCategory.setForeground(Theme.current().getForegroundColor());
addCategory.setMargin(new Insets(0, 0, 2, 0));
ComponentUtils.deriveFont(addCategory, 11);
addCategory.addActionListener(e -> {
new NewCategoryDialog(this);
});
add(addCategory);
}
public void update() {
for (String name: categories) {
JButton b = new JButton(name);
b.setMaximumSize(new Dimension(Integer.MAX_VALUE, b.getPreferredSize().height));
b.setBackground(Theme.current().getBackgroundColor());
b.setForeground(Theme.current().getForegroundColor());
b.setBorder(BorderFactory.createEmptyBorder());
add(b);
}
updateUI();
}
}
`
`
public class NewCategoryDialog extends JDialog {
private final VTextField name = new VTextField(20);
public NewCategoryDialog(ConfigCategories configCategories) {
super(w, L10N.t("dialog.config.new_category"), true);
setSize(580, 195);
setLocationRelativeTo(w);
add(PanelUtils.westAndEastElement(L10N.label("Name:"), name));
JButton ok = new JButton(UIManager.getString("OptionPane.okButtonText"));
getRootPane().setDefaultButton(ok);
JButton cancel = new JButton(UIManager.getString("OptionPane.cancelButtonText"));
cancel.addActionListener(e -> setVisible(false));
ok.addActionListener(e -> {
setVisible(false);
configCategories.categories.add(name.getText());
configCategories.update();
});
add(BorderLayout.SOUTH, PanelUtils.join(ok, cancel));
setVisible(true);
}
}
`
This code works well, But I want to know how can I delete all the buttons added to the panel except the first button (button to add category)?
Because when I add the second, third, etc. button, the previous buttons are added again
Adding first button
Adding second button
BaRiBoD is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.