2014-11-08 41 views
0

我正在嘗試製作一個小程序,它將在屏幕上的隨機位置顯示一個小方塊。然後,一旦我點擊廣場我想廣場消失,並在一小段隨機時間後,我想另一個廣場出現在屏幕上的另一個隨機地方。在線程休眠之前標籤位置的更改不會生效

這裏是我的代碼:

package mouse; 

import org.apache.commons.io.FileUtils; 

import javax.imageio.ImageIO; 
import javax.swing.*; 
import java.awt.*; 
import java.awt.event.MouseEvent; 
import java.awt.event.MouseListener; 
import java.awt.image.BufferedImage; 
import java.io.File; 
import java.io.IOException; 
import java.util.Random; 

/** 
* Created by owner on 07/11/2014. 
*/ 
public class MouseTrainer extends JFrame implements MouseListener { 
    File record = new File("src\\main\\resources\\mouseRecord.txt"); 
    Random rand = new Random(); 
    JLabel lbl; 
    int x = 0; 
    int y = 0; 
    Thread recorder; 


public MouseTrainer() throws IOException { 
    super("GFXAccelerator"); 
    recorder = new Thread(new MouseRecorder(record)); 

    BufferedImage img = ImageIO.read(new File("src\\main\\resources\\square.png")); 
    ImageIcon icon = new ImageIcon(img); 


    this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 

    JPanel contentPane = new JPanel(); 
    contentPane.setOpaque(true); 
    contentPane.setBackground(Color.WHITE); 
    contentPane.setLayout(null); 

    lbl = new JLabel(); 
    lbl.setSize(20, 20); 
    lbl.setIcon(icon); 
    lbl.setLocation(0, 0); 
    contentPane.addMouseListener(this); 


    contentPane.add(lbl); 


    this.setContentPane(contentPane); 
    this.setSize(2560, 1390); 

    this.setVisible(true); 
} 

public static void main(String[] args) throws InterruptedException, IOException { 
    MouseTrainer mr = new MouseTrainer(); 


} 

public void randomPosition() throws IOException { 
    x = rand.nextInt(2540); 
    y = rand.nextInt(1350); 

    FileUtils.writeStringToFile(record, "NEW DESTINATION!\n", true); 
    lbl.setLocation(x, y); 
} 


private void hideSquare(){ 
    lbl.setBounds(new Rectangle(new Point(3000, 3000), lbl.getPreferredSize())); 
} 

@Override 
public void mouseClicked(MouseEvent e) { 
    if((e.getX() > x && e.getX() < x+20) && e.getY()>y && e.getY() <y+20){ 
     System.out.println("hello"); 
     hideSquare(); 
     try { 

      FileUtils.writeStringToFile(record, "Destination clicked: x=" + x + "; y=" + y + "\n", true); 
      Thread.sleep(500 +rand.nextInt(5000)); 
      randomPosition(); 
     } catch (IOException e1) { 
      e1.printStackTrace(); 
     } catch (InterruptedException e1) { 
      e1.printStackTrace(); 
     } 

    } 

} 

@Override 
public void mousePressed(MouseEvent e) { 


} 

@Override 
public void mouseReleased(MouseEvent e) { 

} 

@Override 
public void mouseEntered(MouseEvent e) { 

} 

@Override 
public void mouseExited(MouseEvent e) { 

} 


} 

我聽的鼠標點擊,並點擊鼠標我改變廣場的位置屏幕的面積,並做了Thread.sleep()方法來等待和畫下一個廣場。不幸的是,該位置不會改變到屏幕外的位置,並且廣場停留在同一個地方。

有人可以解釋爲什麼會發生這種情況,也許我可以在用戶點擊它之後,在下一個方塊出現之前讓方塊消失。

回答

1

谷歌Thread.sleep和Swing GUI在這個網站上,你會發現在你的程序中發生的所有其他類似的程序和類似的問題也發生在這裏。