我正在尝试使用代码来移动画布上绘制的内容。但是,我不知道如何去做。截至目前,每当我按下应该使对象向右或向左移动的键时,绘制的对象就会消失。但是,其他不应移动的对象会留在屏幕上。
更多信息:运行时,代码只会显示绘制的圆圈。但是,我认为它永远被重新绘制,因为绘图一直在闪烁和闪烁。当我尝试按下与键监听器关联的按钮时,没有任何反应。
按下按钮几秒钟后,圆圈完全消失。
以下代码制作不当且杂乱无章:
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();
}
}
答案 0 :(得分:1)