Java JTextField - 如何设置背景颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34213400/
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-08-11 15:25:27  来源:igfitidea点击:

JTextField - how to set background color?

javaswingcolorsjtextfield

提问by DamDev

I want to know how to set color of my JTextFieldcomponent. I tried this way:

我想知道如何设置JTextField组件的颜色。我试过这种方式:

setBackground(Color.white)

and it sets a white color, but when the field is marked. I want the field to be white immediately after my program starts and without any user interaction.

并且它设置为白色,但是当该字段被标记时。我希望该字段在我的程序启动后立即变为白色并且没有任何用户交互。

Thanks for help!

感谢帮助!

采纳答案by RAP

You can change background color by this code

您可以通过此代码更改背景颜色

textField.setBackground(Color.RED);

You should also check this Change JTextField enabled background color

您还应该检查此更改 JTextField 启用背景颜色

回答by user1982116

I cannot replicate the problem you're having. Perhaps you are initially seeing the background color of the component holding the JTextField, rather than the JTextField's background.

我无法复制您遇到的问题。也许您最初看到的是包含 JTextField 的组件的背景颜色,而不是 JTextField 的背景。

JFrame f = new JFrame();
f.setBackground(Color.BLUE);
f.setLayout(new GridLayout(1, 1));

JTextField tf = new JTextField();
tf.setBackground(Color.GREEN);
f.add(tf);

f.setSize(500, 500);
f.setVisible(true);

Thread.sleep(2500);
tf.setBackground(Color.RED);