倒,不是和我的思路一样吗? 不过我在补充一点。 To make a component get the keyboard focus, follow these steps: Make sure the component's isFocusTraversable method returns true. This lets the user tab to your component. For example, you can enable keyboard focus for a custom JLabel subclass by overriding the isFocusTraversable method to return true. Make sure that the component requests the focus when appropriate. For custom components, you'll probably need to implement a mouse listener that calls the requestFocus method when the component is clicked. 此时,相关对象可以接受键盘操作
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;public class textfield1 extends JFrame implements KeyListener{
JTextField jTextField1 = new JTextField();
JButton jButton1 = new JButton();
JButton jButton2 = new JButton();
public textfield1() {
try {
jbInit();
}
catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
textfield1 textfield11 = new textfield1();
textfield11.setSize(400,300);
textfield11.setVisible(true);
textfield11.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void jbInit() throws Exception {
jTextField1.setText("jTextField1");
jTextField1.setEditable(false);
jTextField1.setBounds(new Rectangle(60, 25, 233, 23));
this.getContentPane().setLayout(null);
jButton1.setBounds(new Rectangle(29, 97, 113, 37));
jButton1.setText("jButton1");
jButton2.setBounds(new Rectangle(186, 97, 122, 36));
jButton2.setText("jButton2");
this.getContentPane().add(jTextField1, null);
this.getContentPane().add(jButton1, null);
this.getContentPane().add(jButton2, null);
jTextField1.addKeyListener(this);
jButton1.addKeyListener(this);
jButton2.addKeyListener(this);
} public void keyTyped(KeyEvent e) { } public void keyPressed(KeyEvent e) {
jTextField1.setFocusable(true);
if(e.getKeyCode() == KeyEvent.VK_0){
jTextField1.setText("零");
}
if(e.getKeyCode() == KeyEvent.VK_1){
jTextField1.setText("壹");
}
if(e.getKeyCode() == KeyEvent.VK_2){
jTextField1.setText("贰");
}
if(e.getKeyCode() == KeyEvent.VK_3){
jTextField1.setText("叁");
}
//可以写一个方法来搞定她,不然代码可读性太差。
} public void keyReleased(KeyEvent e) {
}}
祝你好运!
不过我在补充一点。
To make a component get the keyboard focus, follow these steps: Make sure the component's isFocusTraversable method returns true. This lets the user tab to your component. For example, you can enable keyboard focus for a custom JLabel subclass by overriding the isFocusTraversable method to return true.
Make sure that the component requests the focus when appropriate. For custom components, you'll probably need to implement a mouse listener that calls the requestFocus method when the component is clicked. 此时,相关对象可以接受键盘操作
WHEN_IN_FOCUSED_WINDOW