[英]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. 我正在开发一个程序,用一个文件中的52张卡片填充数组。 I would like to display these images in a gui window.
我想在gui窗口中显示这些图像。 This is for a program that will select five random card images and display them in a gui window.
这是一个程序,它将选择五个随机卡片图像并在gui窗口中显示它们。 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.
所以,现在,我正在尝试开发代码的一部分,它将在窗口中显示来自数组的图像,我不知道如何在jframe中显示png图像。 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.
我使用了system.out.println语句,所以我知道52张卡片图像的数组正确填充,但是,我不知道如何在窗口中正确显示它们。
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.
我必须使用jframe以并排布局显示结果。 I thought to use flowLayout to accomplish this, but, ia not sure how to pass in an array of images.
我想用flowLayout来完成这个,但是,我不知道如何传入一个图像数组。 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. 我只是在框架中添加了一个带有
Icon
的JLabel
。 The ImageIcon
class is just an implementation of the Icon
interface and it creates an icon by reading an image from file. ImageIcon
类只是Icon
界面的一个实现,它通过从文件中读取图像来创建一个图标。 Creating a JLabel with an Icon will display the icon instead of the text. 使用图标创建JLabel将显示图标而不是文本。 You can also combine the text and the icon.
您还可以组合文本和图标。 For more info, check the documentation .
有关详细信息,请查看文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.