2014-03-04 178 views
0

当然,我制作了一个JTextField,并且当它没有任何字符时,我希望它的背景为红色,并且一旦写入字符被自动更改为绿色。自动更新JTextField的背景颜色

我想这码

textField1.setBackground(textField1.getText().equalsIgnoreCase("") ? Color.RED : Color.GREEN); 

,但它不会自动更新。

感谢

回答

2

你应该添加的DocumentListener

textfield.getDocument().addDocumentListener(this); 

@Override 
    public void insertUpdate(DocumentEvent e) 
    { 
     textField1.setBackground(textField1.getText().equalsIgnoreCase("") ? Color.RED : Color.GREEN); 
    } 

    @Override 
    public void removeUpdate(DocumentEvent e) 
    { 
     textField1.setBackground(textField1.getText().equalsIgnoreCase("") ? Color.RED : Color.GREEN); 
    } 

    @Override 
    public void changedUpdate(DocumentEvent e) 
    { 
     textField1.setBackground(textField1.getText().equalsIgnoreCase("") ? Color.RED : Color.GREEN);  
    } 

也可以尝试设置TextField的不透明财产。

textField1.setOpaque(True) 
+0

作品完美了!谢谢! – Boolena

+0

@Boolena欢迎.. –

0
import java.awt.*; 
import javax.swing.*; 
class m extends JFrame 
{ 
JTextField t; 
public m() 
{ 
    setVisible(true); 
    setSize(1000,1000); 
    setLayout(null); 
    t =new JTextField(); 
    t.setBounds(100,100,100,100); 
    add(t); 
    Timer t1=new Timer(100,new ActionListener(){ 
    public void actionPerformed(ActionEvent e) 
     { 
     if(t.getText().equals("")) 
     { 
      t.setBackground(Color.red); 
     } 
     else 
      { 
     t.setBackground(Color.GREEN); 
     } 

     } 
      } 
     ); 
     t1.start(); 

} 

public static void main (String[] args) { 
    new m(); 
    } 
    } 

enter image description here 插入文本之前的JTextField

enter image description here 在JTextField中插入文本