【发布时间】:2018-03-06 16:23:59
【问题描述】:
我在使用 ImageIcon 数组时遇到问题。当我单击 swing gui 上的 JButton 时,会显示 imageicon 的最后一个图像。我希望能够继续单击按钮并显示图像并让它遍历数组中的所有图像图标。
如何做到这一点?感谢您在这件事上的指导:)
Icon[] myIcons = {
new ImageIcon(getClass().getResource("image0.png")),
new ImageIcon(getClass().getResource("image1.png")),
new ImageIcon(getClass().getResource("image2.png")),
new ImageIcon(getClass().getResource("image3.png")),
};
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnSubmit) {
for (int i = 0; i < myIcons.length; i++) {
lblImage.setIcon(myIcons[i]);
}
}
}
});
【问题讨论】:
-
跟踪您设置的最后一个图标,然后在再次单击按钮时设置下一个图标(您不需要循环)。
-
一次调用 actionPerformed 是一键点击。因此,您当然不能在一个方法调用中显示所有图像。在您的类中保留一个索引字段,并在每次单击按钮时递增(即每次调用 actionPerformed)。显然,您还需要确保索引永远不会 ≥ 数组的大小。
标签: java arrays swing imageicon