Since you edited the question and clarified that you are using a JTextField I will reorder the answer:
You don't see any output because the action command has not been set so there is nothing to display.
Try using the following in your ActionListener:
JTextField textField = (JTextField)e.getSource();
System.out.println( textField.getText() );
Of course this will only display something if the user typed something into the text field. The point is you will only see output if there is something to display. You can always verify that a piece of code is being executed by displaying a hard coded string.
However, if you question was about a JTextArea, then default Action
for using the Enter key
on a JTextArea
is to insert a newline in the text area.
If you want to invoke an action then you need to replace the default Action:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TextAreaEnter extends JPanel
{
private JTextArea message = new JTextArea(5, 20);
private JTextArea display = new JTextArea(5, 20);
public TextAreaEnter()
{
display.setEditable( false );
add( new JScrollPane(message) );
add( new JScrollPane(display) );
Action enter = new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent e)
{
display.append( message.getText() + "
" );
message.setText("");
}
};
message.getActionMap().put("insert-break", enter);
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("TextAreaEnter");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new TextAreaEnter() );
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
See: Key Bindings for a list of the default bindings for each Swing component.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…