日期:2014-05-20 浏览次数:20773 次
import java.awt.*; import java.awt.event.*; public class Java extends Frame implements KeyListener{ static Label l= new Label("A"); public static void main(String args[]) { Java j = new Java(); l.addKeyListener(j); j.setSize(200,200); j.add(l); j.setVisible(true); } public void keyPressed(KeyEvent e) { if (e.getKeyCode()==e.VK_LEFT) { l.setText("B"); } if(e.getKeyCode()==e.VK_RIGHT) { l.setText("A"); } } public void keyTyped(KeyEvent e) { } public void keyReleased(KeyEvent e) { } }
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Java extends JFrame implements KeyListener{ static JLabel l= new JLabel("A"); static JTextField tf=new JTextField(15); public static void main(String args[]) { Java j = new Java(); j.setSize(200,200); j.getContentPane().setLayout(new FlowLayout()); j.getContentPane().add(l); j.getContentPane().add(tf); tf.addKeyListener(j); j.setVisible(true); j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void keyPressed(KeyEvent e){ if (e.getKeyCode()==KeyEvent.VK_LEFT) { System.out.println("-------"); l.setText("B"); } if(e.getKeyCode()==KeyEvent.VK_RIGHT) { l.setText("A"); } } public void keyTyped(KeyEvent e) { // System.out.println("-------"); } public void keyReleased(KeyEvent e) { // System.out.println("-------"); } }
------解决方案--------------------
public void keyPressed(KeyEvent e){ if (e.getKeyCode()==KeyEvent.VK_LEFT) { System.out.println("-------"); String txt = l.getText(); char c = txt.charAt(0); if(!txt.equals("A")) l.setText(String.valueOf((char)(c-1))); } if(e.getKeyCode()==KeyEvent.VK_RIGHT) { String txt = l.getText(); char c = txt.charAt(0); if(!txt.equals("Z")) l.setText(String.valueOf((char)(c+1))); } }