View Full Version : [JAVA] Tasti
come faccio a fare in modo che un programma in java riesca a capire quando premo un tasto?
come faccio a fare in modo che un programma in java riesca a capire quando premo un tasto?Se lavori con una interfaccia grafica AWT/Swing devi usare un apposito listener.
Comunque leggi <qui> (http://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html) sul tutorial.
bene, ma adesso io ho la classe per i tasti
public class tasti implements KeyListener {
/** Handle the key typed event from the text field. */
public void keyTyped(KeyEvent e) {
displayInfo(e, "KEY TYPED: ");
}
/** Handle the key-pressed event from the text field. */
public void keyPressed(KeyEvent e) {
displayInfo(e, "KEY PRESSED: ");
}
/** Handle the key-released event from the text field. */
public void keyReleased(KeyEvent e) {
displayInfo(e, "KEY RELEASED: ");
}
...
private void displayInfo(KeyEvent e, String keyStatus){
//You should only rely on the key char if the event
//is a key typed event.
int id = e.getID();
String keyString;
if (id == KeyEvent.KEY_TYPED) {
char c = e.getKeyChar();
keyString = "key character = '" + c + "'";
} else {
int keyCode = e.getKeyCode();
keyString = "key code = " + keyCode
+ " ("
+ KeyEvent.getKeyText(keyCode)
+ ")";
}
int modifiersEx = e.getModifiersEx();
String modString = "extended modifiers = " + modifiersEx;
String tmpString = KeyEvent.getModifiersExText(modifiersEx);
if (tmpString.length() > 0) {
modString += " (" + tmpString + ")";
} else {
modString += " (no extended modifiers)";
}
String actionString = "action key? ";
if (e.isActionKey()) {
actionString += "YES";
} else {
actionString += "NO";
}
String locationString = "key location: ";
int location = e.getKeyLocation();
if (location == KeyEvent.KEY_LOCATION_STANDARD) {
locationString += "standard";
} else if (location == KeyEvent.KEY_LOCATION_LEFT) {
locationString += "left";
} else if (location == KeyEvent.KEY_LOCATION_RIGHT) {
locationString += "right";
} else if (location == KeyEvent.KEY_LOCATION_NUMPAD) {
locationString += "numpad";
} else { // (location == KeyEvent.KEY_LOCATION_UNKNOWN)
locationString += "unknown";
}
...//Display information about the KeyEvent...
}
}
come faccio a integrarla nel main? con tasti = new tasti(); poi??
Devi aggiungerla al componente che ti interessa monitorare, esempio:
label.addKeyListener( new tasti() );
PS: per leggibilità i nomi di classi andrebbero con la maiuscola.
Devi aggiungerla al componente che ti interessa monitorare, esempio:
label.addKeyListener( new tasti() );
PS: per leggibilità i nomi di classi andrebbero con la maiuscola.
mmm ma nel esempio della matrice a ogni cella devo metterli un'ascoltatore tasti? nn posso metterlo al layout?
Adesso non saprei, prova ad aggiungerlo al pannello.
vBulletin® v3.6.4, Copyright ©2000-2024, Jelsoft Enterprises Ltd.