我刚开始使用摇摆和事件 我想要的是一个基本程序,窗口中有一个按钮,当你点击按钮时,椭圆会在屏幕上移动一段时间,就像想要像动画一样。 这就是我为它做的事情
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++;
}
}
}
答案 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
屏幕截图如下