好吧,我正在用Java創建一個紙牌遊戲。讓我開始說我已經編寫了整個遊戲邏輯,包括所有的規則等,並且我已經開始在該模型之上實現GUI。我對Java和Swing的瞭解基本上與我一樣純粹。Java Swing:運行GUI從單獨的類方法更新方法
我有5個班,但我會談論的只是'主要'或遊戲類和'圖形用戶界面'類。首先,爲了構建手,我使用了我創建的對象類型< Card>的ArrayLists。遊戲通過玩'Play()'方法並且(目前)通過控制檯向他顯示人類玩家手,並要求他在ArrayList中進行整數選擇以放下。我在Main類中有main(String [] args),並且調用類GUI並設置我使用的遊戲板。
public static void main(String[] args)
{
Deck deck = new Deck();
ai = new AI;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
GUI gui = new GUI();
gui.setVisible(true);
}
})
我非常希望遊戲通過使用播放()方法和調用方法從GUI類既更新板和退卡的人類玩家選擇玩。此刻,我能做的最好的是,設立董事會時,我實現通過
Button go = new Button("Update Hand");
ButtonDisplay.add(go);
go.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
Thread queryThread = new Thread() {
public void run() {
UpdateHand();
}
};
queryThread.start();
}
});
點擊時,然後運行
public void UpdateHand()
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
inPlay = main.inPlay;
UpdateInPlay(inPlay, InPlayDisplay);
HumanHand = main.humanplayer;
HumanHandDisplay.removeAll();
,從而清除面板和重繪卡的JLabel背部的按鈕上。
我的問題是,我該如何在GUI類中製作Play()方法調用方法?當我嘗試從Play()方法運行UpdateHand()時,只需使用
gui.UpdateHand();
它返回一個NullPointerException在那個gui.UpdateHand()行,但仍然打印UpdateHand()方法內的變量到控制檯,當我告訴它,如ArrayList。正如我所說的,與其在gui上更新棋盤上的按鈕不同,我希望我的Play()方法在循環其順序時調用UpdateMethod,然後當玩家需要選擇卡時,改爲使用我現在使用的控制檯掃描儀時,運行一種方法,在板上添加一個文本字符和一個按鈕,供用戶輸入他們的選擇,然後返回到Play()方法繼續進行遊戲計算。
任何人都可以闡明我做錯了什麼,以及如何實現我在這裏指定的東西嗎?
編輯:
更多的我的代碼爲2類作爲請求
GUI
public class GUI extends JFrame
{
public Main main;
private ArrayList<Card> AIHand;
public GUI() {
pane = this.getContentPane();
pane.setLayout(new GridLayout(6,1,2,2));
AIBackDisplay = new JPanel();
//just more of the same for other panels here
pane.setBackground(Color.GREEN);
setTitle("Last Man Standing");
pane.add(AIBackDisplay);
pane.add(AIHandDisplay);
pane.add(InPlayDisplay);
pane.add(HumanHandDisplay);
pane.add(HumanBackDisplay);
pane.add(HumanFacedownDisplay);
pane.add(ButtonDisplay);
setSize(800, 700);
setLocationRelativeTo(pane);
setDefaultCloseOperation(EXIT_ON_CLOSE);
UpdateFacedown(AIFacedown, AIBackDisplay); //these are methods called for original display
UpdateFacedown(HumanFacedown, HumanBackDisplay);
然後我有經由按鈕稱爲updateHand()方法和執行此
for (int i = 0; i < (HumanHand.size()); i++)
{
Card card = HumanHand.get(i);
BufferedImage cardImage = null;
try {
cardImage = ImageIO.read(new File("card/" + card + ".jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JLabel picLabel = new JLabel(new ImageIcon(cardImage));
HumanHandDisplay.add(picLabel);
}
HumanHandDisplay.updateUI();
我的主類有
public class Main {
static AI ai;
public static GUI gui;
發現GUI必須是靜態的,否則使用
Scanner sc = new Scanner (System.in);
choice = sc.nextInt(); //what i'm using now
//choice = gui.GUIReturn(); //what i'd like to use
即使GUI是靜態的,我不能把它它不讓我跑GUI。GUIReturn()出於某種原因,說它必須是靜態的
構建一個[sscce](http://sscce.org/)可能是一個有用的練習。 – trashgod 2012-04-07 03:49:58
請學習java命名約定並堅持使用它們。 – kleopatra 2012-04-07 09:11:19