我正在嘗試爲我的Java最終項目創建一個二十一點程序。我還是很新的Java和OOD,所以我很抱歉,如果我的問題似乎很平凡的你:(從另一個類向JFrame添加對象?
如何我程序工作:我有三個類到目前爲止
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);
}
}
我有「你好」作爲文本的標籤,因爲我想看看,如果可能我的數組沒有填充,但即使沒有按沒有工作。如果它幫助這裏是我的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(從另一個類)持有隨機選擇的卡到我的主框架
在此先感謝。
是什麼你引用的'a'屬性是這樣的:'sasetText(「hello」);'?我錯過了什麼嗎? – 2011-05-07 04:33:03
這是我的JLabel的名字......對不起,你看不到它;我已經在我的主類 – lemonpole 2011-05-07 06:08:59
中聲明瞭請學習java命名約定,並堅持他們 – kleopatra 2011-05-07 09:39:57