如何在Java中自动移动圆? [英] How to move a circle automatically in java?

查看:245
本文介绍了如何在Java中自动移动圆?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java GUI的新手,正在尝试学习它。我想在屏幕上自动移动一个圆圈(即不要按任何键或执行任何其他操作)。我找到了一种通过做一些动作来移动它的方法,但这不是我所需要的。请问有人可以告诉我最简单的方法吗?

I am new to java GUI, and am trying to learn it. I want to move a circle on screen automatically(i.e not by pressing any key or doing any other action). I found a way to move it by doing some action but thats not what i needed. Please could anybody tell me the simplest way of doing that?

我想在以下代码中删除动作侦听器,以便圈子自动移动:

I want to remove the action listener in the following code, so that circles move automatically:

public class MyFirstGraphics extends JFrame {

    int x = 100;
    int y = 100;

    MyFirstGraphics() {
        super("Circle");
        setSize(800, 800);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        getContentPane().setBackground(Color.pink);
        JButton f = new JButton("circle");
        f.addActionListener(new re());
        add(f, BorderLayout.NORTH);
    }

    private class re implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            for (int i = 1; i < 50; i++) {
                x++;
                y++;
                repaint();
            }
        }
    }

    public void paint(Graphics g) {
        super.paint(g);
        g.drawOval(x, y, 100, 100);
    }

    public static void main(String[] args) {
        MyFirstGraphics l = new MyFirstGraphics();
        l.setVisible(true);
    }
}


推荐答案

让首先,动画是随着时间变化的幻觉。另外,Swing是一个单线程环境。您不能阻止 Swing线程(也称为事件调度线程)并绘制更新,您需要某种方式来定期安排更新,以便您可以应用更改,然后重新绘制更改...

Lets start with the fact that animation is the illusion of change over time. Also, Swing is a single threaded environment. You can't "block" the Swing thread (aka the Event Dispatching Thread) and have it paint updates, you need some way to schedule updates at a regular bases so you can apply a change and then have the change repainted...

所以您的第一个问题是您的 actionPerformed 方法...

So your first problem is in your actionPerformed method...

for (int i = 1; i < 50; i++) {
    x++;
    y++;
    repaint();
}

基本上,唯一可以绘制的东西是150x150的球

Basically, the only thing that will get painted is the ball at 150x150, nothing else in between will be painted.

相反,您需要将其更改为类似...

Instead, you need to change it to something more like...

public void actionPerformed(ActionEvent e) {
    if (x < 150 && y < 150) {
        x++;
        y++;
    } else {
        ((Timer)e.getSource()).stop();
    }
    repaint();
}

看看:

  • Performing Custom Painting
  • 2D Graphics
  • Concurrency in Swing
  • How to Use Swing Timers

了解更多详情

弹力球的基本示例

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class BounceyDot {

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

    public BounceyDot() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private int x = 0;
        private int y = 100;
        private int radius = 20;
        private int xDelta = 2;

        public TestPane() {
            Timer timer = new Timer(40, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    x += xDelta;
                    if (x + (radius * 2) > getWidth()) {
                        x = getWidth() - (radius * 2);
                        xDelta *= -1;
                    } else if (x < 0) {
                        x = 0;
                        xDelta *= -1;
                    }
                    repaint();
                }
            });
            timer.start();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.RED);
            g.fillOval(x, y - radius, radius * 2, radius * 2);
        }
    }

}

这篇关于如何在Java中自动移动圆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