2011-07-04 57 views
5

我有一個JPanel A在JPanel B的JTabbedPanel C中有一個標題邊框。我有一個方法刷新A和B的內容,不時調用。延遲TitledBorder標題更新/刷新,爲什麼?

不幸的是,A和B的所有項目都會及時更新,但不是A的標題。我明確地必須切換到另一個選項卡面板並返回到C以使A的標題正確顯示。爲什麼?

我使用的代碼如下:

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

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

回答

9

更新標題後,請確認您具有標題邊框或它的一個祖先對組件調用repaint()

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)); 
    } 
} 
+2

作爲參考,切換標籤調用'重繪()'通過'JTabbedPane' UI委託。 – trashgod

+0

好又好+1 – mKorbel

+1

有人認爲設置標題應該會自動調用重繪。然而,由於實施細節,這顯然很難做到;請參閱SUN錯誤報告,查看錯誤4117141:http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4117141 – Ryan