Java 如何制作动画圆圈?
我还在学习图形用户界面,在理解线程方面仍然有一些困难:/ 我正在制作这个GUI,其中有两个圆圈,一个大(100x100)和一个小(50x50)。在0.5秒内,小圆将移到大圆的边缘,当用户必须单击时,小圆将移到中心。每当用户在圆圈在中间点击时,用户就得分。我唯一的问题是圆圈没有移动,因为我怀疑它与我的线程有关,因此我使用线程的原因是为了知道如何使用它们 桂 主要 我知道我没有使用所有的Java 如何制作动画圆圈?,java,swing,animation,user-interface,paintcomponent,Java,Swing,Animation,User Interface,Paintcomponent,我还在学习图形用户界面,在理解线程方面仍然有一些困难:/ 我正在制作这个GUI,其中有两个圆圈,一个大(100x100)和一个小(50x50)。在0.5秒内,小圆将移到大圆的边缘,当用户必须单击时,小圆将移到中心。每当用户在圆圈在中间点击时,用户就得分。我唯一的问题是圆圈没有移动,因为我怀疑它与我的线程有关,因此我使用线程的原因是为了知道如何使用它们 桂 主要 我知道我没有使用所有的mouselistener方法。需要记住的几点: 如果没有覆盖所有方法,请使用MouseAdaptor而不是Mou
mouselistener
方法。需要记住的几点:
MouseAdaptor
而不是MouseListener
JFrame
,JApplet
上涂漆,而应使用JPanel
Thread.sleep()
阅读更多
paintComponent()
方法中调用super.paintComponent()
frame.setVisible(true)
frame.pack()
而不是frame.setSize()
getPreferredSize()
以设置自定义绘制时JPanel
的首选大小示例代码:(根据您的自定义绘画进行更改) 我应该在run()方法中调用它吗?
public class gui extends JPanel implements MouseListener,
Runnable {
Thread t = new Thread();
int score = 0;
int rnd;
static final int smallcircleposx = 75;
static final int smallcircleposy = 75;
int circleposx = 75;
int circleposy = 75;
int mousex, mousey;
Random random = new Random();
public gui() {
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillOval(50, 50, 100, 100);
g.setColor(Color.RED);
g.fillOval(circleposx, circleposy, 50, 50);
}
// THREAD FOR MOVING THE CIRCLE
public void run() {
rnd = random.nextInt(999);
if (rnd % 5 == 0) {
circleposx = circleposx + 25;
} else if (rnd % 4 == 0) {
circleposx = circleposx - 25;
} else if (rnd % 3 == 0) {
circleposy = circleposy + 25;
} else {
circleposy = circleposy - 25;
}
try {
Thread.sleep(500);
circleposx = smallcircleposx;
circleposy = smallcircleposy;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void mouseClicked(MouseEvent m) {
if (circleposx == smallcircleposx && circleposy == smallcircleposy) {
score++;
}
}
public class main {
public static void main(String[] args) {
JFrame frame = new JFrame("Circle enlarger");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setVisible(true);
gui co = new gui();
frame.add(co);
frame.addMouseListener(co);
Thread x = new Thread(new gui());
x.start();
}
}
private Timer timer;
...
// 500 Milli-seconds
timer = new javax.swing.Timer(500, new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// change the coordinate
panel.repaint();
if (condition) {
timer.stop(); // you can stop the timer anytime
}
}
});
timer.setRepeats(true); // you can turn-off the repeatation
timer.start();
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// Initialize the UI
}
});
}
class MyJPanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
...
}
@Override
public Dimension getPreferredSize() {
return new Dimension(..., ...);
}
}