你可以帮我这个java程序吗?

时间:2015-08-23 09:36:18

标签: java swing

我刚开始使用摇摆和事件 我想要的是一个基本程序,窗口中有一个按钮,当你点击按钮时,椭圆会在屏幕上移动一段时间,就像想要像动画一样。 这就是我为它做的事情

package testmode;

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Ainmationtester implements ActionListener {

JFrame frame;
JButton Button;
int x = 30, y = 30;

Ainmationtester tester = new Ainmationtester();
Ainmationtester.MyDrawPanels test = tester.new MyDrawPanels();

public static void main(String[] args) {
    // TODO Auto-generated method stubc
    Ainmationtester test = new Ainmationtester();
    test.go();

}

public void go() {
    frame = new JFrame("Aniamtor");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500, 500);
    frame.setVisible(true);
    Button = new JButton("CLick me to Animate");
    Button.addActionListener(this);

    frame.getContentPane().add(BorderLayout.NORTH, Button);
    frame.getContentPane().add(BorderLayout.CENTER, test);

}

public class MyDrawPanels extends JPanel {

    public void paintComponent(Graphics g) {

        g.fillOval(x, y, 10, 10);
    }
}

public void actionPerformed(ActionEvent event) {

    for (int i = 0; i < 200; i++){
        test.repaint();
    x++;
    y++;
    }
}
}

1 个答案:

答案 0 :(得分:3)

我根据你的代码写了一个例子。

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Ainmationtester implements ActionListener {

    JFrame frame;
    JButton Button;
    int x = 30, y = 30;
    MyDrawPanels draw = new MyDrawPanels();
    public static void main(String[] args) {
        Ainmationtester test = new Ainmationtester();
        test.go();

    }

    public void go() {
        frame = new JFrame("Aniamtor");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 500);
        Button = new JButton("CLick me to Animate");
        Button.addActionListener(this);
        frame.getContentPane().add(BorderLayout.NORTH, Button);
        frame.getContentPane().add(BorderLayout.CENTER, draw);
        frame.setVisible(true);
    }

    public class MyDrawPanels extends JPanel {
        private static final long serialVersionUID = 1L;
        public void paintComponent(Graphics g) {
            g.fillOval(x, y, 50, 50);
        }
    }

    public void actionPerformed(ActionEvent event) {
        x += 5;
        y += 5;
        frame.repaint();
    }
}

最终的run屏幕截图如下

enter image description here

enter image description here 希望有所帮助