Java(GUI)多次添加JButton?
我正在学习 Java,我正在创建一个记忆类型的游戏,你必须找到两张相同的牌。
我创建了一个窗口等,但我的问题是向其中添加多个 JButton。 (我的卡片是带有图标的 JButton)。我已经对我的问题所在的代码进行了评论。
//Get the images.
private File bildmapp = new File("bildmapp");
private File[] bilder = bildmapp.listFiles();
//My own class extending JButton
Kort[] k = new Kort[bilder.length];
for(int i = 0; i < bilder.length; i++){
k[i] = new Kort(new ImageIcon(bilder[i].getPath()));
}
//Later in my code:
int sum = rows * columns;
Kort[] temp = new Kort[sum];
//My function to randomize.
Verktyg.slumpOrdning(k);
//***********************//
//Trying to fill a array from K (which contains all cards) so my temp contains SUM cards and SUM/2 pairs
for(int i = 0; i < sum/2; i++){
temp[i] = k[i];
temp[i+sum/2] = k[i];
}
//Problem is that i only get SUM/2 (half of the cards) cards, not the 16 (8 pairs) i would like to add in this case
//SYNLIGT = VISIBLE.
for(int i = 0; i < sum; i++){
temp[i].setStatus(Kort.Status.SYNLIGT);
j.add(temp[i]);
}
Im learning Java and Im creating a memory type game where you have to find two equal cards.
I have created a Window etc etc but my problem is adding multiple JButtons to it. (my cards are JButtons with icons). I have commented my code where my problem is.
//Get the images.
private File bildmapp = new File("bildmapp");
private File[] bilder = bildmapp.listFiles();
//My own class extending JButton
Kort[] k = new Kort[bilder.length];
for(int i = 0; i < bilder.length; i++){
k[i] = new Kort(new ImageIcon(bilder[i].getPath()));
}
//Later in my code:
int sum = rows * columns;
Kort[] temp = new Kort[sum];
//My function to randomize.
Verktyg.slumpOrdning(k);
//***********************//
//Trying to fill a array from K (which contains all cards) so my temp contains SUM cards and SUM/2 pairs
for(int i = 0; i < sum/2; i++){
temp[i] = k[i];
temp[i+sum/2] = k[i];
}
//Problem is that i only get SUM/2 (half of the cards) cards, not the 16 (8 pairs) i would like to add in this case
//SYNLIGT = VISIBLE.
for(int i = 0; i < sum; i++){
temp[i].setStatus(Kort.Status.SYNLIGT);
j.add(temp[i]);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的代码最终会将每个
Kort
对象添加到容器中两次,因为数组temp
包含对每个Kort
的两个引用。当您第二次添加Kort
时,它会移动到第二个位置。Component
一次只能出现在一个地方。Your code ends up adding each
Kort
object to the container twice, since the arraytemp
contains two references to eachKort
. When you add aKort
a second time, it moves to the second location. AComponent
can only appear in one place at a time.您不能两次添加相同的小部件。您需要两个单独的按钮(但您可以在两个按钮上使用相同的图标)。
You may not add the same widget twice. You need two separate buttons (but you may use the same icon on both).
您必须创建
sum
JButton 对象而不是sum/2
;否则 2 个按钮是相同的,因此只显示一次。You have to create
sum
JButton objects notsum/2
; otherwise 2 buttons are the same and therefore only displayed once.