我的代码如下:
package playingwithjava;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
*
* @author user
*/
public class Window extends JFrame implements ActionListener{
//init stuff
Container ca=getContentPane();
GridBagLayout gridLayout= new GridBagLayout();
GridBagConstraints lol=new GridBagConstraints();
//actual important stuff
JButton done=new JButton("Done!");
JTextField text=new JTextField("",25);
JLabel label=new JLabel("Your name is:");
public Window(int x,int y)
{
super("Playing With Java");
setSize(x,y);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ca.setLayout(gridLayout);
//start of the code
lol.gridx=0;lol.gridy=0;
ca.add(label,lol);
lol.gridx=0;lol.gridy=1;
text.addActionListener(this);
ca.add(text,lol);
lol.gridx=1;lol.gridy=1;
//done.setEnabled(false);
done.addActionListener(this);
ca.add(done,lol);
//ending
setContentPane(ca);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent event)
{
if(event.getSource()==done)
{
JOptionPane.showMessageDialog(null,"Hello, "+text.getText()+"!","Hi!",JOptionPane.NO_OPTION);
}
if(event.getSource()==text)
{
JOptionPane.showMessageDialog(null,"a","Hi!",JOptionPane.NO_OPTION);
}
}
}
当我更改TextField中的文本时,我不明白为什么没有任何反应。
答案 0 :(得分:5)
按Enter键时调用ActionListener。
要监听文本字段中的更改,您应该使用DocumentListener。有关详细信息,请参阅How to Write a Document Listener。