2

I'm in the process of writing a game. The game plays background music while it is running. This works fine, and I've decided to add a main menu, as their are three types of this game:

  • Single Player

  • Two Player

  • Online

When I run these classes individually (which have their own main methods - obviously), they work perfectly fine. However, in my Welcome Menu class, which is responsible for the main menu (all necessary imports are there, just not shown here):

public class WelcomeMenu implements ActionListener {

public void setButtonBG(JButton button, String imgPath) throws IOException //this method is reponsible for setting images to their corresponding JButton(s)
{
    BufferedImage img = ImageIO.read(ClassLoader.getSystemResource(imgPath));
    ImageIcon sp = new ImageIcon(img);
    button.setIcon(sp);
    button.setBorderPainted(false);
}


private JFrame welcomeWindow = new JFrame("Tic-Tac-Toe");
private JButton singlePlayerButton = new JButton();
private JButton twoPlayerButton = new JButton();
private JButton onlineButton = new JButton();
public WelcomeMenu() throws IOException
{
    //START OF CONSTRUCTOR
    //Main window is being sized, default way to close, and internal layout
    welcomeWindow.setSize(600, 420);
    welcomeWindow.setLayout(new CardLayout());
    //Object res = this.getClass().getResource("/");
    //System.out.println(res);
    BufferedImage bf = ImageIO.read(ClassLoader.getSystemResource("images/mainMenuBG.jpg"));
    welcomeWindow.setContentPane(new backImage(bf)); // adding created component to the JFrame using the backImage class
    welcomeWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    welcomeWindow.setLocationRelativeTo(null);
    welcomeWindow.setResizable(false);
    welcomeWindow.setVisible(true);

    //setting the icon
    try
    {
        java.net.URL url = ClassLoader.getSystemResource("images/icon.png");
        Toolkit kit = Toolkit.getDefaultToolkit();
        Image img = kit.createImage(url);
        welcomeWindow.setIconImage(img);
    }
    catch(NullPointerException n)
    {
        System.out.println("Image could not be fetched.");
    }

    //adding custom buttons

    //ImageIcon singlePlayer = new ImageIcon("images/singlePlayerButton.jpg");

    //setting sizes
    singlePlayerButton.setSize(387, 72);
    twoPlayerButton.setSize(387, 72);
    onlineButton.setSize(387, 72);

    //setting background images to buttons
    setButtonBG(singlePlayerButton, "images/sPlayerButton.jpg");
    setButtonBG(twoPlayerButton, "images/tPlayerButton.jpg");
    setButtonBG(onlineButton, "images/mPlayerButton.jpg");

    //adding listeners
    singlePlayerButton.addActionListener(this);
    twoPlayerButton.addActionListener(this);
    onlineButton.addActionListener(this);

    //adding the custom buttons
    welcomeWindow.add(singlePlayerButton);
    welcomeWindow.add(twoPlayerButton);
    welcomeWindow.add(onlineButton);

    //setting locations and visibility
    singlePlayerButton.setLocation(110, 90);
    singlePlayerButton.setVisible(true);

    twoPlayerButton.setLocation(110, 182);
    twoPlayerButton.setVisible(true);

    onlineButton.setLocation(110, 274);
    onlineButton.setVisible(true);

    //END OF CONSTRUCTOR
}
public static TicTacToeTP spg;
//All actions are done here
@Override
public void actionPerformed(ActionEvent e) 
{
    if(e.getSource() == singlePlayerButton)
    {
        System.out.println("<LOG> SINGLE PLAYER GAME REQUESTED");
        JOptionPane.showMessageDialog(welcomeWindow, "This game mode has not been implemented yet.");
    }
    if(e.getSource() == twoPlayerButton)
    {
        System.out.println("<LOG> TWO PLAYER GAME REQUESTED");

        try
        {
            //spg = new TicTacToeTP("images/black-squareMod_RED.jpg");
            //spg.playBackgroundSong();
            TicTacToeTP.main(null);

        }
        catch(IOException io)
        {
            System.out.println("IO EXCEPTION!");
        }

        welcomeWindow.setVisible(false);
        welcomeWindow.dispose(); 
    }
    if(e.getSource() == onlineButton)
    {
        System.out.println("<LOG> ONLINE GAME REQUESTED");
        JOptionPane.showMessageDialog(welcomeWindow, "This game mode has not been implemented yet.");
    }



}

public static void main(String[] args) throws IOException
{
    EventQueue.invokeLater(new Runnable() 
            {
            @Override
            public void run() 
            {
               try
               {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
               }
               catch(ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex)
               {

               }
            }
            });
    new WelcomeMenu();

}


}

