简体   繁体   中英

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 . 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.

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:

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.

Here when you try to select another tab it will be reselected to 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

Another possibility could be to override the addMouseListener(...) with an empty implementation to prevent any mouse interaction. Sample code could be as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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