首页 > 解决方案 > showMessageDialog 不会在游戏中关闭

问题描述

在我的游戏中,当你点击移动的椭圆时你应该获得积分,如果你错过它们就会失去积分。当获得一个点时,会弹出一个消息对话框,说明您有多少点。我无法关闭它,因为它会将我的点击视为未点击。它会减少积分,直到游戏结束。

public void mousePressed(MouseEvent e){
    while (lives > 0) {
        if (oval1.contains(e.getX(), e.getY()) || oval2.contains(e.getX(), e.getY())){
            lives = lives + y;
            JOptionPane.showMessageDialog(null, lives + " points");
        }
        else {
            lives = lives - y;
            JOptionPane.showMessageDialog(null, lives + " points");
        }

        if (lives == -1)
            Input = JOptionPane.showInputDialog(" Would you like to reset?");
        if (Input.equalsIgnoreCase("yes"))
            lives = 3;
        continue;

标签: java

解决方案


您可以使用 makeThread.sleep()并在一段时间后自动消失对话框。

代码:

public void mousePressed(MouseEvent e)
{
    while (lives > 0) {
        if (oval1.contains(e.getX(), e.getY()) || oval2.contains(e.getX(), e.getY()))
        {
            lives = lives + y;
            showLives();
        }
        else 
        {
            lives = lives - y;
            showLives();
        }

        if (lives == -1)
            Input = JOptionPane.showInputDialog(" Would you like to reset?");
        if (Input.equalsIgnoreCase("yes"))
            lives = 3;
        continue;
    }
}

public void showLives()
{
    JOptionPane message = new JOptionPane("Points: " + lives, JOptionPane.INFORMATION_MESSAGE, JOptionPane.DEFAULT_OPTION, null, new Object[]{});  //no buttons will be created
    final JDialog dialog = message.createDialog("Information");
    new Thread(new Runnable()
            {
                public void run()
                {
                    try
                    {
                        Thread.sleep(1500);  // this controls for how long you want the dialog to appear
                        dialog.dispose();
                    }
                    catch ( Throwable t )
                    {}
                }
            }).start();
  dialog.setVisible(true);
}

注意:我做了showLives()每次调用这个方法都会弹出lives并消失。所以,无需点击关闭。


推荐阅读