我有一个关于JTextField
背景颜色的问题。在启用的文本字段(编辑时)中,如何更改它?setBackground
仅适用于禁用的文本字段。 UIManager.put
可以更改窗口中所有文本字段的此背景,但我只想更改其中一个文本字段。
我有一个关于JTextField
背景颜色的问题。在启用的文本字段(编辑时)中,如何更改它?setBackground
仅适用于禁用的文本字段。 UIManager.put
可以更改窗口中所有文本字段的此背景,但我只想更改其中一个文本字段。
有许多方法可以实现这一点,但基本思想是,在字段获得焦点时,您希望将字段的背景颜色设置为其他颜色,并在失去焦点时将其重置...
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
来实现类似的功能,这将使您能够基本上将此突出显示概念应用于任何程序中的所有字段,而无需更改任何代码,但这取决于您的要求。
好的,这就是我需要的:
Properties props = new Properties(); props.put("showFocusFrame", "off");
((AbstractLookAndFeel)UIManager.getLookAndFeel()).getTheme().setProperties(props);
我认为使用 textField.setForeground(Color.RED)
可以实现这个功能 :)