Java 如何制作图像的Jbutton数组
我正在尝试构建一个Java 如何制作图像的Jbutton数组,java,arrays,image,swing,jbutton,Java,Arrays,Image,Swing,Jbutton,我正在尝试构建一个JButton图像数组。这些按钮将有一个切换(可查看/不可查看),因此我选择使用JButtons 这些按钮还具有背景图像。当我在窗格中放置一个按钮时,这是用Java编写的,显然是有效的。但是,当我将按钮加载到数组中并尝试将它们打印到窗格中时,什么都没有……我将感谢您的帮助。这是我的 JButton card = new JButton(); JButton[] deck = new JButton[9]; int xLoc=20, yLoc=5; card.setIcon(
JButton
图像数组。这些按钮将有一个切换(可查看/不可查看),因此我选择使用JButton
s
这些按钮还具有背景图像。当我在窗格中放置一个按钮时,这是用Java编写的,显然是有效的。但是,当我将按钮加载到数组中并尝试将它们打印到窗格中时,什么都没有……我将感谢您的帮助。这是我的
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;
}
JButton卡=新JButton();
JButton[]deck=新JButton[9];
int xLoc=20,yLoc=5;
设置图标(新的图像图标(“Back.jpg”));
卡片.设置尺寸(200250);
设置为可见(真);
对于(inti=0;i您的基本问题归结为一个事实,即组件只能驻留在单个父级中
// 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]);
现在,我无法从您的代码片段中看出,但您似乎试图使用null
布局,这是非常不可取的。相反,请花时间学习和理解如何使用
如果您没有使用null
布局,或者不知道我在说什么,那么setSize
和setLocation
之类的东西将无法按照您期望的方式工作…请为窗格和validate()提供源代码方法如果您的问题已被回答,请单击答案左侧的空心复选标记,将您认为最适合回答问题的答案标记为已接受,而不是发表评论(更不用说答案了!)感谢回答者。当你有至少15名代表时,你也可以对接受的答案和任何其他你认为有用的答案进行投票。请阅读以下内容:
// 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]);