大家好,我是新來的,我是Java新手。我正在編寫一個可以玩一場戰爭遊戲的程序,並在圖形面板上顯示遊戲。我在調用War類中Card類的繪製方法時遇到了問題。例如,當試圖使用drawSpade時,我得到錯誤「無法對來自類型卡片的非靜態方法drawSpade(Graphics,int,int)進行靜態引用」。我知道有很多關於這個錯誤的帖子,但我很難理解爲什麼它在我的程序中發生,以及如何解決它。任何幫助或建議都會很棒。謝謝!試圖從另一個類中調用方法
public class War extends JFrame
{
private int card;
private int drawNum;
public int drawSuit;
private final int xA = 225;
private final int yA = 50;
public War()
{
Color tableGreen = new Color(50, 150, 50);
setBackground(tableGreen); // Sets background color
setSize(800,500); // Sets window size
setTitle("War"); // Sets window title
setLocation(50,50); // Sets where the window appears
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); // Makes the window appear
}
int myCard()
{
Random myCard = new Random();
return myCard.nextInt(13) + 1;
}
int mySuit()
{
Random mySuit = new Random();
return mySuit.nextInt(4) + 1;
}
int compCard()
{
Random compCard = new Random();
return compCard.nextInt(13) + 1;
}
int compSuit()
{
Random compSuit = new Random();
return compSuit.nextInt(4) + 1;
}
public void cardNum()
{
if (myCard() == 1)
{
drawNum = 1;
}
}
public void cardSuit()
{
if (mySuit() == 1)
{
drawSuit = 1;
}
}
public void paint (Graphics pane)
{
drawSuit = 1;
drawNum = 1;
if (drawNum == 1)
Card.drawBlank(pane, xA, yA);
Card.drawTwo(pane, xA, yA);
if (drawSuit == 1)
Card.drawSpade(pane, 75, 100);
}
public int getDrawSuit()
{
return drawSuit;
}
}
public class Card
{
private static final int HEIGHT = 200;
private static final int WIDTH = 150;
private final int xA = 225;
private final int yA = 50;
public void drawBlank (Graphics pane, int xA, int yA)
{
pane.setColor(Color.black);
pane.drawRoundRect(xA, yA, WIDTH, HEIGHT, 20, 20);
pane.setColor(Color.white);
pane.fillRoundRect(xA + 1, yA + 1, WIDTH - 1, HEIGHT - 1, 20, 20);
}
public void drawSpade (Graphics pane, int xA, int yA)
{
pane.setColor(Color.black);
Polygon triangle;
triangle = new Polygon();
triangle.addPoint(xA + WIDTH + WIDTH/2, yA + HEIGHT/5);
triangle.addPoint(xA + WIDTH + WIDTH/2 + 5, yA + HEIGHT/3);
triangle.addPoint(xA + WIDTH + WIDTH/2 - 5, yA + HEIGHT/3);
pane.fillPolygon(triangle);
pane.drawOval(xA + WIDTH + WIDTH/2, yA + HEIGHT/5, 20, 20);
pane.fillOval(xA + WIDTH + WIDTH/2, yA + HEIGHT/5, 20, 20);
pane.drawOval(xA + WIDTH + WIDTH/2 - 20, yA + HEIGHT/5, 20, 20);
pane.fillOval(xA + WIDTH + WIDTH/2 - 20, yA + HEIGHT/5, 20, 20);
pane.drawOval(xA + WIDTH + WIDTH/2 - 10, yA + HEIGHT/5 - 15, 20, 20);
pane.fillOval(xA + WIDTH + WIDTH/2 - 10, yA + HEIGHT/5 - 15, 20, 20);
}
/**
* Numbers
*/
public void drawTwo (Graphics pane, int xA, int yA)
{
if (getDrawSuit() == 1 || getDrawSuit() == 2)
pane.setColor(Color.black);
else
pane.setColor(Color.red);
pane.drawString("2", xA, yA);
}
public int getDrawSuit()
{
return getDrawSuit();
}
}
我在您發佈的代碼中沒有看到'drawSpade()'的靜態調用。你是否也從別的地方打電話給它? 'Card'級在哪裏? – 2014-10-29 03:22:48