标签位置的更改在线程休眠之前不会生效

时间:2014-11-08 17:36:51

标签: java swing io thread-safety listener

我正在尝试制作一个小程序,在屏幕上的随机位置显示一个小方块。然后,一旦我点击广场,我希望广场消失,经过一小段随机时间之后,我希望另一个广场出现在屏幕上的另一个随机位置。

这是我的代码:

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 个答案:

答案 0 :(得分:1)

Google Thread.sleep以及此网站上的Swing GUI,您会发现您的程序中发生了同样的事情,这些事情发生在所有其他类似程序和类似问题中。