[英]How to pass value from one class to another class GUI
我是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 {
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
感謝您的幫助
我猜Player類是您的業務對象。 將PropertyChangeSupport添加到此類,讓CardsGameGUI實現PropertyChangeListener並將其作為偵聽器添加到播放器實例。 每次您在控制台中更改某些內容時,播放器都會觸發一個屬性更改事件,您可以在gui中進行監聽和做出反應。 這是一個簡單的觀察者模式。
一個簡單的例子可以在這里找到: http : //examples.javacodegeeks.com/core-java/beans/bean-property-change-event-listener/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.