How to shift focus on the clicked tab

613 views Asked by At

I have a JTabbedPane and when i add new tab button it creates new tab and focus on the new tab. But i want to shift the focus from the new tab to the another tab when i click on that tab.

How can i shift focus on the clicked tab? Thanks in advance.

Here is the portion of the code that handles new tabs:

public Test(){
    newPage = new JButton();
    newPage.setPreferredSize(new Dimension(30, 30));
    newPage.setBorderPainted(false);
    newPage.setBackground(Color.decode("#330300"));
    newPage.setToolTipText("New Page");
    newPage.setEnabled(true);
    JPanel jp = new JPanel();
    jp.setLayout(new BorderLayout());
    tb = new JTabbedPane();
    tb.setUI(new CustomTabbedPaneUI());
    tb.setForeground(Color.decode("#330300"));
    tb.addTab("New Tab", fPane);
    jp.add(new JLayer<JTabbedPane>(tb));
    newPage.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            try {
                tb.addTab("New Tab", new JPanel());
                //initial value of inI=0;
                tb.setSelectedIndex(inI+1);
                inI++;
            } catch (IOException ex) {
                Logger.getLogger(Pooh.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });
    tb.setOpaque(true);


}
1

There are 1 answers

0
camickr On BEST ANSWER
tb.setSelectedIndex(inI+1);
inI++;

There is no need for a variable to track the number of tabs in the tabbed pane.

You can get that information from the tabbed pane itself. I think the method is getTabCount() or something like that. Read the JTabbedPane for the method.

Then you can select the tab by subtracting one from the value returned from the method.