@madprogrammer probably has the simplest answer, but if you don't want to change the look of the application, you could combine your button's actionListener
with a mouseListener
for the panels.
The mouseListener
portion saves the last panel clicked, and the actionListener
just removes the panel that was registered by the mouseListener
.
Here's a quick sample I cooked up - it doesn't use JXTitledPane
but that shouldn't matter because they're all in the same hierarchy.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TempProject extends JFrame{
public TempProject(){
Box mainContent = Box.createVerticalBox();
//Create Button
JButton removePanel = new JButton("RemovePanel");
RemoveListener listener = new RemoveListener(mainContent);
removePanel.addActionListener(listener);
mainContent.add(removePanel);
//Create Panels
mainContent.add(getPanel(Color.red, listener));
mainContent.add(getPanel(Color.orange, listener));
mainContent.add(getPanel(Color.pink, listener));
mainContent.add(getPanel(Color.magenta, listener));
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setContentPane(mainContent);
pack();
setVisible(true);
}
public JPanel getPanel(Color color, RemoveListener l){
JPanel result = new JPanel();
result.setBackground(color);
result.add(new JLabel(color.toString()));
result.addMouseListener(l);
return result;
}
public static void main(String args[])
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
new TempProject();
}
});
}
public static class RemoveListener extends MouseAdapter implements ActionListener{
Component lastSelectedComponent = null;
Container master; //The panel containing the ones being listened to
public RemoveListener(Container master){
this.master = master;
}
@Override
public void mouseClicked(MouseEvent arg0) {
lastSelectedComponent = (Component)arg0.getSource();
}
@Override
public void actionPerformed(ActionEvent e) {
if(lastSelectedComponent != null){
master.remove(lastSelectedComponent);
master.repaint();
}
}
}
}