change TitledBorder color dynamically in java

戏子无情 提交于 2019-12-13 00:23:39

问题


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


回答1:


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



回答2:


If you know your panel has a titled border you can just do this:

    TitledBorder titledBorder = (TitledBorder)jPanel1.getBorder();
    titledBorder.setTitleColor(Color.red);


来源:https://stackoverflow.com/questions/15879216/change-titledborder-color-dynamically-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!