Java - 暂停一个方法?

时间:2014-07-13 17:37:43

标签: java sleep

我的一个菜单只是一个图像,一个按钮可以回来。' 问题是,后退按钮总是在图像之前加载,即使它在代码之后。

有什么方法可以解决这个问题吗?我对编程很陌生,所以我能想到的最好方法是以某种方式暂停方法,比如3秒钟,当图片加载时,然后加载后退按钮。

我尝试过使用thread.sleep(3000),但如果我这样做,那么图像根本不会加载!也许我使用它错了?

public void render(Graphics g){

 if(Instscrn==true){
        g.drawImage(InstructionScreen, 0, 0, Resources.sp);

        if(instclose){
            g.setFont(new Font("Arial", Font.PLAIN, 30)); 
            g.setColor(Color.BLACK);
            g.drawString("Back", 672, 552);
        }

使用thread.sleep

public void render(Graphics g){

 if(Instscrn==true){
        g.drawImage(InstructionScreen, 0, 0, Resources.sp);

       try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if(instclose){
            g.setFont(new Font("Arial", Font.PLAIN, 30)); 
            g.setColor(Color.BLACK);
            g.drawString("Back", 672, 552);
        }

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您可以在渲染(图形g)上加载图像而不会暂停任何方法:

boolean inited = false;
Image i;
public void render(Graphics g){
    if(!inited) {
        //here, init your image, for example: download files from web or load resources
        try {
            i = ImageIO.read(new File(""));//loading image
        } catch (IOException e) {
            e.printStackTrace();//error
        } 
        inited=true;
    }
    g.drawImage...
}

您无法暂停某个方法,但可以暂停一个主题(使用方法):

public static void main(String[] args) throws InterruptedException {
    final Thread pauseable = new Thread("Pauseable method/thread") {
        //Pauseable method
        public void run() {
            for(int i=0; i<20; i++) {
                System.out.println("Working");
                sleepMethod();
            }
        }
        //Sleep for 1 seconds
        public void sleepMethod() {
            try {
                sleep(1000);
            } catch(Throwable t){}
        }
    };
    pauseable.start();
    JFrame f = new JFrame();
    JButton pause = new JButton("Pause");
    JButton start = new JButton("Resume");
    pause.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent arg0) {
            try {
                pauseable.suspend();
            } catch(Throwable t) {
                t.printStackTrace();
            }
        }});
    start.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent arg0) {
            try {
                pauseable.resume();
            } catch(Throwable t) {
                t.printStackTrace();
            }
        }});

    //STYLE OF BUTTONS ETC.:
    JPanel p = new JPanel(new GridLayout(1,2));
    p.add(pause);
    p.add(start);
    f.getContentPane().add(p);
    f.pack();
    f.setLocationRelativeTo(null);
    f.setVisible(true);


    pauseable.join(); //If you want wait to end of running method
    System.out.println("Method pauseable.run() was ended!");
}