【发布时间】:2011-05-07 04:16:06
【问题描述】:
我正在尝试为我在 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 也是(构造函数和主要方法):
// 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属性是什么:s.a.setText("hello");?我错过了什么吗? -
那是我的 JLabel 的名字...抱歉你看不到它;我在我的主类中声明了它
-
请学习java命名约定并遵守它们
-
@kleopatra 已经做到了..那个名字只是临时的。你对你的回复没有多大帮助,所以请不要打扰.....
-
我打扰与否 - 这不是你的决定 ;-) 为了你在这里的长期成功,你最好遵守规范