我写了下面的代码来使用箭头键移动一个矩形,但是当我按下键时,jframe窗口上没有发生任何移动。我搜索了很多关于这个,但无济于事。我只看到一个寡妇画出的矩形而没有别的。请帮助 这是我的代码
import javax.swing.JFrame;
public class Main
{
public static void main(String args[])
{
JFrame window=new JFrame();
window.setSize(640,480);
window.setTitle("window");
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawingComponent DC=new drawingComponent();
window.add(DC);
}
}
import java.awt.Graphics2D;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Event;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JComponent;
import javax.swing.Timer;
public class drawingComponent extends JComponent implements ActionListener,KeyListener
{
Timer t=new Timer(50,this);//moving after 5 milliseconds
int x=0,y=0,vx=0,vy=0;
public drawingComponent()
{
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void paintComponent(Graphics g)
{
Graphics2D g2=(Graphics2D) g;
Rectangle rect1=new Rectangle(x,y,100,30);
g2.draw(rect1);
}
public void actionPerformed(ActionEvent e) //inbuilt fncn f actionListener(interface) which needs to be created
{
x+=vx; //changing values
y+=vy;
repaint(); //inbuilt fncn to repeat the paintComponent method
}
public void keyPressed(KeyEvent e)
{
System.out.println("ewbkw");
int code=e.getKeyCode();
if(code==KeyEvent.VK_UP)
{ vx=0; vy=-2;repaint(); }
if(code==KeyEvent.VK_DOWN)
{ vx=0; vy=2; repaint(); }
if(code==KeyEvent.VK_LEFT)
{vy=0; vx=-2; repaint(); }
if(code==KeyEvent.VK_RIGHT)
{vy=0; vx=2; repaint();}
}
public void keyTyped(KeyEvent e)
{}
public void keyReleased(KeyEvent e)
{}
}
答案 0 :(得分:0)
您可以尝试使用ArrayList
添加按下ArrayList
的密钥,然后在发布后将其删除。
您也可以使用
repaint();
在您的所有if
语句
public void keyPressed(KeyEvent e)
{
System.out.println("ewbkw");
int code = e.getKeyCode();
if(code==KeyEvent.VK_UP){
vx=0; vy=-2;
}
if(code==KeyEvent.VK_DOWN){
vx=0; vy=2;
}
if(code==KeyEvent.VK_LEFT){
vy=0; vx=-2;
}
if(code==KeyEvent.VK_RIGHT){
vy=0; vx=2;
}
repaint();
}
如果您只对if
语句使用一个语句,那么您将不需要使用Curly Brackets {}
if (true)
System.out.println("Example of no brackets");
else
System.out.println("Not even for an IF ELSE");
你也可能不需要定时器。但我可能是错的。