0
当然,我制作了一个JTextField,并且当它没有任何字符时,我希望它的背景为红色,并且一旦写入字符被自动更改为绿色。自动更新JTextField的背景颜色
我想这码
textField1.setBackground(textField1.getText().equalsIgnoreCase("") ? Color.RED : Color.GREEN);
,但它不会自动更新。
感谢
当然,我制作了一个JTextField,并且当它没有任何字符时,我希望它的背景为红色,并且一旦写入字符被自动更改为绿色。自动更新JTextField的背景颜色
我想这码
textField1.setBackground(textField1.getText().equalsIgnoreCase("") ? Color.RED : Color.GREEN);
,但它不会自动更新。
感谢
你应该添加的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)
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();
}
}
插入文本之前的JTextField
在JTextField中插入文本
作品完美了!谢谢! – Boolena
@Boolena欢迎.. –