我有一个矩形,我想要旋转。所以我只是按每次按键切换宽度和高度。但是该键也会向下移动矩形,因此再次单击后它会旋转回原来的位置。
所以我想知道如何让它只旋转一次,之后如果再向下按(使其旋转的键)它再次向下移动但不再旋转它。
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class paint extends JLabel implements KeyListener {
int x = 1;
int y = 1;
int velocity = 20;
int w = 200;
int h = 100;
int temp;
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.BLACK);
g.setColor(Color.BLACK);
g.setColor(Color.RED);
g.fillRect(x, y, w, h);
repaint();
}
//this is the section i am talking about.
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
y += velocity;
System.out.println(y);
//the next three lines rotate the rectangle
temp = w;
w = h;
h = temp;
if (y > 261) {
y = 1;
}
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
x += velocity;
System.out.println(x);
if (x > 591) {
x = 1;
}
} else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
x -= velocity;
System.out.println(x);
if (x < 1) {
x = 591;
}
} else if (e.getKeyCode() == KeyEvent.VK_UP) {
y -= velocity;
System.out.println(y);
if (y < 1) {
y = 271;
}
}
}
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}