0

我正在尝试编写一个非常简单的二十一点游戏。

这是应该显示当前绘制的卡片的类:

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();
}
}

这是实际的游戏类:

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();
}
 }

但是持有卡片的 JPanel 并没有消失。任何帮助,将不胜感激。

4

1 回答 1

3

当您从可见框架中删除组件时,基本代码是:

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

但是,很少有充分的理由使用这样的代码。相反,您应该使用卡片布局来隐藏/显示面板。

方法名称不以大写字符开头。“垃圾收集()”应该是GarbageCollection()

于 2013-04-26T17:46:35.463 回答