Java swing卡游戏错误

时间:2014-01-08 18:30:34

标签: java multithreading swing jpanel

我正在为一项任务制作一个Java纸牌游戏,我遇到了一个问题。

以下代码位于不同的类别中。

cgp class。

private DisplayableDeck deck = new DisplayableDeck("b1fv.png");
DisplayableCard[] cards = new DisplayableCard[10];
private Thread[] theThreads = new Thread[2];
private int[] players = new int[2];
private Deck D = new Deck();
int count = 0;
Graphics g;

CardGamePanel()
{
    D.buildDeck();
    for(int i=0;i<cards.length;i++)
    {
        Random r = new Random();
        int num1 =r.nextInt(52);                       
        cards[i] = new DisplayableCard("1.png",30,30);            
    }
}

 public void go()
{

  if(count < 9 )
  {
      cards[count].display(g); //error here
  }

  count ++;
}

简单类扩展了japplet

 private CardGamePanel cgp;
private JButton btnD = new JButton("Flip");
private Thread repaintThread;


public void init()
{
    cgp = new CardGamePanel();
    JPanel panel2 = new JPanel();
    panel2.add(btnD);
    btnD.addActionListener(new ActionListener()
    {

        public void actionPerformed(ActionEvent e)
        {
            cgp.go();
        }
    });
    add(cgp, BorderLayout.CENTER);
    add(panel2, BorderLayout.SOUTH);
    setSize(500,500);
}

-

public class DisplayableCard extends Card implements Displayable {  
public int x,y;
private Image image;
private String imageFilename = "";

public DisplayableCard(String s,int x,int y) {
    imageFilename = s;
    this.x =x;
    this.y=y;
}

public void display(Graphics g) {
    image = new ImageIcon(getClass().getResource(imageFilename)).getImage();
    g.drawImage(image, x, y, null); //ERROR HERE
}

当我单击按钮并调用go()方法时,游戏会抛出错误。

错误

Exception in thread "AWT-EventQueue-1"
java.lang.NullPointerException
 at DisplayableCard.display(DisplayableCard.java:16)
 at CardGamePanel.go(CardGamePanel.java:31)
 at simple$1.actionPerformed(simple.java:24)

我写了代码中出现错误的地方。

不确定哪个部分是错的:s非常感谢任何帮助:)

1 个答案:

答案 0 :(得分:0)

您应该获得一个现有的Graphic对象。你可以从JLabel那里得到一个:

public void init(){
cgp = new CardGamePanel();
JPanel panel2 = new JPanel();
panel2.add(btnD);
btnD.addActionListener(new ActionListener(){

    public void actionPerformed(ActionEvent e){
        cgp.go(panel2.getGraphics());
    }
});
  add(cgp, BorderLayout.CENTER);
  add(panel2, BorderLayout.SOUTH);
  setSize(500,500);
}

并在CardGamePanel类中修改您的其他方法:

public void go(Graphic gr){
  if(count < 9 ){
    cards[count].display(gr); 
  }
  count ++;
}

但我认为这对您没有帮助,因为您应该将卡放在顶级容器或顶级容器中的JComponent中。 如果您想了解有关此次点击的更多信息here,这是一个教程。我希望它能帮助你理解。