更改JTextField启用的背景颜色

我有一个关于JTextField背景颜色的问题。 如何在启用的文本字段中进行更改(编辑时)? setBackground仅适用于禁用的文本字段。 UIManager.put可以在窗口中为我的所有文本字段更改此背景,但我只想为其中一个执行此操作。

您可以通过多种方式实现此目标,但基本思路是,当字段获得焦点时,您希望将字段背景颜色设置为其他内容,当它失去焦点时,您需要重置它…

FocusChange

 import java.awt.Color; import java.awt.EventQueue; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class FocusedField { public static void main(String[] args) { new FocusedField(); } public FocusedField() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { } JTextField field1 = new JTextField(20); JTextField field2 = new JTextField(20); FocusListener highlighter = new FocusListener() { @Override public void focusGained(FocusEvent e) { e.getComponent().setBackground(Color.GREEN); } @Override public void focusLost(FocusEvent e) { e.getComponent().setBackground(UIManager.getColor("TextField.background")); } }; field1.addFocusListener(highlighter); field2.addFocusListener(highlighter); JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.insets = new Insets(4, 4, 4, 4); gbc.gridwidth = gbc.REMAINDER; frame.add(field1, gbc); frame.add(field2, gbc); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } } 

我很想写一个简单的单例“管理器”,它允许你根据需要注册和取消注册字段。

您也可以通过将一个PropertyChangeListener附加到KeyboardFocusManager来实现类似的function,这将允许您将此突出显示概念基本应用于任何程序中的所有字段,而无需更改任何代码,但这取决于您的要求

我认为它适用于textField.setForeground(Color.RED) 🙂

只需在textField上添加一个ActionListener,然后在Listener中设置Background。

好的,我需要的是:

 Properties props = new Properties(); props.put("showFocusFrame", "off"); ((AbstractLookAndFeel)UIManager.getLookAndFeel()).getTheme().setProperties(prop‌​s);