如何恢复 JTextField 以使用默认颜色
textField.setBackground( null );
禁用或设置为只读时自动切换颜色?
使用 PropertyChangeListener:
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.text.*;
public class SSCCE extends JPanel implements PropertyChangeListener
{
public SSCCE()
{
JTextField textField = new JTextField("Some Text");
// Uncomment and run again to see the difference
//textField.addPropertyChangeListener( this );
textField.setBackground(Color.RED);
textField.setEditable(false);
add(textField);
}
public void propertyChange(PropertyChangeEvent e)
{
System.out.println(e.getPropertyName());
JTextField textField = (JTextField)e.getSource();
if ("editable".equals(e.getPropertyName()))
textField.setBackground( null );
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new SSCCE() );
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}