2013-12-11 299 views
0

我是JAVA編程新手,但是如何將變量/值從一個類A傳遞給seconnd類B,其中B是我的GUI,A是邏輯來顯示玩家?我需要在GUI中將播放器名稱打印到lblPlayer標籤。如何將值從一個類傳遞到另一個類GUI

A類:

package driverPkg; 

    import game.Card; 
    import game.CardsUI; 
    import game.players.CardPlayer; 


    public class GameConsole implements CardsUI { 


     public void currentCard(CardPlayer[] player) { 


      for (CardPlayer p : player) { 
      // here somehow return p.getName() and pass to the GUI 
      } 
     } 
....more code not really need it 

B類(GUI)

public class CardsGameGUI extends JFrame { 

    private JPanel contentPane; 


    /** 
    * Launch the application. 
    */ 
    public static void main(String[] args) { 
     EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       try { 
        CardsGameGUI frame = new CardsGameGUI(); 
        frame.setVisible(true); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 
    } 

    /** 
    * Create the frame. 
    */ 
    public CardsGameGUI() { 
     setFont(new Font("Arial", Font.PLAIN, 26)); 
     setResizable(false); 
     setTitle("Card Game"); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setBounds(100, 100, 828, 556); 
     contentPane = new JPanel(); 
     contentPane.setBackground(new Color(102, 153, 153)); 
     contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); 
     setContentPane(contentPane); 
     contentPane.setLayout(null); 


      JLabel lblPlayer = new JLabel("");//here i need to bring the players name 
     lblPlayer.setFont(new Font("Arial One", Font.PLAIN, 13)); 
     lblPlayer.setBounds(6, 11, 49, 16); 
     panel.add(lblPlayer); 

...more code below not need it now 

感謝您的幫助

+0

化妝B到創建一個實例和每個塗料獲得其狀態 – Gustavo

+0

肯定,但任何想法,我該怎麼辦呢:( – medzi

回答

0

我猜Player類是你的businness對象。將PropertyChangeSupport添加到此類,讓CardsGameGUI實現PropertyChangeListener並將其作爲偵聽器添加到播放器實例中。每當你改變控制檯中的某些東西時,玩家就會觸發財產變化事件,並且你可以在gui中聽取並作出反應。這是一個簡單的觀察者模式。

一個簡單的例子可以在這裏找到:http://examples.javacodegeeks.com/core-java/beans/bean-property-change-event-listener/

+0

我修改了代碼在循環中,但我仍然知道如何實現你的解決方案:(我只需要簡單地將值從一個類傳遞給另一個。) – medzi

+0

我仍然不確定,但我認爲你想控制框架的內容GameConsole,不是嗎?您可以將主要方法移動到GameConsole。此類打開CardsGameUI併爲每個playeras一個監聽器註冊幀。 – Spindizzy

相關問題