对于我的程序,只要用户添加按钮,该按钮就会添加到“panel1”和“panel2”。到目前为止,我可以删除用户在第一个JPanel,panel1中所需的按钮。但是如何根据我在下面提供的代码删除第二个JPanel中的相同按钮?我应该检查第二个面板是否包含具有相同名称的按钮?我该怎么做?
public class deleteButton
{
public boolean deleteNow = false;
class ClickListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
deleteNow = true;
}
}
ActionListener deleteButtonClicked = new ClickListener();
deleteButton.addActionListener(deleteButtonClicked);
class ClickListenerTwo implements ActionListener
{
public void actionPerformed(ActionEvent f)
{
JButton buttonThatWasClicked = (JButton) e.getSource();
if (deleteNow == true)
{
panel1.remove(buttonThatWasClicked);
panel1.revalidate();
panel1.repaint();
//This is where I want it to delete from panel2.
deleteNow = false;
}
else
{
System.out.println("The button wasn't deleted");
}
}
}
}
答案 0 :(得分:1)
您可以遍历组件树以查找按钮。像这样的东西
/**
* Searches for all children of the given component which are instances of the given class.
*
* @param aRoot start object for search.
* @param aClass class to search.
* @param <E> class of component.
* @return list of all children of the given component which are instances of the given class. Never null.
*/
public static <E> List<E> getAllChildrenOfClass(Container aRoot, Class<E> aClass) {
final List<E> result = new ArrayList<E>();
final Component[] children = aRoot.getComponents();
for (final Component c : children) {
if (aClass.isInstance(c)) {
result.add(aClass.cast(c));
}
if (c instanceof Container) {
result.addAll(getAllChildrenOfClass((Container) c, aClass));
}
}
return result;
}
/**
* Finds the button by its text.
* @param aParent container for button search.
* @param aText text of button.
* @return button with the given text or null if no such button found.
*/
public static JButton findButtonByText(Container aParent, String aText) {
List<JButton> buttons = getAllChildrenOfClass(aParent, JButton.class);
for (JButton btn : buttons) {
if (btn.getText().equals(aText)) {
return btn;
}
}
return null;
}
用法:
JButton btn = findButtonByText(panel2, buttonThatWasClicked.getText());
if (btn != null && btn.getParent() != null) {
btn.getParent().remove(btn);
}
答案 1 :(得分:0)
从JPanel
删除组件的代码没有问题。也许代码的其他部分可能存在其他问题,但下面的代码可以正常工作,您可以检查逻辑并编辑代码:
public class DeleteButton extends JFrame {
private boolean flag;
public DeleteButton() {
setSize(new Dimension(400, 400));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
getContentPane().add(panel);
JButton button1 = new JButton("Set Flag");
panel.setLayout(new FlowLayout());
panel.add(button1);
JButton button2 = new JButton("Delete");
panel.add(button2);
button1.addActionListener(e -> flag = true);
button2.addActionListener(e -> {
JButton buttonThatWasClicked = (JButton) e.getSource();
if (flag) {
panel.remove(buttonThatWasClicked);
panel.revalidate();
panel.repaint();
flag = false;
} else {
System.out.println("The button wasn't deleted");
}
});
setVisible(true);
}
public static void main(String[] args) {
new DeleteButton();
}
}