I know exactly what line is causing the problem, but there are no stack trace errors being shown, so I'm left with debugging. The problem that has got me is that I thought the panel didn't have focus. When first opened, the panel is blank, and not drawn, but when I minimize and restore, the panel gets painted. I tried adding panel.requestFocus()
and panel.requestFocusInWindow()
to the constructor of the class that is being initialized before the screen is painted, but it doesn't seem to do anything. Here is the code:
JPanel class:
package blackjack;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class Board extends JPanel {
int dealer = 0;
int player = 0;
int money = 2500;
Deck deck;
Player p = new Player();
public Board() {
deck = new Deck(false, this); //if I comment this out, the panel gets painted straight away
}
public void paint(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillRect(0,0,getWidth(),getHeight());
repaint();
}
}
And the class that is causing the problem:
package blackjack;
import java.awt.Image;
import java.util.Random;
import javax.swing.ImageIcon;
public class Deck {
Card[] deck = new Card[52];
int[] used = new int[52];
Random r = new Random();
public Deck(boolean shuffle, Board b) {
int i = 0;
for(int x=0; x<51; x++) {
used[x] = -1;
}
for(Cards card : Cards.values()) {
if(card.getId() != 53) {
Image image = new ImageIcon(this.getClass().getResource(card.getImagePath())).getImage();
deck[i] = new Card(card.getId(),card.getValue(),image);
i = i+1;
}
}
if(shuffle) shuffle();
b.requestFocus();
b.requestFocusInWindow();
}
public void shuffle() {
Card[] shuffled = new Card[52];
for(int x=0; x<51; x++) {
int i = pickNotUsed();
if(i==-1) break;
shuffled[x] = deck[i];
}
deck = shuffled;
}
private int pickNotUsed() {
int notpicked = r.nextInt(52);
for(int x=0; x<51; x++) {
if(used[x] != notpicked) {
return notpicked;
}
}
return -1;
}
public Card[] getCards() {
return deck;
}
public Card drawCard() {
for(int x=0; x<deck.length; x++) {
if(deck[x] != null) {
return deck[x];
}
}
return null;
}
}
original class, extends JFrame package blackjack;
import javax.swing.JFrame;
@SuppressWarnings("serial")
public class Blackjack extends JFrame {
public static void main(String[] args) {
new Blackjack();
}
public Blackjack() {
setSize(1000,600);
setTitle("Blackjack");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
add(new Board());
}
}
A subclass that just wants to specialize the UI (look and feel) delegate's paint method should just override paintComponent.
Anyway, even in this state you application shows me the green background frame from the start.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.