2013-02-27 58 views
-2

我在Java中創建了一個遊戲,並且我有一個帶有按鈕的主菜單,我需要某種方式來返回按下的按鈕,以便我可以在不同的類中使用它。我不知道該怎麼做。有人有什麼主意嗎?爪哇迴歸按鈕

我在actionPerformed方法中使用e.getSource()獲得按鈕。 我試着返回按鈕,但沒有奏效。

非常感謝。

下面是一些代碼:

菜單類

public void actionPerformed(ActionEvent e) { 
    Object button = e.getSource(); 
    return button 
} 

其他類

public static void createGameScreen() { 
    if(Menu.button == Menu.button1) { 
     // do something here 
    } 
} 
+1

哪裏碼?另一個想法是使用某種事件總線。 – 2013-02-27 15:19:05

+0

傳遞整個按鈕對象是坦率而浪費的。傳遞一個代表按鈕的整數不是更好嗎? – christopher 2013-02-27 15:24:34

回答

1

你不會這麼多的回報哪個按鈕被按下,而是分配代碼的行動(或者至少這是我如何解釋你的問題)。爲那個按鈕分配一個這樣的監聽器。我更喜歡這樣做。可能有更好的方法。

button.addActionListener(new java.awt.event.ActionListener() { 
    public void actionPerformed(java.awt.event.ActionEvent e) { 
     buttonBoardActionPerformed(e); 
    } 
}); 


public void buttonActionPerformed(ActionEvent e) { 
    // Do some stuff 
} 

基本上你直接鏈接按鈕的動作,而不是整個事情分配一個單獨的監聽器。更容易調試IMO。也請閱讀THIS TUTORIAL

0

對於您鍵入的內容,我覺得你寫的東西,如:

buttonProcess = new JButton("Process"); 
buttonProcess.set//bounds,actionlistener,etc. 
if (e.getSource().equals(buttonProcess)){ 
//do some stuff 
return buttonProcess; 
} 

您可以嘗試使用類UI的在輔助classor定義一個靜態變量。

e.g:

public class AuxClass{ 
public static Object PROCESS_BUTTON; //YOu can replace Object by Component or JButton 
} 

//then in your first UI code 
if (e.getSource().equals(buttonProcess)){ 
    AuxClass.PROCESS_BUTTON = buttonProcess; 
    } 

//then in your other UI: 
if (AuxClass.PROCESS_BUTTON !null && AuxClass.PROCESS_BUTTON instanceof JButton){ 
//Do what you want here 
} 
+0

做這個工作,如果我的課程在不同的包裝? – user1976336 2013-02-27 16:57:23

+0

是的,這並不重要,因爲你的變量是靜態的並且是公共的,這是沒有問題的,無論你在什麼軟件包中都可以使用它。 – 2013-02-27 23:37:04