Reputation: 55
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. Any help would be appreciated.
Upvotes: 0
Views: 218
Reputation: 324187
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()
Upvotes: 3