cls*_*tek 3 java swing background colors jtextfield
我有一个关于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);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
我很想写一个简单的单例"管理器",它允许你根据需要注册和取消注册字段.
您也可以通过附加一个类似的东西来实现类似PropertyChangeListener的功能KeyboardFocusManager,这样您就可以将这个突出显示概念基本应用于任何程序中的所有字段,而无需更改任何代码,但这取决于您的要求
| 归档时间: |
|
| 查看次数: |
20641 次 |
| 最近记录: |