我制作了以下代码,使用键盘的箭头键移动矩形。 “keyPressed”功能似乎没有正常工作。事实上,我不认为当按下某个键时我甚至会被调用bcz当我按下一个键时我试图打印一些文本时,它没有被打印出来。我在输出窗口看到的是一个固定在窗口左上角的固定矩形。这是我的代码....请帮助我......我拼命地需要它
import javax.swing.JFrame;
public class Main
{
public static void main(String args[])
{
JFrame window=new JFrame();
window.setSize(600,400);
window.setTitle("window");
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawingComponent DC=new drawingComponent();
window.add(DC);
}
}
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Graphics;
import java.awt.Rectangle;
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(2000,this);//moving after 5 milliseconds
static int x=0;
static int y=0;
private static int velx=0;
private static int vely=0;
public drawingComponent()
{
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
System.out.println("tr1");
}
public void paintComponent(Graphics g)
{
Graphics2D g2=(Graphics2D) g;
Rectangle rect1=new Rectangle(x,y,50,30);
g2.setColor(Color.RED);
g2.fill(rect1);
System.out.println("tr2");
}
public void actionPerformed(ActionEvent e) //inbuilt fncn f actionListener(interface) which needs to be created
{
x+=velx; //changing values
y+=vely;
System.out.println("tr3");
repaint(); //inbuilt fncn to repeat the paintComponent method
}
public void keyPressed(KeyEvent e)
{
int code=e.getKeyCode();
if(code==KeyEvent.VK_UP)
{ velx=0; vely=-1;repaint(); }
if(code==KeyEvent.VK_DOWN)
{ velx=0; vely=1; repaint(); }
if(code==KeyEvent.VK_LEFT)
{vely=0; velx=-1; repaint(); }
if(code==KeyEvent.VK_RIGHT)
{vely=0; velx=1; repaint();}
}
public void keyTyped(KeyEvent e)
{}
public void keyReleased(KeyEvent e)
{}
}
答案 0 :(得分:0)
欢迎来到KeyListener
的精彩世界......
虽然您已将组件设置为可聚焦,但您并未要求对组件进行聚焦。
您可以尝试拨打requestFocusInWindow
,但他提出了何时调用它的问题。
您可以在构造函数中调用它,但由于该组件尚未属于有效的可见组件,因此调用可能会失败。在调用addNotify
之后,您可以覆盖组件super.addNotify
方法并添加对其的调用,但requestFocusInWindow
方法不会确保将重点放在组件上
相反,您可以简单地避免所有这些麻烦并使用key bindings API代替,这将使您可以控制触发关键事件所需的焦点水平
作为旁注,您应在完全设置完UI后在框架上调用setVisible