简体   繁体   English

在showConfirmDialog之后关闭背景JFrame

[英]Closing background JFrame after showConfirmDialog

I am trying to write a very simple Blackjack game. 我正在尝试编写一个非常简单的二十一点游戏。

This is the class that is supposed to show the currently drawn card: 这是应该显示当前绘制的卡片的类:

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

public class ShowRandomCard {
    JFrame f = new JFrame();
    JPanel p = new JPanel();

public void ShowUsARandomCard() {
    f.setLayout(new BorderLayout());
    p.add(new JLabel("A Panel"));
    f.add(p, BorderLayout.NORTH);

    // Picture
    BufferedImage myPicture = null;
    try {
        myPicture = ImageIO.read(new File("somepicture"));
    } catch (IOException e) {
        e.printStackTrace();
    }
    JLabel picLabel = new JLabel(new ImageIcon(myPicture));
    f.add(picLabel,BorderLayout.NORTH);

    // elements

    f.pack();
    f.setVisible(true);

    Blackjack jt = new Blackjack();
    jt.dialog();

}

public void hideCards() {
    f.setVisible(false);
    f.remove(p);
    f.dispose();
    f.repaint();
}
}

And this is the actual game class: 这是实际的游戏类:

import static javax.swing.JOptionPane.*;

public class Blackjack {

    ShowRandomCard it = new ShowRandomCard();

   public void dialog() {

        int answer2 = showConfirmDialog(null, "some message", "some title",
                YES_NO_OPTION);
        if (answer2 == YES_OPTION) {
            garbageCollection();
            it.ShowUsARandomCard();
        if (answer2 == NO_OPTION || answer2 == CANCEL_OPTION) {
            garbageCollection();
        //  System.exit(0);
        }
        }
   }

public void garbageCollection() {
    it.hideCards();
}
 }

But the JPanel that holds the cards does not disappear. 但是保存卡的JPanel不会消失。 Any help would be appreciated. 任何帮助,将不胜感激。

When you remove a component from a visible frame the basic code is: 当您从可见框架中删除组件时,基本代码为:

panel.remove(...);
panel.revalidate();
panel.repaint();

However, there is rarely a good reason to use code like that. 但是,很少有理由使用这样的代码。 Instead you should be using a Card Layout to hide/show panels. 相反,您应该使用卡片布局来隐藏/显示面板。

Method names do not start with an upper case character. 方法名称不能以大写字母开头。 "GarbageCollection()" should be GarbageCollection() “ GarbageCollection()”应为GarbageCollection()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM