单击JButton时删除父JPanel

时间:2017-03-18 15:54:13

标签: java jpanel jbutton

我有一个JPanel的ArrayList。此列表中的每个项目都有一个JButton。 现在,当单击JButton时,我想从ArrayList中删除它的'父JPanel。那么如何让JButton从ArrayList中删除它的父元素呢?

提前致谢。

public class TestingArrayList extends JFrame {

JPanel grandPanel;  // a JPanel for all the panels
ArrayList<JPanel> panelParent = new ArrayList<>();  // JPanel ArrayList

public TestingArrayList() {
    super("Test");
    setLayout(new FlowLayout());

    grandPanel = new JPanel();
    add(grandPanel);

    for (int i = 0; i < 10; i++) {  // adding 10 JPanel into grandPanel
        panelParent.add(new JPanel());
        grandPanel.add(panelParent.get(i));

        // adding JButton in all panels
        JButton btnParent = new JButton("X");
        panelParent.get(i).add(btnParent);

        // add new task button action
        btnParent.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                System.out.println(getParent());
                //What to do!!!
            }
        });
    }

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(1000, 100);
    setLocationRelativeTo(null);
    setVisible(true);
}

public static void main(String[] args) {
    new TestingArrayList();
}

}

2 个答案:

答案 0 :(得分:1)

您在代码中拥有所需的一切。您只需要对感兴趣的JPanel进行final引用,因为这将允许您在匿名内部ActionListener类中使用它:

for (int i = 0; i < 10; i++) { 

    // make it final so that it is accessible from inner anon class
    final JPanel myPanel = new JPanel();
    panelParent.add(myPanel);
    grandPanel.add(myPanel);

    JButton btnParent = new JButton("X");
    myPanel.add(btnParent);

    btnParent.addActionListener(event -> panelParent.remove(myPanel));
}

如果您还想从grandPanel中删除它,那么您还需要更多...

btnParent.addActionListener(event -> {
    panelParent.remove(myPanel);
    grandPanel.remove(myPanel);
    grandPanel.revalidate();
    grandPanel.repaint();
});

请注意,如果您想使用Seymore删除JPanel的方法,首先需要了解通过在ActionEvent参数上调用getSource()获得的源对象是侦听器所在的对象。添加到 - 这里是JButton而不是JPanel,并且返回的对象类型是Object,因此在不进行强制转换的情况下不能调用其上的Swing组件方法。因此,您需要将所有内容括在括号中,以便允许您调用该类型的方法。例如:

parentPanel.remove((JPanel) ((JButton) event.getSource()).getParent());

parentPanel.remove((JPanel) ((JComponent) event.getSource()).getParent());

当代码变得复杂时,我发现分离行更容易:

// since a JButton extends from JComponent
JComponent source = (JComponent) event.getSource();
JPanel parent = (JPanel) source.getParent();
parentPanel.remove(parent);

答案 1 :(得分:0)

btnParent.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent event) {
        System.out.println(getParent());
        panelParent.remove((JPanel)(event.getSource().getParent()));
    }
});