JTextField 事件

为什么我输入aa,背景不变颜色
怎么修改

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ddddfs extends JFrame{
JTextField t = new JTextField(20);
ddddfs(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new FlowLayout());
c.add(t);
t.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
if(e.getSource()=="aa")
getContentPane().setBackground(Color.BLUE);
t.setText("");
}});
setSize(300,400);
setVisible(true);
}
public static void main(String [] args){
new ddddfs();
}
}


代码说明: 

        不需要按回车  ,自动识别文字 , 然后进行事件响应

        事件说明: ActionListener 一般用于按钮JButton等的事件响应

        JTextField 组件 使用的是另外一种文本事件响应机制

具体代码如下

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.event.DocumentEvent;

import javax.swing.event.DocumentListener;


public class ddddfs extends JFrame {

JTextField t = new JTextField(20);


ddddfs() {

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Container c = getContentPane();

c.setLayout(new FlowLayout());

c.add(t);

//t.getDocument() 首先获得文本对象, 然后添加文本事件响应

t.getDocument().addDocumentListener(new DocumentListener() {//可以响应文本事件

void changColor(String str){

if(str.equals("a")){

    getContentPane().setBackground(Color.RED);

}

if(str.equals("aa")){

getContentPane().setBackground(Color.BLUE);

}

if(str.equals("aaa")){

getContentPane().setBackground(Color.YELLOW);

}

}

@Override

public void removeUpdate(DocumentEvent e) {//删除文字

changColor(t.getText());

}

@Override

public void insertUpdate(DocumentEvent e) {//插入文字

changColor(t.getText());

}

@Override

public void changedUpdate(DocumentEvent e) {//改变文字

changColor(t.getText());

}

});

setSize(300, 400);

setVisible(true);

}


public static void main(String[] args) {

new ddddfs();

}

}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-12-08
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JTextField;

public class ddddfs extends JFrame
{
JTextField t = new JTextField(20);

ddddfs()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new FlowLayout());
c.add(t);
t.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//输入aa后回车看效果
if("aa".equals(t.getText()))
{
getContentPane().setBackground(Color.BLUE);
}
t.setText("");
}
});
setSize(300, 400);
setVisible(true);
}

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