2

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?

predi
  • 5,528
  • 32
  • 60

1 Answers1

2

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.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Saw this in another answer, but failed to realize that using the button scrolls one tab worth of width at a time. This is exactly what I've been looking for. – predi Feb 01 '19 at 07:29
  • Always calling the backward action sometimes gave me strange results (Nimbus L&F), so I had to put it in a condition to ensure that it's called only if the last tab isn't visible : `if (tabs.getUI().getTabBounds(tabs, tabs.getTabCount() - 1).getMaxX() <= 0.0) { // call backward action }` – Florent Bayle Jan 04 '22 at 14:18