Domanda

I'm doing a basic Pong game for a class. I have the Pong working, and I have a GUI display on startup, unfortunately I can't seem to start the game from the start JButton. I've commented where the problem is on the code, and removed irrelevant code.

 frame.add(GUIPanel);
        JButton startButton = new JButton("Start!");     
        GUIPanel.add(startButton, BorderLayout.CENTER);
        startButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
         { 
             frame.getContentPane().remove(GUIPanel);
             frame.validate();
             frame.repaint();

             drawPanel = new DrawPanel();
             drawPanel.requestFocus();
             frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
              //This is the part that freezes it, everything else works fine
              //except that the playGame method isn't called. If I remove the whole
              //startButton and whatnot I can call playGame and it works perfectly.                                                                                    
              playGame();          
           }
         }); 
         }

any ideas?

È stato utile?

Soluzione

Swing is a single threaded framework.

That is, all interactions and modifications to the UI are to be made from within the context of the Event Dispatching Thread. Anything that blocks this thread will prevent it from processing, amongst other things, repaint requests and user input/interactions.

My guess is that playGame is using something like Thread.sleep or some kind of while(true) and is blocking the EDT, causing your program to appear as if it's frozen

Have a read through Concurrency in Swing for more details.

A simple solution would be to use a Swing Timer to act as you game loop. Each time it ticks, you would update the state of your game and call (something like) repaint on you game's component

Altri suggerimenti

It looks like you've got a parenthesis that doesn't belong next to your second to last semicolon. Try removing it.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top