如何将值从一个类传递到另一个类GUI

时间:2013-12-11 20:26:59

标签: java user-interface

我是JAVA编程的新手,但如何将变量/值从一个A类传递到seconnd B类,其中B是我的GUI,A是显示玩家的逻辑?我需要在GUI中将玩家名称打印到lblPlayer标签。

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

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

我猜Player类是你的业务对象。将PropertyChangeSupport添加到此类,让CardsGameGUI实现PropertyChangeListener并将其作为侦听器添加到播放器实例。每次你在控制台中改变某些东西时,玩家都会触发一个属性改变事件,你可以在gui中听取并做出反应。这是一个简单的观察者模式。

可在此处找到一个简单示例:http://examples.javacodegeeks.com/core-java/beans/bean-property-change-event-listener/