How to use setNextFocusableComponent in a Jtextarea

Asked

Viewed 192 times

3

I used setNextFocusableComponent in a JTextArea, but it doesn’t work because the TAB works as a "space" inside the JTextArea, how to solve this ??

1 answer

4


You can use control+TAB to change the focus of a JTextArea for other components. By default, TAB insert tab spaces inside this component.

But nothing prevents changing this default behavior by adding a KeyAdapter to "force" shift focus when clicking TAB. I removed this example below of this website:

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class TextAreaTabMoveFocus extends JFrame {
    public TextAreaTabMoveFocus() {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setTitle("JTextArea TAB DEMO");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        JTextField textField = new JTextField();
        JPasswordField passwordField = new JPasswordField();
        final JTextArea textArea = new JTextArea();
        JScrollPane scrollPane = new JScrollPane(textArea);

        // Add key listener to change the TAB behavior in
        // JTextArea to transfer focus to other component forward
        // or backward.
        textArea.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_TAB) {
                    if (e.getModifiers() > 0) {
                        textArea.transferFocusBackward();
                    } else {
                        textArea.transferFocus();
                    }
                    e.consume();
                }
            }
        });

        getContentPane().add(textField, BorderLayout.NORTH);
        getContentPane().add(scrollPane, BorderLayout.CENTER);
        getContentPane().add(passwordField, BorderLayout.SOUTH);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TextAreaTabMoveFocus().setVisible(true);
            }
        });
    }
}

See working:

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.