我有一个简单JTabbedPane
的显示文本文件。每个选项卡都包含一个JList
包裹,JScrollPane
我希望能够通过右键单击关闭各个选项卡,但我无法让这个看似简单的行为起作用。
这是我迄今为止尝试过的:
将侦听器添加到窗格
public class RightClickListener extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
remove(getComponentAt(e.getPoint()));
}
}
}
添加到各个选项卡
public class RightClickListener extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
remove((Component) e.getSource());
}
}
}
我尝试了其他几种变体,但似乎没有任何效果。有谁知道为什么这些组件没有被删除?我很乐意在必要时提供任何其他详细信息。
更新更多细节:
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()));
}
}
}