私はカスタムタブコンポーネントを持つJTabbedPaneを持っています。私はタブのどこかを右クリックしてJPopupMenuを表示できるようにしたい。私が抱えている問題は、JPopupMenuが右クリックで表示されない各タブにデッドスペースがあることです。私は、タブコンポーネントとして機能している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;
}
}
Genius!ありがとうございました。私は清潔な方法があると思ったが、これは素晴らしい。 – systemoutprintln
@mainstringargs「きれいな道があると思った」 - あなたは正しい。編集を参照してください。 – camickr