2014-03-04 190 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中插入文本