我确切地知道是哪一行导致了问题,但是没有显示堆栈跟踪错误,所以我只剩下调试了。困扰我的问题是我认为面板没有焦点。第一次打开时,面板是空白的,没有绘制,但是当我最小化和恢复时,面板被绘制了。我尝试在绘制屏幕之前将panel.requestFocus()
和添加panel.requestFocusInWindow()
到正在初始化的类的构造函数中,但它似乎没有做任何事情。这是代码:
JPanel 类:
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();
}
}
导致问题的类:
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;
}
}
原始类,扩展JFrame包二十一点;
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());
}
}