Java 从另一个类向JFrame添加对象?
我正试图为我的最后一个Java项目创建一个21点程序。我对Java和OOD还很陌生,所以如果您觉得我的问题很微不足道,我向您道歉:( 我的课程如何运作:到目前为止,我有三节课 main.java 这个类构建我的框架并运行所有其他方法 cards.java 这个类创建了一个数组来保存卡片值和图片的位置。我在其中有一个for循环来自动填充它 hits.java 该类旨在“随机”生成一个表示所选卡片的数字。其工作方式是获取随机创建的int并将其指向数组上匹配的索引位置 我将值分配给字符串对象,然后尝试将其添加到jlabel,然后将该jlabel添加到我的主框架中。代码如下: hits.javaJava 从另一个类向JFrame添加对象?,java,arrays,Java,Arrays,我正试图为我的最后一个Java项目创建一个21点程序。我对Java和OOD还很陌生,所以如果您觉得我的问题很微不足道,我向您道歉:( 我的课程如何运作:到目前为止,我有三节课 main.java 这个类构建我的框架并运行所有其他方法 cards.java 这个类创建了一个数组来保存卡片值和图片的位置。我在其中有一个for循环来自动填充它 hits.java 该类旨在“随机”生成一个表示所选卡片的数字。其工作方式是获取随机创建的int并将其指向数组上匹配的索引位置 我将值分配给字符串对象,然后尝试
// 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方法):
希望我已经提供了足够的信息来帮助您理解这里发生了什么。所以总结一下:我如何将持有随机选择的卡的jlabel(来自另一个类)添加到我的主框架中
提前感谢。deal.runHits()将标签添加到deal拥有的主对象,而不是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);}
}
您这样引用的
a
属性是什么:s.a.setText(“hello”);
?我遗漏了什么吗?这是我的JLabel的名称…很抱歉,您看不到它;我在我的主类中声明了它。请学习java命名约定并坚持使用them@kleopatra已经有了……那个名字只是临时工。你在回复中帮不了什么忙,所以请不要打扰……打扰我还是不打扰我——这不是你的决定;-)为了你在这里取得长期的成功,你最好按照规范行事。是的,它通过从主类内部将其添加到框架中来起作用。不幸的是,我的数组出现了一些问题,它没有显示值。。。但至少我可以看到字符串出现在那里。谢谢你的帮助。:)最后一个问题。。。所以我无法从另一个类设置swing对象的值。。。就像我试图实现的一样?尝试发送希望作为方法中的参数或构造函数使用的JSwing对象。。public void addJLabel(JFrame frame){frame.add(label1);}公共类class1{private JFrame frame_to_work_with;class1(JFrame frame){frame_to_work_with=frame;}
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);}
}