Search code examples
javaswingactionlistenerjtextarea

Workaround for adding ActionListener to JTextArea


I have a program that get's input string with file path in one JTextArea and then loads it's content to a second JTextArea. Problem is that when using JTextArea I cannot add an actionListener that will load content in the second JTextArea when leaving this field. How to get around this problem ?

protected JTextArea inputField, outputField;

public Main(){
    super(new BorderLayout());
    inputField = new JTextArea(5, 20);
    outputField = new JTextArea(2, 20);
    //inputField.addActionListener(this);
    inputField.setEditable(false);
    JScrollPane scroller2 = new JScrollPane(inputField);
    JScrollPane scroller1 = new JScrollPane(outputField);

    this.add(scroller1, BorderLayout.WEST);
    this.add(scroller2, BorderLayout.EAST);
}

public void actionPerformed(ActionEvent evt) {
    String text = inputField.getText();
    (loading contents of file)
}

Solution

  • You do not want an actionListener, you want a FocusListener.

    JTextArea text = ...;
    text.addFocusListener(new FocusListener() {
        public void focusGained(FocusEvent e) {}
        public void focusLost(FocusEvent e) {
            // Load your content.
        }
    
    });