如何制作Jbutton图像阵列

时间:2014-03-11 02:39:50

标签: java arrays image swing jbutton

我正在尝试构建一个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;

    }

在我看来,我正在创建一个具有大小和背景并且可见的卡片对象,然后将相同的卡一遍又一遍地加载到我的阵列中,然后将其添加到具有背景的窗格中。它不会导致任何错误或异常,但除了背景外,它不会放置任何内容。

提前致谢。我会诚实地说这是一项家庭作业,但是我通过这条路线超出了预期。我知道我可以创建单独的按钮并将它们放在屏幕上。我知道怎么做,也可以做到。我想做的事不在课堂范围内。

这是一个项目,而不仅仅是一项任务,教师鼓励我们自己学习新事物并扩展项目。所以,通过帮助我,你不是在帮助我作弊,而是帮助我学习比课更多的东西。谢谢!

1 个答案:

答案 0 :(得分:2)

您的基本问题归结为一个组件只能驻留在单个父级中......

// 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布局或者不知道我在说什么,那么setSizesetLocation之类的内容将无法按您预期的方式运行他们......