3
我有一個帶有自定義選項卡組件的JTabbedPane。我希望能夠右鍵單擊選項卡上的任意位置並顯示JPopupMenu。我遇到的問題是每個選項卡上存在無法右鍵單擊JPopupMenu的死空間。我相信這是因爲我將監聽器附加到充當Tab組件的JPanel上,但JPanel不是「填充」整個選項卡。右鍵單擊JTabbedPane上的JPopupMenu
有沒有辦法將鼠標監聽器連接到整個選項卡?
下面是一個例子來說明我所看到的。在選項卡的黃色區域中,我可以右鍵單擊並獲得一個彈出式菜單,但在選項卡的灰色區域中,不會截取右鍵單擊。
public class TabExample {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 1024, 768);
JTabbedPane pane = new JTabbedPane();
for (int i = 0; i < 15; i++) {
JPanel panel = new JPanel();
JLabel label = new JLabel("Panel " + i);
panel.add(label);
pane.addTab("", panel);
final JPanel tabComponentPanel = new JPanel(new BorderLayout());
final JLabel tabComponentLabel = new JLabel("My Tab " + i);
final JLabel tabComponentImageLabel = new JLabel();
ImageIcon icon = new ImageIcon(getImage());
tabComponentImageLabel.setHorizontalAlignment(JLabel.CENTER);
tabComponentImageLabel.setIcon(icon);
tabComponentPanel.add(tabComponentImageLabel,BorderLayout.CENTER);
tabComponentPanel.add(tabComponentLabel,BorderLayout.SOUTH);
tabComponentPanel.setBackground(Color.YELLOW);
tabComponentPanel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
pane.setSelectedComponent(panel);
} else if (e.getButton() == MouseEvent.BUTTON3) {
JPopupMenu jPopupMenu = new JPopupMenu();
JMenuItem menuItem = new JMenuItem("Menu Item");
jPopupMenu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Clicked ");
}
});
jPopupMenu.show(tabComponentPanel, e.getX(),
e.getY());
}
}
});
pane.setTabComponentAt(pane.indexOfComponent(panel),
tabComponentPanel);
}
frame.add(pane);
frame.setVisible(true);
}
});
}
private static BufferedImage getImage() {
BufferedImage bimage = new BufferedImage(16, 16,
BufferedImage.TYPE_BYTE_INDEXED);
Graphics2D g2d = bimage.createGraphics();
g2d.setColor(Color.red);
g2d.fill(new Ellipse2D.Float(0, 0, 16, 16));
g2d.dispose();
return bimage;
}
}
天才!謝謝。我覺得有一個更清晰的方式,但這很好。 – systemoutprintln
@ domainstringargs'我覺得有一個更清潔的方式 - 你說得對。請參閱編輯。 – camickr