简体   繁体   中英

displaying images from an array in a gui window using swing in java

I am developing a program that will populate an array with 52 images of cards from a file. I would like to display these images in a gui window. This is for a program that will select five random card images and display them in a gui window. So, right now, i am trying to develop the part of the code which will display images from an array in a window and i am at a loss as to how to display png images in a jframe. This is the code i have so far. I used a system.out.println statement so i know that the array of 52 card images is populating correctly, however, i do not know how to display them properly in a window.

String[] cardsArray = new String[52];

for (int i = 0; i < 52; i++)
{
    cardsArray[i] = "C:\\Users\\mike\\Documents\\NetBeansProjects\\card shuffler\\cards\\\"+String.valueOf(i+1)+".png";
}

System.out.println(Arrays.toString(cardsArray));

additional note. I have to use a jframe to display the results in a side by side layout. I thought to use flowLayout to accomplish this, but, ia not sure how to pass in an array of images. I have no problem doing it with a single image from a file. I am using the code below as a guide.

JFrame myJFrame = new JFrame();

// create and assign a FlowLayout for myFrame
myJFrame.setLayout(new FlowLayout());

// Create a label with an image icon
JLabel jlCSCI = new JLabel(new ImageIcon("CSCI.jpg"));

// add the Label to the frame 
myJFrame.add(jlCSCI); // Add thelabel to MyGridLayout

// set the title, size, location and exit behavior for the frame
myJFrame.setTitle("ImageIcon Demo");
myJFrame.setSize(240, 200);
myJFrame.setLocation(200, 100);
myJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// make the frame visible (activate the GUI frame)
myJFrame.setVisible(true);

I am not sure how to develop the statement that would utilize an array that i created within the program.

Maybe like this?

for (String imgName : cardsArray)
{
    myJFrame.add(new JLabel(new ImageIcon(imgName)));
}

Hope this helps.

EDIT:

I simply added a JLabel with an Icon to the frame. The ImageIcon class is just an implementation of the Icon interface and it creates an icon by reading an image from file. Creating a JLabel with an Icon will display the icon instead of the text. You can also combine the text and the icon. For more info, check the documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM