我正在尝试构建 JButton
图像数组。这些将有一个切换(可见/不可见),这就是我选择使用 JButton 的原因。
这些按钮还有背景图像。当我将一个按钮放置到 Pane 中时,这显然是用 Java 编写的,它可以工作。但是当我将按钮加载到数组中并尝试将它们打印到 Pane 时,什么也没有......我将不胜感激。这是我所拥有的。
JButton card = new JButton();
JButton[] deck = new JButton[9];
int xLoc=20, yLoc=5;
card.setIcon(new ImageIcon("Back.jpg"));
card.setSize(200,250);
card.setVisible(true);
for(int i=0; i<9;i++)
{
deck[i]=card;
}
for(int i=1;i<10;i++)
{
deck[i-1].setLocation(xLoc,yLoc);
pane.add(deck[i - 1]);
validate();
xLoc+=220;
if(i%3==0)
{
yLoc+=265;
}
在我看来,我正在创建一个具有大小、背景且可见的卡片对象,然后一遍又一遍地将同一张卡片加载到我的数组中,然后将其添加到具有背景的 Pane 中。它不会导致任何错误或异常,但不会将除背景之外的任何内容放置到 Pane 中。
提前致谢。老实说,这是一项家庭作业,但走这条路我超出了预期。我知道我可以创建单独的按钮并将它们放在屏幕上。我知道怎么做,也能做到。我想做的事情不在类(class)范围之内。
这是一个项目,而不仅仅是一项作业,讲师鼓励我们自己学习新事物并扩展项目。所以,通过帮助我,你不是在帮助我作弊,而是帮助我学到比类里面教授的更多的东西。谢谢!
最佳答案
您的基本问题归结为组件只能驻留在单个父级中......
// You create a card...
JButton card = new JButton();
// You create an array of buttons
JButton[] deck = new JButton[9];
int xLoc=20, yLoc=5;
// You set the icon
card.setIcon(new ImageIcon("Back.jpg"));
// This is not a good idea...
card.setSize(200,250);
// JButton is visible by default...
card.setVisible(true);
// Start your loop...
for(int i=0; i<9;i++)
{
// Assign the card reference to an element in the array...
deck[i]=card;
// Add the card, via the array to the component...here's your problem...
pane.add(deck[i - 1]);
将 card
添加到 pane
时,首先将其从 pane
中删除,因为它只能有一个父级。您需要做的是将 JButton
的唯一实例分配给数组中的每个元素
// You create an array of buttons
JButton[] deck = new JButton[9];
// Start your loop...
for(int i=0; i<9;i++)
{
// Assign the card reference to an element in the array...
deck[i]=new JButton();
// You set the icon
deck[i].setIcon(new ImageIcon("Back.jpg"));
// This is not a good idea...
deck[i].setSize(200,250);
// JButton is visible by default...
deck[i].setVisible(true);
// Add the card, via the array to the component...here's your problem...
pane.add(deck[i]);
现在,我无法从您的代码片段中看到,但您似乎正在尝试使用 null
布局,这是非常不可取的。相反,花时间学习和理解如何使用 appropriate layout managers .
如果您没有使用 null
布局或者不知道我在说什么,那么可以使用 setSize
和 setLocation
等内容> 不会按照您期望的方式工作...
关于java - 如何制作 Jbutton 图像数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22315401/