netbeans 如何在java中使用Tab键选择文本字段

91zkwejq  于 2022-11-10  发布在  Java
关注(0)|答案(3)|浏览(151)

当我按下键盘上的Tab键时,我想在上面的www.example.com中选择我的文本字段order.how来执行该操作?

wvmv3b1j

wvmv3b1j1#

请尝试以下示例....

package com.Demo;

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

@SuppressWarnings("serial")
public class TabTest extends JFrame {
    public TabTest() {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setTitle("JTextArea TAB DEMO");
        setDefaultCloseOperation(JFrame.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 behaviour 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 TabTest().setVisible(true);
            }
        });
    }
}
ldxq2e6h

ldxq2e6h2#

jTextField1.setNextFocusableComponent(jTextField2);
jTextField2.setNextFocusableComponent(jTextField3);
jTextField3.setNextFocusableComponent(jTextField4);
jTextField4.setNextFocusableComponent(jTextField5);

试试这个:)

hvvq6cgz

hvvq6cgz3#

试试看:

txtfld.addFocusListener(new FocusListener() {
        @Override
        public void focusGained(FocusEvent e) {                
            txtfld.setText("aaa");
        }

        @Override
        public void focusLost(FocusEvent e) {
           ...
        }
    });

see更完整的代码。

相关问题