2

我有 JTabbedPane,里面有 5 个标签。位置 2,3 和 5 的选项卡被禁用。我想在单击此禁用选项卡时显示一个 JDialog。我尝试添加鼠标侦听器并更改侦听器,但对我没有任何帮助。使用鼠标单击方法,我可以单击该选项卡,但无法确定单击了哪个选项卡。如何在 JTabbedPane 中禁用的选项卡上获取单击事件?

这是我尝试过的:

import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.lang.reflect.InvocationTargetException;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Test {
    public static void main(String[] args) throws InterruptedException, InvocationTargetException {
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame("Test tab pane click");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                JTabbedPane tabbedPane = new JTabbedPane();
                JPanel panel1 = new JPanel();
                panel1.add(new JLabel("HI1"));
                tabbedPane.addTab("Tab 1", panel1);
                JPanel panel2 = new JPanel();
                panel2.add(new JLabel("HI2"));
                tabbedPane.addTab("Tab 2", panel2);
                JPanel panel3 = new JPanel();
                panel3.add(new JLabel("HI3"));
                tabbedPane.addTab("Tab 3", panel3);
                JPanel panel4 = new JPanel();
                panel4.add(new JLabel("HI4"));
                tabbedPane.addTab("Tab 4", panel4);
                JPanel panel5 = new JPanel();
                panel3.add(new JLabel("HI5"));
                tabbedPane.addTab("Tab 5", panel5);
                frame.setLayout(new BorderLayout());
                frame.add(tabbedPane, BorderLayout.CENTER);
                frame.setSize(500, 200);
                frame.setVisible(true);

                // disable 2nd, 3rd and 5th tab.
                tabbedPane.setEnabledAt(1, false);
                tabbedPane.setEnabledAt(2, false);
                tabbedPane.setEnabledAt(4, false);

                tabbedPane.addChangeListener(new ChangeListener() {
                    @Override
                    public void stateChanged(ChangeEvent e) {
                        System.out.println("I'm not called for disabled tabs.");
                    }
                });
                tabbedPane.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        System.out.println("I'm called for disabled tabs, but not able to know which tab is clicked.");
                    }
                });
            }
        });
    }
}
4

1 回答 1

4

With mouse click method I can get that tab is clicked but not able to identify particular which tab is clicked.

您可以使用JTabbedPane'indexAtLocation(int, int)方法(MouseEventhasgetX()getY()),它告诉您包含给定位置的选项卡的索引。

于 2012-07-30T12:37:05.127 回答