사용자 정의 탭 컴포넌트가있는 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