java 在java中动态更改TitledBorder颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15879216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 21:10:11  来源:igfitidea点击:

change TitledBorder color dynamically in java

javaswingjpanelbordertitled-border

提问by sajad

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

我创建了一个 TitledBorder 并将其设置为 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 thiledBorderand 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

现在我想更改边框标题文本的颜色;如果可能的话,边界线。当我通过方法titledborder.setTitleColor(theColor);revalidate()和改变边框的颜色时,我看到了repaint();表格面板不受影响。我还创建了新实例thiledBorder并将其分配给面板;但没有效果。是否有必要更新面板,然后将其设置为新的边框实例?谢谢

回答by Reimeus

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

您没有说明如何titledborder分配,但这就是它的工作方式:

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

then at runtime:

然后在运行时:

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

回答by Dave Marsh

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

如果你知道你的面板有一个标题边框,你可以这样做:

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