Title length in JTabbedPane tabs

Has anyone ever written code to make JTabbedPane tab titles shorten automatically when there isn't room for all of them in one row?
Our users like neither of the many-tabs solutions that Swing provides (scroll and multiple rows of tabs), and would prefer a style similar to Eclipse where the tab titles shorten if there isn't room for the entire text.
All I really want to know is - did anyone do it? And if so a few hints as to how you achieved it.
Thanks,
Tim

Well here is the code I developed in case it is useful to anyone else. Didn't have to do anything clever like work out the length of the text in the end - as you will see in the code:     import java.awt.BorderLayout;
     import java.awt.event.ActionEvent;
     import java.awt.event.ActionListener;
     import java.awt.event.ContainerEvent;
     import java.awt.event.ContainerListener;
     import java.util.Random;
     import javax.swing.JButton;
     import javax.swing.JFrame;
     import javax.swing.JPanel;
     import javax.swing.JTabbedPane;
     import nz.co.timryan.components.CentredButtonPanel;
     import nz.co.timryan.components.FixedWidthButton;
      * Automatically shorten the tab selector titles if necessary to fit them
      * into the width of the space available without scrolling.
      * <br><br>Created on 10/07/2005 by Tim Ryan
     public class BTTTabbedPane extends JTabbedPane implements ContainerListener {
          static BTTTabbedPane instance;
          BTTTabbedPane() {
               setTabPlacement(JTabbedPane.BOTTOM);
               setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
               addContainerListener(this);
               instance = this;
           * @param args
          public static void main(String[] args) {
               JFrame frame = new JFrame("TabbedPane test");
               frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               JPanel main = new JPanel(new BorderLayout());
               main.add(new BTTTabbedPane(), BorderLayout.CENTER);
               JPanel buttonPanel = new CentredButtonPanel();
               JButton addButton = new FixedWidthButton("Add");
               addButton.addActionListener(new ActionListener() {
                    Random random = new Random();
                    public void actionPerformed(ActionEvent e) {
                         String text = "MARY AND JANE SMITH AND MICHAEL".substring(0, random.nextInt(30) + 1);
                         instance.addTab(text, null, new JPanel(), text);
               JButton removeButton = new FixedWidthButton("Remove");
               removeButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                         instance.remove(instance.getTabCount() - 1);
               buttonPanel.add(addButton);
               buttonPanel.add(removeButton);
               main.add(buttonPanel, BorderLayout.SOUTH);
               frame.add(main);
               frame.setBounds(100, 100, 800, 500);
               frame.setVisible(true);
          public void componentAdded(ContainerEvent e) {
               recalculateTitleWidths();
          public void componentRemoved(ContainerEvent e) {
               recalculateTitleWidths();
           * Shorten the titles of the tabs as necessary to fit the selectors across
           * the width of the available space without scrolling (if possible).
           * Whenever a title is shortened, "..." is appended to the text to show that
           * this has occurred.
           * The full length titles are held in the tooltip text so that the text can
           * be restored if other tabs are deleted, and also so that the user can see
           * the full text by mousing over the title.
          private void recalculateTitleWidths() {
               int tabCount = getTabCount();
               int[] tabWidth = new int[tabCount];
               int availableWidth = getBounds().width - 4;
               //  Reset the titles to their full text
               for (int j = 0; j < tabCount; j++) {
                    setTitleAt(j, getToolTipTextAt(j));
                    tabWidth[j] = getBoundsAt(j).width;
               int totalWidth = getTotalWidth(tabWidth, tabCount);
               boolean wasShortened = true;
               // Loop around, shortening titles until all the selectors fit across
               // the screen, or the titles are too short to be shortened further.
               while ((totalWidth > availableWidth) && wasShortened) {
                    int longestTab = -1;
                    int longestTabWidth = 0;
                    int longestText = 0;
                    wasShortened = false;
                    // Find the longest tab
                    for (int j = 0; j < tabCount; j++) {
                         if (tabWidth[j] >= longestTabWidth) {
                              longestTab = j;
                              longestTabWidth = tabWidth[j];
                              longestText = getTitleAt(j).length();
                    // Shorten its text (adding "..." if not already done)
                    // and then determine the new tab width and total tab width
                    String title = getTitleAt(longestTab);
                    if (title.length() > 4) {
                         if (title.endsWith("...")) {
                              title = title.substring(0, title.length() - 4);
                         } else {
                              title = title.substring(0, title.length() - 2);
                         setTitleAt(longestTab, title + "...");
                         tabWidth[longestTab] = getBoundsAt(longestTab).width;
                         wasShortened = true;
                         totalWidth = getTotalWidth(tabWidth, tabCount);
           * Calculate the total width of the tab selectors.
           * @param  tabWidth the individual widths of the tab selectors
           *         (held in an array for performance reasons)
           * @param  tabCount the count of tabs
           * @return the total width of all tab selectors
          private int getTotalWidth(int[] tabWidth, int tabCount) {
               int totalWidth = 0;
               for (int j = 0; j < tabCount; j++) {
                    totalWidth += tabWidth[j];
               return totalWidth;
}Regards,
Tim

Similar Messages

  • Protected tab titles are not supported (tab TABSTRIP title COMPANY)

    hi gurus
    i got error in infotype like this wat is the problem
    Protected tab titles are not supported (tab TABSTRIP title COMPANY)

    Error message is like this
    Protected tab titles are not supported (tab TABSTRIP title COMPANY)
    Message no. 00119
    Diagnosis
    You cannot print the title on a tab index as the tab index does not support this.
    Procedure
    Check the screen modifications or the Screen Painter definitions of the tab title.
    When you modify the screen, do not set the INPUT attribute of the tab title to '0'.

  • Protected tab titles are not supported(tab tabstr_ 025 title tab1)

    Hi,
       In training and event mgt module-while maintaining relationship with business event to person subtype A025 after saving the system asking anotherdata that time i got one error iam unable to maintain plz help.
    Error:protected tab titles are not supported(tab tabstr_ 025 title tab1)

    Hello Prasad,
    'Protected' means,  that the flag 'input' for the pushbutton of the tabstrip is set to 0. For a normal pushbutton this is allowed but not for a pushbutton which is the title of a tabstrip.
    Hoping this clarify.
    Kind regards,
    Graziela

  • JTabbedPane: Tab Text, Tab Width and Tab Height

    Whenever i put text on JTabbedPane tab it displays it in one line, so when i have a text e.g. "XXXXXXXXX XXXXXXXXX"
    it displays it as it is not like XXXXXXXXX
    XXXXXXXXX
    How can I display it in two line or more?
    Does Tab width and height automatically adjust itself relative to the text inside it? If not how can I set the tab width and height?
    Thanks in advance.

    leemax quote:
    Simply add the escaped new line character "\n" to display the text of the tab on the next line.
    --Yeah i tried that already but anyway i solved the problem by making used of htnl tags "<br>"                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Shorten the length of the tabs?

    I'm not sure if I pushed something to change this, I need help changing it back.
    Now
    How it used to be
    I know they're different browsers but they're just there to compare.
    I want to shorten the length of the tab so that it's not taking up the whole bar. It just annoying me for some strange reason.

    I'm not sure if I pushed something to change this, I need help changing it back.
    Now
    How it used to be
    I know they're different browsers but they're just there to compare.
    I want to shorten the length of the tab so that it's not taking up the whole bar. It just annoying me for some strange reason.

  • Adusting Title Length

    I'm stumped...I can adjust the title length as long as I have a clip in the project window but then I am as yet unable to move the beginning of the clip to the end of the adjusted title. If I try to adjust the title length before I put the clip into the project window IMovie will not change the title length.
    What am I missing?

    I've got it fixed. I don't know exactly why buy during my efforts to lengthen the title clip there were some 2s incremental changes that were made to the original 29s title clip. These changes evidently blocked me from making the change I was going for. By putting the title length back to the original 20s I was then able to adjust the proper length.
    Thanks

  • Preset title length

    Is there anyway to preset the title length in iMovie 08?
    Every time I add a title it is between 3 and 5 minutes long. Can't I set the length before I add it?
    Thanks

    I think you mean 3 to 5 seconds, however:-
    It's impractical to set a default title duration for a number of reasons, one being that different titles take different times to read. I'm not sure whether im08 tries to adjust the title duration for a particular situation but adjusting the duration of a title manually once it is added is just something you need to do.

  • Why isn't the selected tab title bold in JTabbedPane? How can I make it be?

    The selected tab title of JTabbedPanel is not bold. Is there a simple way to set it to be bold when a tab is selected? Thanks in advance.

    1. Simply use the HTML code in it's text like '<html><b>NameOfThisTab</b></html>'.
    2. Extend the JTabbedPane and fine-tune the font it uses.

  • Fix tab title size in JTabbedPane

    Now, each tab in my JTabbedPane occupies the whole row because the title is too long. Is there any way to set each tab title size to be preferred fixed size in JTabbedPane? (I can use the tooltip to show the whole string. )
    Thanks.

    Swing related questions should be posted in the Swing forum.
    You will probably need to write your own UI. The TabbedPaneUI has a getTabBounds method you could probably override.
    Otherwise just set the tab text manually to be a certain number of characters. You can store the full text in a variable that is referenced by your tool tip logic.

  • How can I change the font of the titles in a JTabbedPane

    Hi
    I use a JTabbedPane in a project and use windows LookAndFeel.
    I want to distinguish the selected Tab titels by changing the font of the title. Is there anybody who can help me. I can not find any component used as the title. They are only there when I create the tabs with.
    myTabbedPan.addTab("aTitle",aPanel);
    How TabbedPan use the string "aTitle" to create Tab "Buttons". Is there a component or... I can not get it
    Thanks
    nan2000

    Unfortunately, you have to sub-class the WindowsTabbedPaneUI to do that, and override the convenient methods.
    After that, you have to specify to the UIManager this new class it have to use to display the JTabbedPane components.
    Denis

  • Dialog title to depend on tab name dynamically....

    Hi,
    I have an application which has a tab(Phones) and tab has a Jtable with some data.
    When i press Lookup button the first tab-Jtable loads .
    When i right click on a cell in the table, the corresponding row first coloumn value is shown through a dialog.
    Now in the dialog the title is "Shakin", i want the dialog title to be dynamic depending on the tab(name) it is clicked i.e it depends on the tab names (like in this case Phones).
    If someone click a cell in table of first tab(Phones) then the dialog title should also be Phones.
    In future if i add more tabs then each tab would have dialog and each dialog title would depend on each corresponding tab name.
    Can somebody suggest be what to do?
    Below is the code....
         package alignment;
    * @author K
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.Arrays;
    import java.util.Vector;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTable;
    import javax.swing.event.TableModelEvent;
    import javax.swing.table.DefaultTableModel;
    public class TestJava extends JFrame {
         DefaultTableModel mtm;
         JTabbedPane tabbedPane = new JTabbedPane();
         JPanel phones = new JPanel();
         JScrollPane scroller = new JScrollPane();
         JPanel p = new JPanel(new BorderLayout());
         JPanel topPanel = new JPanel();
         JButton lookup = new JButton("Lookup");
         JTable table = new JTable();
         Dbi di;
         String[] columnNames = { "full name", "HP-URL", "address" };
         Vector cnv;
         Vector dbResult;
         public TestJava() {
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              mtm = new DefaultTableModel(columnNames, 2);
              cnv = new Vector<String>(Arrays.asList(columnNames));
              table = new JTable(mtm);
              final JOptionPane pane = new JOptionPane("", JOptionPane.PLAIN_MESSAGE,
                        JOptionPane.INFORMATION_MESSAGE);
              final JDialog d = pane.createDialog(null, "Shakin'!");
              d.setModal(false);
              d.pack();
              table.addMouseListener(new MouseAdapter() {
                   public void mouseClicked(MouseEvent me) {
                        if (me.getButton() == me.BUTTON3) {
                             int row = table.rowAtPoint(me.getPoint());
                             Object value1 = table.getValueAt(row, 0);
                             // JOptionPane.showInputDialog(value1,"Value is " + row);
                             pane.setMessage(value1);
                             if (!d.isVisible())
                                  d.setVisible(true);
              scroller = new JScrollPane(table);
              topPanel.add(lookup);
              phones.add(scroller);
              tabbedPane.addTab("Phones", phones);
              p.add(topPanel, BorderLayout.NORTH);
              p.add(tabbedPane, BorderLayout.CENTER);
              setContentPane(p);
              pack();
              di = new Dbi();
              lookup.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        fetch();
                        table.tableChanged(new TableModelEvent(table.getModel()));
                        if (pane != null) {
                             pane.setMessage("");
                        table.repaint();
         public void fetch() { // time-consuming task should be run
              Thread t = new Thread() { // in a separate thread
                   public void run() {
                        dbResult = di.getQueryResult("QUERY!!!!!");
                        mtm.setDataVector(dbResult, cnv);
              t.start(); // actionPerformed() immediately returns, not blocking GUI
         public static void main(String[] args) {
              TestJava frame = new TestJava();
              frame.setVisible(true);
    class Dbi { // make it a separate public class
         public Vector<Vector> getQueryResult(String query) {
              Vector<String> v1 = new Vector<String>();
              Vector<String> v2 = new Vector<String>();
              Vector<String> v3 = new Vector<String>();
              Vector<String> v4 = new Vector<String>();
              v1.addAll(Arrays.asList(new String[] { "Tim Marshall",
                        "http://tim.marshall/", "Never never land" }));
              v2.addAll(Arrays.asList(new String[] { "Com Commercial",
                        "http://com.comcom/", "Land of gold" }));
              v3.addAll(Arrays.asList(new String[] { "Love Lovable",
                        "http://love.neverhate/", "Sun lotus state" }));
              v4.addAll(Arrays.asList(new String[] { "War Monger",
                        "http://war.momongers/", "Fire and ice city" }));
              Vector<Vector> v0 = new Vector<Vector>();
              v0.add(v1);
              v0.add(v2);
              v0.add(v3);
              v0.add(v4);
              return v0;
    }Thanks

    Use a ChangeListener, it fires every time a new tab is selected.

  • How to change the selected tabPane title color in JTabbedPane

    how to change the selected tabPane title color(or set bold) in JTabbedPane.
    Any advice will be appreciate.

    Hi,
    try
    // Set text color for the selected tab
    tab.setForegroundAt(tab.getSelectedIndex(), Color.red);Hope that helps

  • Row length in Cross tab

    Hi
    How to increase length of row in cross tab.
    i took descrption as row in crosstab, how to increase it's length.

    The length of the row can only be increased by clicking on the row field and expand it from the corner pointers. There is no automatic adjustment button for the row to adjust itself.
    Regards
    Jehanzeb

  • Modify title of drill down tabs

    Hi All,
       Just a quick questions regarding the titles embedded in the drill down tabs. Is it possible to modify the titles? As an example, if I drill down to a level that is grouped by month, I would like the drill down tab to display "Month".
    Thank you in advance.

    There is a solution. You have to use a customized group name field
    Go to Reports->Group Expert.
    Select the Options button for the group.
    Click on the Options tab
    Select the checkbox Customize Group Name Field
    Select the radio button Use A Formula As Group Name
    Click on the fomula button
    Enter whatever you want the tab name to be, as a string. You can customize the tab to say, for instance, Order No. - 5630  by entering "Order No - " + CStr() in the formula editor
    Daniel

  • Button in JTabbedPane tab

    Greetings,
    i'd like to have a button on every tab in JTabbedPane, like close button in NetBeans when you edit the code. By default, you can put an icon only. Do you guys know how to do that?
    thanks in advence.

    If you can wait another couple of months (or if you are willing to use the beta version), you can use the new JTabbedPane features in Java 6 (Mustang). Have a look at the method setTabComponentAt:
    [url http://download.java.net/jdk6/docs/api/javax/swing/JTabbedPane.html#setTabComponentAt(int,%20java.awt.Component)]setTabComponentAt

Maybe you are looking for

  • Some keys as ENTER, SPACE and BACKSPACE type characters

    Some keys as ENTER, SPACE and BACKSPACE are not working properly in my HP Pavilion dm4 1055br. When pressing one of these keys type two or three characters ( ): ENTER (lçj), SPACE (.;M), BACKSPACE (~h). This latter at the same time turn off the F11 k

  • Download of documents

    I am trying to create a download of pdf or other documents from the web site I am creating.  I would appreciate very much receiving some help how this is done.

  • Install Acrobat Pro XI

    Bought Pro XI and downloaded from invoice.  Opened it and it is labels Acrobab Pro XI but when I try to open it it says the number isn't one of the programs listed, when I click the drop down list Acrobat Pro XI isn't even a choice....even though the

  • Sd card reader on t500-not working,what to do?

    sda standard complaint sd host controller thats what it says in my device manager i have t500 with vista 32 how do i access the card? when i go to the device manager it says - no drivers are installed for this device. what to do?!! thanks!

  • Capturar a Premier Elements 4.0 desde dispositivo AverMedia

    Premier Elements no reconoce el dispositivo de captura AverMedia DVD EZMaker USB Gold modelo P/N300AC038-CLD. ¿Existe algún modo de hacer que funcione y así importar vídeo analógico compuesto directamente? Gracias