簡體   English   中英

從另一個類向JFrame添加對象?

[英]Adding Objects to JFrame from another class?

我正在嘗試為Java的最終項目創建一個二十一點程序。 我對Java和OOD還是很陌生,所以如果您的問題對我來說很微不足道,我深表歉意:(

我的程序如何工作:到目前為止,我有三節課。

main.java此類構建我的框架並運行所有其他方法。

cards.java此類創建一個數組,其中保存卡片值和圖片位置。 我在那里有一個for循環,它會自動填充它。

hits.java此類旨在“隨機”生成一個代表所選卡的數字。 它的工作方式是采用隨機創建的int並將其指向數組上匹配的索引位置。

我將值分配給字符串對象,然后嘗試將其添加到jlabel,然后將該jlabel添加到我的主框架。 代碼如下:

hits.java

// Import necessary classes.
import java.util.Random;

public class hits {
// Create random object.
Random rand = new Random();

// Declare variables.
int card;
String cardVal, cardPic;

// Instantiate the needed classes.
main s = new main();
cards t = new cards();

// Constructor for the class.
public hits() {
    // Randomly generate a number (0 - 9).
    card = rand.nextInt(10);

    // Populate the array.
    t.runCards();

    // Assign the cards according to the num. generated.
    cardVal = t.deck[card][0];
    cardPic = t.deck[card][1];
}
// Run Method
public void runHits() {
    // Add the card chosen to the GUI.
    s.a.setText("hello");
    s.dealerCards.add(s.a);
}
}

我將“ hello”作為標簽的文本,因為我想看看我的數組是否未填充,但即使這樣也不起作用。 如果有用的話 ,這里也是我的main.java (構造函數和main方法):

// Constructor for the main class.
public main() {
    // Setup the MAIN container.
    f1.getContentPane().setLayout(new GridLayout(0, 1));
    f1.setSize(200, 200);
    f1.add(dealerName);
    f1.add(dealerCards);
    f1.add(userCards);
    f1.add(userName);

    // Setup the inner panels.
    dealerCards.setLayout(new GridLayout(1, 2));
    dealerCards.add(b);
    userCards.setLayout(new GridLayout(1, 6));
    userCards.add(c);
    userCards.add(d);
}
// Build the frame.
public void GUILaunch() {
    // Display Frame
    f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f1.setVisible(true);
}
// Main method.
 public static void main(String args[]) {
     // Distribute the dealer's/player's starting hands.
     hits deal = new hits();
     deal.runHits();

     // Launch the GUI
     main gui = new main();
     gui.GUILaunch();
}

希望我提供了足夠的信息來幫助您了解這里的情況。 因此,總而言之: 我如何將持有隨機選擇的卡片的jlabel(來自另一個類)添加到我的主框架中

提前致謝。

deal.runHits()將標簽添加到交易擁有的Main對象而不是gui對象。

我建議以下內容:

讓您的主類有一個hits實例,而hits有一個cards對象的實例...所以您會得到這樣的信息

public class main {

private hits hits_instance

//constructor

main(){ hits_instance = new hits(); }

//this method will add your cards

public void addCards(){
// frame = whatever frame you are using
frame.add(hits_instance.getCards());

}

}

public class hits {

private cards cards_instance;

hits(){ cards_instance= new cards();}

public JLabel getCards() {return cards_instance.getCard(randomNumber);}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM