简体   繁体   English

如何在Java中制作圆形幻灯片? 没有持续按下

[英]How to make a circle slide in Java? Not pressing constantly

I want the oval to slide when I hold down the key. 按住键时,我希望椭圆形滑动。 But it wont work! 但这行不通!

I tried the while loop which did nothing at all. 我尝试了while循环,什么也没做。

I kinda disorganized it, but it's still readable. 我有点杂乱无章,但它仍然可读。 Im using a lower version of java so some things will look different. 我使用的Java版本较低,因此某些情况看起来会有所不同。

import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;

public class TEST extends JFrame {

    int x, y;

    private Image dbgImage;
    private Graphics dbg;

    public TEST() {
        addKeyListener(new AL());
        setTitle("CIRCLE THING");
        setSize(1000, 1000);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        setResizable(true);
        x = 150;
        y = 150;
    }

    public class AL extends KeyAdapter {
        public void keyPressed(KeyEvent e) {
            int keyCode = e.getKeyCode();

            if(keyCode == e.VK_D) {
                x++;
            }
            if(keyCode == e.VK_A) {
                x--;
            }
            if(keyCode == e.VK_W) {
                y--;
            }
            if(keyCode == e.VK_S) {
                y++;
            }
        }

        public void keyReleased(KeyEvent e) {}
    }

    public void paint(Graphics g) {
        dbgImage = createImage (getWidth(), getHeight());
        dbg = dbgImage.getGraphics();
        paintComponent(dbg);
        g.drawImage(dbgImage, 0, 0, this);
    }

    public void paintComponent(Graphics g) {
        g.fillOval(x, y, 90, 100);
        repaint();  
    }

    public static void main(String[] args) {
        new TEST(); 
    }
}

You should not be overriding paint(). 您不应该覆盖paint()。

See Motion Using the Keyboard for some examples. 有关某些示例,请参见使用键盘运动 The example moves a label, but many of the concepts are the same. 该示例移动了标签,但是许多概念是相同的。 One difference is that when you do custom painting you are responsible for invoking the repaint() method on the component when you change a property of the component. 一个区别是,当您进行自定义绘制时,您有责任在更改组件的属性时在组件上调用repaint()方法。 In your case when the change the location where you want to paint the image. 在您的情况下,当您更改要绘制图像的位置时。

You need to call the repaint() method of the image object (the oval) after changing the coordinates values. 更改坐标值后,需要调用图像对象(椭圆形)的repaint()方法。

In the end of the keyPressed() method, add dbgImage.repaint(). 在keyPressed()方法的末尾,添加dbgImage.repaint()。 This will cause the image's parent paint() method to be called, which in this case is your frame's paint() method. 这将导致图像的父paint()方法被调用,在这种情况下,该方法就是框架的paint()方法。

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

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