[英]The Code Won't Repaint Properly
I'm trying to get the code to move the things that are drawn on the canvas. 我正在尝试获取代码来移动在画布上绘制的东西。 However, I don't know how to go about by it.
但是,我不知道该怎么做。 As of now, whenever I press the key that is supposed to make the object move to the right or left, the drawn object simply disappears.
到目前为止,每当我按下应该使对象向右或向左移动的键时,绘制的对象就会消失。 However, other objects that are not supposed to move stay on the screen.
但是,不应移动的其他对象仍留在屏幕上。
More information: When ran, the code would simply display the circle drawn. 更多信息:运行时,代码将仅显示绘制的圆。 However, I think that it is perpetually being repainted as the drawing keeps flashing and blinking.
但是,我认为随着图纸的不断闪烁,它会被永久重新粉刷。 When I try to press the buttons associated with the key listener, nothing happens.
当我尝试按下与按键侦听器关联的按钮时,什么也没发生。
After pressing the button for a few seconds, the circle disappears completely. 按下按钮几秒钟后,圆圈完全消失。
Here is the code that is poorly made and disorganized: 这是编写得不好且杂乱无章的代码:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
public class FaceFrame extends JFrame {
private FaceCanvas face;
public FaceFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 800);
setVisible(true);
setLayout(new BorderLayout());
face = new FaceCanvas();
add(face, BorderLayout.CENTER);
}
public static void main(String args[]) {
JFrame faceFrame = new FaceFrame();
}
}
class FaceCanvas extends Canvas
{ private int xpos, ypos;
public FaceCanvas()
{
setBackground( Color.BLUE );
setSize( 300, 300 );
xpos = ypos = 50;
}
public void paint( Graphics g )
{ // override paint method by re-defining it
g.setColor( Color.WHITE );
g.drawOval( xpos, ypos, 31, 31 );
g.drawLine( xpos + 10, ypos + 20, xpos + 20, ypos + 20 );
repaint();
}
class KeyListenerTester extends JFrame implements KeyListener {
public KeyListenerTester() {
}
@Override
public void keyTyped(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
}
}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
addX(-10);
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
}
}
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
}
}
}
public void addX(int x)
{
xpos = xpos + 10;
repaint();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.