当我按键盘上的Tab键时,我想按上述顺序选择我的文本字段。如何做到这一点?
答案 0 :(得分:0)
试试这个例子......
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);
}
});
}
}
答案 1 :(得分:0)
jTextField1.setNextFocusableComponent(jTextField2);
jTextField2.setNextFocusableComponent(jTextField3);
jTextField3.setNextFocusableComponent(jTextField4);
jTextField4.setNextFocusableComponent(jTextField5);
尝试:)
答案 2 :(得分:0)
尝试一下:
txtfld.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
txtfld.setText("aaa");
}
@Override
public void focusLost(FocusEvent e) {
...
}
});
see更完整的代码。