Reputation: 3
I am making a storybook and, because I'm not very creative with names, I gave images page numbers like so.
ImageIcon pg1icon = new ImageIcon("images/1.png");
ImageIcon pg2icon = new ImageIcon("images/2.png");
ImageIcon pg3icon = new ImageIcon("images/3.png");
JLabel pg1Label = new JLabel(pg1icon);
JLabel pg2Label = new JLabel(pg2icon);
JLabel pg3Label = new JLabel(pg3icon);
Because I have 30 pages, this process is getting tedious. Is there a way to scale the page num similar to i++?
Upvotes: 0
Views: 55
Reputation: 201439
Assuming you only need the ImageIcon
for the JLabel
, you could use one array to store your thirty JLabel
(s). Like,
int pageCount = 30;
JLabel[] labels = new JLabel[pageCount];
for (int i = 0; i < pageCount; i++) { // <-- i++ as requested
ImageIcon icon = new ImageIcon(String.format("images/%d.png", 1+i));
labels[i] = new JLabel(icon);
}
And then use labels[0]
- labels[29]
instead of pg1Label
- pg30Label
.
Upvotes: 1
Reputation: 521178
Using streams we can handle this requirement concisely as:
List<JLabel> labels = IntStream.rangeClosed(1, 30)
.mapToObj(i -> new JLabel(new ImageIcon("images/" + i + ".png")))
.collect(Collectors.toList());
Upvotes: 3