简体   繁体   English

Java:KeyLIstener和paintComponent不配合

[英]Java: KeyLIstener and paintComponent not cooperating

I have been trying to make a java program that shows a circle on the screen. 我一直试图制作一个在屏幕上显示一个圆圈的java程序。 I have three classes: 我有三节课:

  1. first ---> initializes the frame and adds the key listener from input. 首先--->初始化框架,并从输入中添加键侦听器。

  2. panel ---> contains the paintComponent method and the method that will move the object across the screen(I even remembered to put repaint(); ) 面板--->包含paintComponent方法和将对象在屏幕上移动的方法(我什至还记得放repaint();)

  3. input ---> implements KeyListener and calls the animation method in panel 输入--->实现KeyListener并在面板中调用animation方法

In the input class I have this if statment: 在输入类中,我有以下if陈述:

if (e.getKeyCode() == KeyEvent.VK_D) {
  new panel().animation();
}

here is the animation method inside of the panel class : 这是panel类内部的动画方法:

public void animation() {
  playerX += 10;
  System.out.println(playerX);
  repaint();
}

when I runthe program, I know the animation method is being ran because it is outputing playerX to the console (it increased evey time like it was supposed to), but the repaint(); 当我运行程序时,我知道动画方法正在运行,因为它会将playerX输出到控制台(它像预期的那样增加了传送时间),但是repaint(); command is being ignored! 命令被忽略! What am I doing wrong? 我究竟做错了什么?

Your KeyListener is creating a new panel every time it receives a VK_D event, and invoking animation() on that. 您的KeyListener每次接收到VK_D事件都会创建一个新panel ,并在该panel调用animation() That is unlikely to be what you want. 那不可能是您想要的。 It should probably be invoking animation() always on the same panel object, that panel being a visible component in the application UI. 可能应该总是在同一panel对象上调用animation() ,该panel是应用程序UI中的可见组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM