Search code examples
javaswingrefreshtitled-border

Delayed TitledBorder title update/refresh, why?


I have a JPanel A with a title border inside a JPanel B of a JTabbedPanel C. I have a method refreshing the content of A and B which is called from time-to-time.

Unfortunately, all the items of A and B are refreshed in time, but not the title of A. I explicitely have to switch to another tabbed panel and come back to C for A's title to be displayed properly. Why?

The code I am using is the following:

    TitledBorder tmp
            = (TitledBorder) this.GroupingProfilePanel.getBorder();

    // Resetting header
    if ( this.c != null ) {
        tmp.setTitle("Set - " + this.c.getName());
    } else {
        tmp.setTitle("Set");
    }

Solution

  • After updating the title, verify that you invoke repaint() on the component having the titled border or one of its ancestors.

    enter image description here

    import java.awt.BorderLayout;
    import java.awt.EventQueue;
    import java.awt.event.ActionEvent;
    import java.util.Date;
    import javax.swing.AbstractAction;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.border.TitledBorder;
    
    /** @see http://stackoverflow.com/questions/6566612 */
    public class TitledBorderTest {
    
         public static void main(String[] args) {
              EventQueue.invokeLater(new Runnable() {
                  public void run() {
                      new TitledBorderTest().create();
                  }
              });
         }
    
         private void create() {
    
             String s = "This is a TitledBorder update test.";
             final JLabel label = new JLabel(s);
             final TitledBorder tb =
                 BorderFactory.createTitledBorder(new Date().toString());
             label.setBorder(tb);
             JFrame f = new JFrame("Titled Border Test");
             f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             f.add(label);
             f.add(new JButton(new AbstractAction("Update") {
    
                public void actionPerformed(ActionEvent e) {
                    tb.setTitle(new Date().toString());
                    label.repaint();
                }
            }), BorderLayout.SOUTH);
             f.pack();
             f.setLocationRelativeTo(null);
             f.setVisible(true);
             System.out.println(tb.getMinimumSize(f));
         }
    }