change TitledBorder color dynamically in java

sajad picture sajad · Apr 8, 2013 · Viewed 15.3k times · Source

I have created a TitledBorder and set it to a JPanel.

JPanel panel = new JPanel();
panel.setBorder(javax.swing.BorderFactory.
      createTitledBorder(null, "title", javax.swing.border.
      TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.
      TitledBorder.DEFAULT_POSITION, null, java.awt.Color.red));

now I want to change the color of the title text of the border; and if possible border lines. I see when I change color of the border by the method titledborder.setTitleColor(theColor); and revalidate() and repaint(); the panel on form is not affected. I also created new instance of thiledBorder and assign it to the panel; but not effective. Is it necessary to renew the panel, and then set it new a border instance? thank you

Answer

Reimeus picture Reimeus · Apr 8, 2013

You don't state how titledborder is assigned but this is how it would work:

TitledBorder titledBorder = BorderFactory.createTitledBorder(...);
panel.setBorder(titledBorder);

then at runtime:

titledBorder.setTitleColor(theColor);
repaint(); // revalidate not necessry