predi
predi

Reputation: 5928

Scroll remaining tabs to visible after tab removal from a SCROLL_TAB_LAYOUT JTabbedPane

How does one scroll remaining tabs to visible after a single tab is removed from tail of a JTabbedPane with SCROLL_TAB_LAYOUT tab layout policy set.

Default behavior seems to be to not do anything - user is forced to use scroll buttons to bring remaining tabs back into view (the entire tab row becomes empty).

You can see what I mean if you repeatedly click the "Remove" button in my example. If you remove enough tabs, you eventually end up with a blank tab row.

import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;

public class FooTest extends JFrame {

    public FooTest() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        final JTabbedPane tabs = new JTabbedPane();
        tabs.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);        
        add(tabs, BorderLayout.CENTER);

        for (int i = 0; i < 10; i++) {
            tabs.addTab("Long tab name " + i, new JPanel());
            tabs.setSelectedIndex(i);
        }

        JButton button = new JButton("Remove");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (tabs.getTabCount() > 0) {
                    tabs.removeTabAt(tabs.getTabCount() - 1);
                }
            }
        });
        add(button, BorderLayout.PAGE_END);

        setSize(400, 400);
        setLocationRelativeTo(null);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new FooTest().setVisible(true);
            }
        });
    }

}

blank tab row

In other words, how do I ensure visibility of as much tabs as possible after removing from tail?

Upvotes: 2

Views: 298

Answers (1)

camickr
camickr

Reputation: 324088

how do I ensure visibility of as much tabs as possible after removing from tail?

Swing uses an Action to perform common functions of a component.

You could manually invoke the Action that scrolls the tabs after deleting a tab:

tabs.removeTabAt(tabs.getTabCount() - 1);
ActionMap am = tabs.getActionMap();
Action action = am.get("scrollTabsBackwardAction");
action.actionPerformed(new ActionEvent(tabs, ActionEvent.ACTION_PERFORMED, ""));

Check out Key Bindings for a list of the Actions support by each Swing component.

Upvotes: 2

Related Questions