Reputation: 4421
I have a simple JTabbedPane
that shows text files. Each tab contains a JList
wrapped in a JScrollPane
I would like to be able to close the individual tabs with a right click, but I can't get this seemingly simple behavior to work.
Here is what I've tried so far:
Adding a listener to the Pane
public class RightClickListener extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
remove(getComponentAt(e.getPoint()));
}
}
}
Adding to the individual tabs
public class RightClickListener extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
remove((Component) e.getSource());
}
}
}
I've tried several other variations, and nothing seems to work. Does anyone know why these components aren't being removed? I'd be happy to provide any additional details as necessary.
UPDATE More detail:
public void loadCode(String cFile, String cLine) {
Scanner scan = null;
try {
scan = new Scanner(new File(cFile));
} catch (FileNotFoundException e) { e.printStackTrace();}
DefaultListModel<String> model = new DefaultListModel<String>();
JList<String> list = new JList<String>(model);
while(scan.hasNext()) {
model.addElement(scan.nextLine());
}
JScrollPane newTab = new JScrollPane(list);
tp.add(cFile, newTab);
tp.addMouseListener(new RightClickListener());
}
public class RightClickListener extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
remove(indexAtLocation(e.getX(), e.getY()));
}
}
}
Upvotes: 1
Views: 1502
Reputation: 6465
Right now in your listener, you're using getComponentAt
- which will return the component at the point which was clicked (if you're clicking on the tab titles, you're going to get the JTabbedPane back). Since the JTabbedPane was never added to itself, it can't remove that component...
Try using the indexAtLocation
method instead - this will check if the x/y coordinates of the click correspond to a tab heading and return that tab's index (see http://docs.oracle.com/javase/7/docs/api/javax/swing/JTabbedPane.html for more details)
public class RightClickListener extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
tp.remove(tp.indexAtLocation(e.getX(), e.getY()));
}
}
}
Upvotes: 2