Java 如何将值从一个类传递到另一个类GUI
我是JAVA编程新手,但如何将变量/值从一个类A传递到第二个类B,其中B是我的GUI,A是显示播放器的逻辑?我需要在GUI中将玩家名称打印到lblPlayer标签 A类:Java 如何将值从一个类传递到另一个类GUI,java,user-interface,Java,User Interface,我是JAVA编程新手,但如何将变量/值从一个类A传递到第二个类B,其中B是我的GUI,A是显示播放器的逻辑?我需要在GUI中将玩家名称打印到lblPlayer标签 A类: package driverPkg; import game.Card; import game.CardsUI; import game.players.CardPlayer; public class GameConsole implements CardsUI {
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类(图形用户界面)
感谢您的帮助我想玩家类是您的业务目标。将PropertyChangeSupport添加到此类,让CardsGameGUI实现PropertyChangeListener并将其作为侦听器添加到player实例。每次您在控制台中更改某些内容时,播放机都会触发属性更改事件,您可以在gui中进行监听和响应。这是一个简单的观察者模式
这里可以找到一个简单的例子:make B创建A的实例,on every paint获得它的statesure,但是我知道怎么做吗:(我在循环中编辑了我的代码。但是我仍然知道如何实现您的解决方案:(我只需要简单地将值从一个类传递到另一个类。我仍然不确定,但我认为您希望从GameConsole控制帧的内容,不是吗?您可以将主方法移动到GameConsole。该类打开CardsGameUI,并将每个playeras的帧注册为侦听器。
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