... if I click the Two Player button, for example, it plays the audio ONLY. None of my other components load. Just an empty JFrame. Notice how in the actionPerformed() method, I tried both TicTacToeTP.main(null) and (commented out, now) instantiating a new TicTacToeTP object AND calling the playBackgroundSong() method. If I eliminate this methods call, and just instantiate the object, it works fine - but no music.

Why is this happening, and how can I fix it?

Here is the playBackgroundSong() method:

private Player p = null;
    //private InputStream fis = null;
    public void playBackgroundSong() //responsible for playing background music
    {
       //PausablePlayer p = null;
       InputStream fis = null;
       ArrayList<InputStream> stream = new ArrayList<InputStream>(); //this ArrayList contains multiple audio files that the method will loop through >> defined below

       stream.add(ClassLoader.getSystemResourceAsStream("resources/01 Intro.mp3"));
       stream.add(ClassLoader.getSystemResourceAsStream("resources/Basic space - The XX - Instrumental.mp3"));
       stream.add(ClassLoader.getSystemResourceAsStream("resources/Mirrors [ Upbeat Electronic Instrumental ] Spence Mills HQ Free Beat Download 2012.mp3"));
       stream.add(ClassLoader.getSystemResourceAsStream("resources/Static [ Aggressive Dark Pop Hip Hop Rap Instrumental ] Spence Mills Free Beat Download Link 2012 HD.mp3"));
       stream.add(ClassLoader.getSystemResourceAsStream("resources/System Shock 2 soundtrack Med Sci 1.mp3"));
       stream.add(ClassLoader.getSystemResourceAsStream("resources/System Shock 2 Soundtrack Ops 2.mp3"));
       stream.add(ClassLoader.getSystemResourceAsStream("resources/01 Intro.mp3"));

       Collections.shuffle(stream);

       for(int i = 0; i < stream.size(); i++)
       {
            try 
            {
                fis = stream.get(i);
            } 
            catch (NullPointerException ex) 
            {
                Logger.getLogger(TicTacToeTP.class.getName()).log(Level.SEVERE, null, ex);
            }
            try 
            {
                p = new Player(fis);
            } 
            catch (JavaLayerException ex) 
            {
                Logger.getLogger(TicTacToeTP.class.getName()).log(Level.SEVERE, null, ex);
            }
            try 
            {
                p.play();
            } 
            catch (JavaLayerException ee) 
            {
                Logger.getLogger(TicTacToeTP.class.getName()).log(Level.SEVERE, null, ee);
            } 


       }
       playBackgroundSong();
    }
4

1 回答 1

3

playBackgroundSong()您似乎在 Swing 事件调度线程或 EDT 上播放一段长时间运行的代码。该线程负责绘制 GUI 以及交互和响应用户输入,如果它被占用,程序基本上会冻结。当您在 main 方法中调用此方法时,这可能不是问题 - 基本上是在 Swing 事件线程之外,但是当它在事件调度线程上专门调用时会出现问题。一个可能的解决方案:在后台线程中播放音乐。SwingWorker 可能适合您,并且有关于使用这些和 EDT 的不错的教程。谷歌“ Concurrency in Swing ”,看看什么可能是第一个热门。

顺便说一句:您通常不想调用另一个类的 main 方法。而是创建另一个类的实例并使用它。


编辑你状态:

谢谢。看这部分:docs.oracle.com/javase/tutorial/uiswing/concurrency/simple.html 似乎解释了我想要做什么,对吗?顺便说一句,我正在阅读所有内容

其实你可以更简单。由于您不等待来自您的结果playBackgroundSong(),因此您可能只需将其包装在 Runnable 中,然后将其放入线程中即可在其自己的简单线程中调用它:

new Thread(new Runnable() {
  public void run() {
    playBackgroundSong();
  }
}).start();
于 2013-05-17T23:45:56.910 回答