Inicio > Programación, java > KeyEvent simple en java

KeyEvent simple en java

Tuesday, 24 de February de 2009

Este código me fué de mucha ayuda cuando recién empecé a ver algo de java en el instituto, espero que le sirva a las nuevas generaciones de programadores.

Acá tenemos un keyListener, su función es captar los eventos del teclado,tanto con o sin modificadores, esto se refiere a si el usuario usa SHIFT o no.

El código está funcionando, es autónomo, para ejecutar el ejemplo se debe agregar al proyecto a darle RUN.

JAVA:
  1. package keyListener;
  2.  
  3. import javax.swing.*;
  4. import java.awt.event.*;
  5. import java.awt.BorderLayout;
  6. import java.awt.Dimension;
  7.  
  8. public class KeyEventDemo extends JPanel
  9. implements KeyListener,
  10. JTextArea displayArea;
  11. JTextField typingArea;
  12. static final String nuevaLinea = "\n";
  13.  
  14. public KeyEventDemo() {
  15. super(new BorderLayout());
  16.  
  17. JButton button = new JButton("Clear");
  18. button.addActionListener(this);
  19.  
  20. typingArea = new JTextField(20);
  21. typingArea.addKeyListener(this);
  22.  
  23. displayArea = new JTextArea();
  24. displayArea.setEditable(false);
  25. JScrollPane scrollPane = new JScrollPane(displayArea);
  26. scrollPane.setPreferredSize(new Dimension(375, 125));
  27.  
  28. add(typingArea, BorderLayout.PAGE_START);
  29. add(scrollPane, BorderLayout.CENTER);
  30. add(button, BorderLayout.PAGE_END);
  31. }
  32.  
  33. /** Handle the key typed event from the text field. */
  34. public void keyTyped(KeyEvent e) {
  35. displayInfo(e, "KEY TYPED: ");
  36. }
  37.  
  38. /** Handle the key pressed event from the text field. */
  39. public void keyPressed(KeyEvent e) {
  40. displayInfo(e, "KEY PRESSED: ");
  41. }
  42.  
  43. /** Handle the key released event from the text field. */
  44. public void keyReleased(KeyEvent e) {
  45. displayInfo(e, "KEY RELEASED: ");
  46. }
  47.  
  48. /** Handle the button click. */
  49. public void actionPerformed(ActionEvent e) {
  50. //Limpia los componentes de texto.
  51. displayArea.setText("");
  52. typingArea.setText("");
  53.  
  54. //Vuelve el foco al área de tipeo.
  55. typingArea.requestFocusInWindow();
  56. }
  57.  
  58. protected void displayInfo(KeyEvent e, String s){
  59. String keyString, modString, tmpString,
  60. actionString, locationString;
  61.  
  62. int id = e.getID();
  63. if (id == KeyEvent.KEY_TYPED) {
  64. char c = e.getKeyChar();
  65. keyString = "key character = '" + c + "'";
  66. } else {
  67. int keyCode = e.getKeyCode();
  68. keyString = "key code = " + keyCode
  69. + " ("
  70. + KeyEvent.getKeyText(keyCode)
  71. + ")";
  72. }
  73.  
  74. int modifiers = e.getModifiersEx();
  75. modString = "modificadores = " + modifiers;
  76. tmpString = KeyEvent.getModifiersExText(modifiers);
  77. if (tmpString.length()> 0) {
  78. modString += " (" + tmpString + ")";
  79. } else {
  80. modString += " (sin modificadores)";
  81. }
  82.  
  83. actionString = "¿Tecla de acción? ";
  84. if (e.isActionKey()) {
  85. actionString += "SI";
  86. } else {
  87. actionString += "NO";
  88. }
  89.  
  90. locationString = "Ubicación tecla: ";
  91. int location = e.getKeyLocation();
  92. if (location == KeyEvent.KEY_LOCATION_STANDARD) {
  93. locationString += "standard";
  94. } else if (location == KeyEvent.KEY_LOCATION_LEFT) {
  95. locationString += "izquierda";
  96. } else if (location == KeyEvent.KEY_LOCATION_RIGHT) {
  97. locationString += "derecha";
  98. } else if (location == KeyEvent.KEY_LOCATION_NUMPAD) {
  99. locationString += "numpad";
  100. } else {
  101. // (location == KeyEvent.KEY_LOCATION_UNKNOWN)
  102. locationString += "desconocido";
  103. }
  104.  
  105. displayArea.append(s + nuevaLinea
  106. + "    " + keyString + nuevaLinea
  107. + "    " + modString + nuevaLinea
  108. + "    " + actionString + nuevaLinea
  109. + "    " + locationString + nuevaLinea);
  110. displayArea.setCaretPosition(displayArea.getDocument().getLength());
  111. }
  112.  
  113. /**
  114. * Se crea la GUI y se muestra.
  115. */
  116. private static void createAndShowGUI() {
  117. //Se crea y setea la ventana.
  118. JFrame frame = new JFrame("KeyEventDemo");
  119. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  120.  
  121. //Se crea y setea el content pane.
  122. JComponent newContentPane = new KeyEventDemo();
  123. newContentPane.setOpaque(true); //content panes deben ser opacos
  124. frame.setContentPane(newContentPane);
  125.  
  126. //Muestra la ventana
  127. frame.pack();
  128. frame.setVisible(true);
  129. }
  130.  
  131. public static void main(String[] args) {
  132. //Creando y mostrando la gui de esta aplicación.
  133. javax.swing.SwingUtilities.invokeLater(new Runnable() {
  134. public void run() {
  135. createAndShowGUI();
  136. }
  137. });
  138. }
  139. }

VN:F [1.0.9_379]


Comparte esto en :Enviar a Apezz
Ancelot Programación, java , , ,

Comentarios cerrados.