延迟TitledBorder标题更新/刷新,为什么?

时间:2011-07-04 01:37:44

标签: java swing refresh titled-border

我有一个JPanel A,其标题边框位于JPanel C的JTabbedPanel B内。我有一种方法可以刷新A和B的内容,该内容从时间调用 - 时间

不幸的是,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");
    }

1 个答案:

答案 0 :(得分: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));
     }
}