JButton没有在我的JFrame中绘制。 JFrame在while循环中

时间:2011-11-22 00:59:42

标签: java swing jframe jbutton

我正在尝试创建某种类型的鼹鼠游戏,并且我在while循环中设置了一个JFrame,所以它会在每秒创建一个新的JFrame,但问题是我的JButton在这个过程中不会加载。这是我的代码:

import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class WACKAMOLE {
private static JFrame frame;
private static JFrame frame1;
private static JButton button1;
private static int a;
private static int b;
private static int x = 0;
private static int score=0;

    public static void main(String args[]){
    Menu n=new Menu();
    n.Start();

}

static class Menu{

       public void Start(){
    frame=new JFrame();
    frame.setSize(150, 150);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.setLocationRelativeTo(null);
    JPanel panel=new JPanel();
    JLabel label=new JLabel("Main Menu");
    JLabel label1=new JLabel("WACK A MOLE DELUXE");
    JButton button=new JButton("Start");
    JButton button1=new JButton("Highscores");
    panel.add(label1);
    panel.add(label);
    panel.add(button);
    panel.add(button1);
    frame.add(panel);
    frame.setVisible(true);
    button.addActionListener(new game());
    }
}

static class game implements ActionListener{
    public void actionPerformed(ActionEvent e){
        frame.dispose();
        Random generator=new Random();
        Random generator1=new Random();
        while(x<=30){
        a=generator.nextInt(1000);
        b=generator1.nextInt(1000);
        frame1=new JFrame("HEHE");
        frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame1.setSize(100,100);
        frame1.setLocation(a,b);
        frame1.setResizable(false);
        button1=new JButton("WACK ME!");
        button1.addActionListener(new clicked());
        frame1.setVisible(true);
        frame1.add(button1);
        frame1.setVisible(true);

        try{Thread.sleep(900);}
        catch(Exception e1){System.out.println("ERROR");}

        frame1.dispose();
        x++;
        }

    }

    static class clicked implements ActionListener{
        public void actionPerformed(ActionEvent e){
            frame1.dispose();
            x++;
            score++;

        }
    }

}

 }

1 个答案:

答案 0 :(得分:3)

如果使事件调度线程处于休眠状态,则会阻止所有GUI事件和绘图。你需要使用后台线程来休眠,然后从后台线程中触发在EDT中处理帧。

阅读tutorial about concurrency in Swing