|
|||||||
|
|
|
![]() |
|
|
Strumenti |
|
|
#1 |
|
Member
Iscritto dal: Jan 2009
Città: Trento
Messaggi: 81
|
[JAVA] Problema KeyListener
Sto facendo un programma che, disegnato un pallino al centro di un pannello, lo sposti di 10 pixel alla pressione di 'a', 's', 'w' e 'z'. Tuttavia nella classe che implementa il Key Listener non so bene che scrivere..ecco come l'ho fatta per ora.
Codice:
package ex3;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Pane extends JPanel{
Dimension paneSize=this.getSize();
int x=400/2-25/2;
int y=300/2-25/2;
protected void paintComponent(Graphics g){
g.setColor(Color.RED);
g.fillOval(x, y, 25, 25);
}
public Pane(){
this.setFocusable(true);
this.addKeyListener(new Move());
}
class Move implements KeyListener{
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e) {
if(e.getKeyChar()=='a'){
x=x+10;
repaint();
}
}
public void keyReleased(KeyEvent e) {}
}
}
|
|
|
|
|
|
#2 |
|
Senior Member
Iscritto dal: Nov 2004
Città: Tra Verona e Mantova
Messaggi: 4553
|
Usa e.getKeyCode() == KeyEvent.VK_A. Potrebbe essere necessario un click del mouse sul pannello prima che questo inizi a reagire agli eventi da tastiera per via del focus. Comunque il codice è ok.
__________________
Uilliam Scecspir ti fa un baffo? Gioffri Cioser era uno straccione? E allora blogga anche tu, in inglese come me! |
|
|
|
|
|
#3 | |
|
Senior Member
Iscritto dal: Feb 2007
Città: Verona
Messaggi: 1060
|
Quote:
http://www.hwupgrade.it/forum/showpo...50&postcount=3
__________________
|
|
|
|
|
|
|
#4 |
|
Senior Member
Iscritto dal: Oct 2007
Città: Padova
Messaggi: 4131
|
Credo che per il focus basti prima richiederlo invocando requestFocusInWindow sul componente.
__________________
As long as you are basically literate in programming, you should be able to express any logical relationship you understand. If you don’t understand a logical relationship, you can use the attempt to program it as a means to learn about it. (Chris Crawford) |
|
|
|
|
|
#5 |
|
Member
Iscritto dal: Jan 2009
Città: Trento
Messaggi: 81
|
|
|
|
|
|
|
#6 | |
|
Senior Member
Iscritto dal: Feb 2007
Città: Verona
Messaggi: 1060
|
Quote:
__________________
|
|
|
|
|
|
| Strumenti | |
|
|
Tutti gli orari sono GMT +1. Ora sono le: 08:26.




















