/** TxtApp.java à l'écoute des événements clavier dans un TextField appui sur R/C récupéré (cf. classe RobotTxtApp) frappe d'un caractère standard (cf. classe RobotTxtApp) quelques touches reprérées (ALT, F1 ...) fenêtre swing.JFrame */ import javax.swing.*; import java.awt.*; import java.awt.event.*; public class TxtApp extends JFrame { FlowLayout geometre = new FlowLayout(); TextField z_txt = new TextField("toto",30); String txt = new String(); //Construire la fenêtre principale public TxtApp() { try { dessineFen(); } catch (Exception e) { e.printStackTrace(); } } // Méthode reconnue par l'EDI private void dessineFen() throws Exception { this.getContentPane().setLayout(geometre); z_txt.setEchoChar('*'); z_txt.setBackground(Color.yellow); this.getContentPane().add(z_txt); // Evénements clavier RobotTxtApp cap = new RobotTxtApp(); z_txt.addActionListener(cap); z_txt.addKeyListener(cap); // Pour quitter l'application par l'encadrement WindowAdapter pf; pf = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); }; }; this.addWindowListener(pf); } //Méthode principale public static void main(String[] args) { TxtApp fen = new TxtApp(); fen.setTitle("Titre du cadre"); fen.setSize(new Dimension(400, 300)); fen.validate(); fen.setLocation(200,300); fen.setVisible(true); } class RobotTxtApp implements ActionListener, KeyListener { RobotTxtApp() { ;} // Appui sur R/C dans un champ texte (TextField) public void actionPerformed(ActionEvent e) { TextField t = (TextField)e.getSource(); System.out.print("RobotTxtApp.actionPerformed(): '" + t.getText() + "'"); } public void keyPressed(KeyEvent e) { String ch; // getKeyCode() KeyEvent. VK_ALT V_CVONTROL VK_HELP VK_SHIFT switch(e.getKeyCode() ) { case KeyEvent.VK_ALT: ch="touche ALT"; break; case KeyEvent.VK_BACK_SPACE: ch="touche VK_BACK_SPACE"; break; case KeyEvent.VK_CONTROL: ch="touche CONTROL"; break; case KeyEvent.VK_F1: ch="touche F1"; break; case KeyEvent.VK_HELP: ch="touche HELP"; break; case KeyEvent.VK_SHIFT: ch="touche SHIFT"; break; default: ch="Autre touche"; } System.out.println("RobotTxtApp.keyPressed()-> "+ch); } public void keyReleased(KeyEvent e) { // System.out.println("RobotTxtApp.keyReleased()"); } // Frappe d'un caractère standard public void keyTyped(KeyEvent e) { TextField t = (TextField)e.getSource(); System.out.println("RobotTxtApp.keyTypes(): "+e.getKeyChar()); } } // fin class RobotTxtApp } // fin class TxtApp