showMessageDialog将不会在游戏中关闭

时间:2019-04-09 20:48:22

标签: java

在我的游戏中,当您单击移动的椭圆形时,您应该获得积分,而如果错过椭圆形,则会失去积分。当获得一个点时,会弹出一个对话框,提示您有多少个点。我无法关闭它,因为它会将我的点击视为未点击。它会减少点数直到游戏结束。

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;

1 个答案:

答案 0 :(得分:-1)

您可以使用Thread.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并消失。因此,无需单击即可关闭。