当我按下键盘上的给定键时,我试图让JFrame中的矩形移动,但我似乎很难做到这一点。这是我的代码:
package TestPackage;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JComponent;
public class Mainframe extends JComponent implements KeyListener
{
private static final long serialVersionUID = 1L;
int x = 350;
int y = 250;
public static void main (String[] args)
{
JFrame frame = new JFrame ("Mainframe");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.setSize (800, 600);
frame.setFocusable (true);
frame.getContentPane().setBackground (Color.WHITE);
frame.getContentPane().add (new Mainframe());
frame.addKeyListener (new Mainframe());
frame.setVisible (true);
}
public void paint (Graphics graphics)
{
graphics.setColor (Color.BLACK);
graphics.fillRect (x, y, 100, 100);
}
public void keyPressed (KeyEvent event)
{
if (event.getKeyCode() == KeyEvent.VK_A)
{
x++;
repaint();
}
else if (event.getKeyCode() == KeyEvent.VK_D)
{
y++;
repaint();
}
}
public void keyReleased (KeyEvent event) {}
public void keyTyped (KeyEvent event) {}
}
我确定这是我的KeyListener的一个问题,因为其他一切都很完美。有人知道我做错了什么吗?感谢。
答案 0 :(得分:1)
MainFrame
个实例,一个添加到框架中,另一个用作JFrame
KeyListener
,这意味着{{1}实例使用KeyListener
值,UI上的实例不会看到x/y
,它有太多与焦点相关的问题,请使用旨在克服这些问题的Key Bindings API。请参阅How to Use Key Bindings KeyListener
(特别是如果您不打算致电paint
),则应覆盖super.paint
方法(并致电paintComponent
)。有关详细信息,请参阅Painting in AWT and Swing和Performing Custom Painting 例如......
super.paintComponent
答案 1 :(得分:0)
使你的主要像这样,它将工作
public static void main (String[] args)
{
JFrame frame = new JFrame ("Mainframe");
JComponent test = new Mainframe();
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.setSize (800, 600);
frame.setFocusable (true);
frame.getContentPane().setBackground (Color.WHITE);
frame.getContentPane().add (test);
frame.addKeyListener ((KeyListener) test);
frame.setVisible (true);
}