繁体   English   中英

使用java中的swing在gui窗口中显示来自数组的图像

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

我正在开发一个程序,用一个文件中的52张卡片填充数组。 我想在gui窗口中显示这些图像。 这是一个程序,它将选择五个随机卡片图像并在gui窗口中显示它们。 所以,现在,我正在尝试开发代码的一部分,它将在窗口中显示来自数组的图像,我不知道如何在jframe中显示png图像。 这是我到目前为止的代码。 我使用了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));

另外注意。 我必须使用jframe以并排布局显示结果。 我想用flowLayout来完成这个,但是,我不知道如何传入一个图像数组。 使用文件中的单个图像来完成它没有任何问题。 我使用下面的代码作为指南。

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);

我不确定如何开发利用我在程序中创建的数组的语句。

也许是这样的?

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

希望这可以帮助。

编辑:

我只是在框架中添加了一个带有IconJLabel ImageIcon类只是Icon界面的一个实现,它通过从文件中读取图像来创建一个图标。 使用图标创建JLabel将显示图标而不是文本。 您还可以组合文本和图标。 有关详细信息,请查看文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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