Using getText to output a text, but missing the last character when outputting on console

Viewed 106

I am trying to get the input from a JTextField and output it on the console using getText(). And it seems to be working except it doesn't print out the last character. If I typed Hello the output would be Hell, If I typed Hello there the output would be Hell ther .... missing the last character.

public class Generator {

    private JFrame frame;
    private JTextField textRoomName;
    private String roomName;
    
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Generator window = new Generator();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public Generator() {
        initialize();
        
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.getContentPane().setBackground(Color.GRAY);
        frame.setForeground(Color.BLACK);
        frame.setBackground(Color.BLACK);
        frame.setBounds(100, 100, 450, 500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);
        
        textRoomName = new JTextField();
        textRoomName.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                roomName = textRoomName.getText();
                
            }
        });
        textRoomName.setBounds(140, 52, 212, 20);
        frame.getContentPane().add(textRoomName);
        textRoomName.setColumns(10);
        
        JButton btnGenerate = new JButton("Generate");
        btnGenerate.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println(roomName);
            }
        });
        btnGenerate.setBounds(324, 427, 89, 23);
        frame.getContentPane().add(btnGenerate);
    }
}
1 Answers
textRoomName.addKeyListener(new KeyAdapter() {
    @Override
    public void keyPressed(KeyEvent e) {
        roomName = textRoomName.getText();
        
    }
});

Don't use a KeyListener. The Document hasn't been updated with the text yet when the keyPressed event is generated.

Instead the better API to use is a DocumentListener.

Read the sections from the Swing tutorial on:

  1. Listening For Changes on a Document and
  2. How to Write a DocumentListener

for more information and examples.

Related