我确切知道导致问题的是哪一行,但是没有显示堆栈跟踪错误,所以我留下了调试。让我感到困惑的是,我认为小组没有焦点。首次打开时,面板是空白的,而不是绘制的,但是当我最小化并恢复时,面板会被绘制。我尝试将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());
}
}
答案 0 :(得分:0)
只想专门化UI(外观)委托的paint方法的子类应该覆盖paintComponent。
无论如何,即使在这种状态下,你的应用程序也会从一开始就向我展示绿色背景框架。