I was wondering how to go about making an image gallery like this one:
All I would need is for it to display images in a 5x5 square like above with a click event for each image (I know how to do ActionEvents)
I tried making a GridLayout with the constructor 5, 5, then adding images with panel.add(image, 0, 0); and so on, but to no avail. Here's that code:
imagelayout = new GridLayout(5, 5, 5, 5);
imagepanel = new JPanel(imagelayout);
JLabel image = new JLabel(LogoManager.getInstance().getLogo("Apple"));
JLabel image1 = new JLabel(LogoManager.getInstance().getLogo("McDonalds"));
JLabel image2 = new JLabel(LogoManager.getInstance().getLogo("Fox"));
JLabel image3 = new JLabel(LogoManager.getInstance().getLogo("Microsoft"));
imagepanel.add(image, 0, 0);
imagepanel.add(image1, 1, 0);
imagepanel.add(image2, 1, 1);
imagepanel.add(image3, 2, 0);
And this is what I get:
Thanks guys!
解决方案
If you are going to be doing layouts, instead of BorderLayout, do GridLayout. It literally sets up the items on your screen in a grid fashion. Just set the panel's layout as so:
panel.setLayout(new GridLayout(5,5));
and that should create the output you are looking for. hope this helps!
EDIT:
You can just use the BASE panel, and add a JButton instead of JLabels. And to have the images appear, just do:
JButton image1 = new JButton(new ImageIcon(//apple logo));
JButton image2 = new JButton(new ImageIcon(//next logo));
JButton image3 = new JButton(new ImageIcon(//next logo));
JButton image4 = new JButton(new ImageIcon(//next logo));
JButton image5 = new JButton(new ImageIcon(//next logo));
panel.setLayout(new GridLayout(5,5));
panel.add(image1);
panel.add(image2);
panel.add(image3);
panel.add(image4);
panel.add(image5);
don't worry about putting the images in specific spots (unless of course you have a reason for that), but the program will already put the images in the correct spot, and in the order you place them by adding them onto the panel, so it's a waste of time to worry about putting them in the specific spot. Hope this helps you!