Niral Mehta
Niral Mehta

Reputation: 63

Java Image array display

I have created an array for Java with what I believe is the correct method, however, when I attempt to display the image in a button, nothing happens and I am unable to find what the reason behind it is (code updated thanks to Frakcool

private void showOnesSecsActionPerformed(java.awt.event.ActionEvent evt) {                                             

    ImageIcon[] secs;
    secs = new ImageIcon[10]; Integer.parseInt(oneSecs.getText());
    for (int i = 0; i < 10; i++)
    {
        String location = "images\\" + i + ".png";
        secs[i] = new ImageIcon(location);
        oneSecsDisplay.setIcon(secs[i]);
    }

}

In the above snippet, the image is called from the secs[i] variable and then set as oneSecsDisplay new image.

oneSecsDisplay is a button that will show the image once another button called showOneSecs is pressed

I have 10 images from 0 to 9 that need to be displayed as a button is pressed; I was given the code:

int ones = Integer.parseInt(oneSecs.getText());
if (ones == 0) oneSecsDisplay.setIcon(new javax.swing.ImageIcon(filelocation);
if (ones == 0) oneSecsDisplay.setIcon(new javax.swing.ImageIcon(filelocation);

I don't think that this is good practice at it will be too repetitive and rather messy.

Upvotes: 1

Views: 2080

Answers (1)

David ten Hove
David ten Hove

Reputation: 2826

If you are trying to set just the correct image, there is no need for arrays or for loops. Try this instead:

private void showOnesSecsActionPerformed(java.awt.event.ActionEvent evt) {
    int index = Integer.parseInt(oneSecs.getText());
    String location = "images\\" + index + ".png";
    oneSecsDisplay.setIcon(new ImageIcon(location));
}

Upvotes: 2

Related Questions