我有 JTabbedPane,每个选项卡都有一个 JTextPane。
每个 JTextPane 都有一个弹出菜单,但我希望它们都共享完全相同的弹出菜单。为什么?因为当我切换标签时,我希望在每个弹出窗口上突出显示相同的选项。
我怎样才能做到这一点?我尝试向每个窗格添加一个静态 PopupMenu 实例,但是当我将它添加到一个窗格时,它会从其他窗格中消失。
编辑:在以下 SSCCE 中,当在 TabOne 上选中复选框时,在 TabTwo 上未选中。我希望在两个选项卡上都检查它。除该选项卡外,所有其他选项对于每个选项卡都可以是唯一的。
SSCCE:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.lang.reflect.InvocationTargetException;
import javax.swing.*;
public class Main {
public static void main(String[] Args) {
final Main M = new Main();
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
JFrame F = new JFrame("SSCCE");
JTabbedPane Pane = new JTabbedPane();
Pane.addTab("TabOne", M.new DebugBox(500, 500));
Pane.addTab("TabTwo", M.new DebugBox(500, 500));
F.setLayout(new BorderLayout());
F.add(Pane, BorderLayout.NORTH);
F.pack();
F.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
F.setVisible(true);
}
});
} catch (InvocationTargetException | InterruptedException e) {
e.printStackTrace();
}
}
public class DebugBox extends JTextPane {
private JScrollPane ScrollPane = null;
private final JPopupMenu Menu = new JPopupMenu();
private static final long serialVersionUID = 7731036968185936516L;
public DebugBox(int Width, int Height) {
this.ScrollPane = new JScrollPane(this, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
this.setPreferredSize(new Dimension(Width, Height));
JCheckBoxMenuItem Debug = new JCheckBoxMenuItem(new AbstractAction() {
private static final long serialVersionUID = -336209978671944858L;
@Override
public void actionPerformed(ActionEvent e) {
//DO something here that affects ALL the DebugBoxes because they all share this Menu Option somehow :S
//Change name of this menu option, all instances have their names changed too.
}
});
JMenuItem Copy = new JMenuItem(new AbstractAction() {
private static final long serialVersionUID = -6774461986513304498L;
@Override
public void actionPerformed(ActionEvent e) {
DebugBox.this.copy();
}
});
JMenuItem Clear = new JMenuItem(new AbstractAction() {
private static final long serialVersionUID = -5567371173360543484L;
@Override
public void actionPerformed(ActionEvent e) {
DebugBox.this.setText(null);
}
});
JMenuItem SelectAll = new JMenuItem(new AbstractAction() {
private static final long serialVersionUID = -8792250195980016624L;
@Override
public void actionPerformed(ActionEvent e) {
DebugBox.this.selectAll();
}
});
this.Menu.add(Copy);
this.Menu.add(Clear);
this.Menu.add(SelectAll);
this.Menu.add(Debug);
Copy.setText("Copy");
Clear.setText("Clear");
SelectAll.setText("Select All");
Debug.setText("Show Debug Box");
this.setEditable(false);
this.add(this.Menu);
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
DebugBox.this.Menu.show(DebugBox.this, e.getX(), e.getY());
}
}
});
}
}
}