简体   繁体   English

如何防止通过鼠标单击更改选项卡

[英]how to prevent from changing tab by mouse click

my question could be silly but I'm trying to disable changing of tabs by mouse click in JTabbedPane . 我的问题可能很愚蠢,但我试图通过JTabbedPane 单击鼠标禁用更改选项卡 I searched on google but didn't found any helpful answer. 我在谷歌搜索,但没有找到任何有用的答案。 I tried to add empty MouseListener but still I can change the tab on mouse click. 我试图添加空的MouseListener但我仍然可以在鼠标单击时更改选项卡。

My Code is as follows: 我的守则如下:

public JTabbedPane createTabbedPane()
{
    JTabbedPane pane=new JTabbedPane();
    pane.addTab("tab1",panel1);
    pane.addTab("tab2",panel2);
    pane.addTab("tab3",panel3);
    pane.addMouseListener(new MouseAdapter());
    return pane;
}

I also tried this one: 我也试过这个:

public JTabbedPane createTabbedPane()
{
    JTabbedPane pane=new JTabbedPane();
    pane.addTab("tab1",panel1);
    pane.addTab("tab2",panel2);
    pane.addTab("tab3",panel3);
    pane.addMouseListener(new MouseListener()
    {
        @Override
            public void mouseClicked(MouseEvent e) {}

            @Override
            public void mousePressed(MouseEvent e) {}

            @Override
            public void mouseReleased(MouseEvent e) {}

            @Override
            public void mouseEntered(MouseEvent e) {}

            @Override
            public void mouseExited(MouseEvent e) {}
    });
    return pane;
}

If any one have any idea about how to do this please tell me. 如果有人知道如何做到这一点,请告诉我。 Thanks in advance. 提前致谢。

You can block changing tabs by mouse with help of ChangeListener like next: 您可以在ChangeListener帮助下通过鼠标阻止更改标签,如下所示:

final JTabbedPane pane = new JTabbedPane();
pane.addChangeListener(new ChangeListener() {

    @Override
    public void stateChanged(ChangeEvent e) {
        pane.setSelectedIndex(HOLD_INDEX);
    }
});

HOLD_INDEX is index of tab selected programatically. HOLD_INDEX是以编程方式选择的选项卡的索引。

Here when you try to select another tab it will be reselected to HOLD_INDEX . 当您尝试选择另一个选项卡时,它将重新选择为HOLD_INDEX

There are several things you could try... 你可以尝试几件事......

You Could 你可以

Set the tabs you don't want selected to disabled... 将您不希望选中的选项卡设置为禁用...

pane.setEnabled(indexOfTab, false);

You Could 你可以

Supply your own SingleSelectionModel from which you can control which tabs can be selected 提供您自己的SingleSelectionModel ,您可以从中控制可以选择哪些选项卡

Another possibility could be to override the addMouseListener(...) with an empty implementation to prevent any mouse interaction. 另一种可能是使用空实现覆盖addMouseListener(...)以防止任何鼠标交互。 Sample code could be as follows: 示例代码如下:

JTabbedPane tabbedPane = new JTabbedPane() {
    public synchronized void addMouseListener(MouseListener l) { };
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM