[英]How to make an animated circle?
我仍在學習GUI,但仍然難以理解線程:/
我在制作這個有2個圓圈的GUI,一個大(100x100)和一個小(50x50)。 小圓圈將移到大圓圈的邊緣,在0.5秒內,小圓圈將移至中心,當用戶必須單擊時將移至小圓圈。 每當用戶單擊圓圈中間的位置時,用戶就會得分。 我唯一遇到的麻煩是該圓環並沒有移動,因為我懷疑它與我的線程有關,因此,我使用線程來了解如何使用它們的原因。
GUI
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();
}
}
我知道我沒有使用所有的mouselistener
方法。
如果不覆蓋所有方法,請使用MouseAdaptor
而不是MouseListener
。
不要直接在頂級容器(例如JFrame
繪制,而是使用JPanel
繪制JApplet
不要使用有時會掛起整個Swing應用程序的Thread.sleep()
,而是嘗試最適合Swing應用程序的Swing Timer 。
了解更多如何使用Swing計時器
不要忘記在重寫的paintComponent()
方法中調用super.paintComponent()
。
添加所有組件后,最后調用frame.setVisible(true)
。
使用frame.pack()
代替根據組件的首選大小適合組件的frame.setSize()
。
重寫getPreferredSize()
以在自定義繪制的情況下設置JPanel
的首選大小。
使用SwingUtilities.invokeLater()或EventQueue.invokeLater()確保EDT正確初始化。
閱讀更多
值得一讀的課:執行自定義繪畫
示例代碼:( 根據您的自定義繪畫進行更改 )
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(..., ...);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.