我正在做一個創建戰艦遊戲的項目。 我有以下類:將數據從GUI傳遞給Java中的另一個類
Battleship
(主類)Player
,Game
,Board
,Visualisation
(GUI類,其中我有一個的JButtons
),其中用戶按下想要插入船隻的JButton
。
首先創建一個新的Game
與一些參數,如板的大小。然後在課堂上Game
我做了一個新的Visualisation
。在這堂課內我已經完成了actionListener
和actionPerformed
。
我的問題是如何傳遞的信息,例如,其中JButton
我已經按下(插入在的單元格中的船)類Game
?這是我有:
Class Game
private Player _user;
private Player _computer;
然後,我要檢查的_user
董事會如果該位置可插入船。 _user.MethodOfClassPlayer();
Class Player
private int id;
private String name;
private Board _boardPlayer
Class Board
private int size;
private int[][] _board = null ;
功能的actionPerformed
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < tUsuariCPU.length; i++){
for (int j = 0; j < tUsuariCPU[i].length; j++){
if (e.getSource() == tUsuariCPU[i][j]){
buttonPressedUser(i,j);
JButton temp = (JButton) e.getSource() ;
temp.setBackground(java.awt.Color.ORANGE);
}
我想通過將JButton的信息壓到遊戲類知道,如果該玩家該位置是否可用的把船。如果它是可用的,所以我會畫JButton 我希望你能理解我。
我建議你通過戰艦類在GUI的構造,並保持對它的引用內勾起來作爲GUI名爲parent的一個字段:GUI(Battleship parent)和this.parent = parent。當單擊一個按鈕時,您可以通過執行main類中的函數來執行該函數:parent.myfunction() – Dien
您可以在構造函數中使用參數傳遞某些數據,也可以使Visualization類成爲一個帶有返回值的對話框函數,當你點擊一個按鈕時,它將一個數組中的「x和y」保存在一個數組中,並將它返回到它在被處理後調用的主類中 – DoubleMa
你能澄清你的意思嗎?這樣。你有沒有連接到按鈕的動作?你可以添加該代碼嗎? – ChiefTwoPencils