我想知道如何制作像这样的图片库:
我所需要的只是像上面那样在 5x5 正方形中显示图像,并为每个图像提供一个单击事件(我知道如何执行 ActionEvents)
我尝试制作 GridLayout
使用构造函数5, 5
,然后使用 panel.add(image, 0, 0);
添加图像等等,但都无济于事。这是代码:
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);
这就是我得到的:
谢谢大家!
最佳答案
如果您要进行布局,请使用 GridLayout,而不是 BorderLayout。它实际上以网格方式设置屏幕上的项目。只需将面板的布局设置如下:
panel.setLayout(new GridLayout(5,5));
这应该会创建您正在寻找的输出。希望这有帮助!
编辑:
您可以只使用 BASE 面板,并添加 JButton 而不是 JLabels。要显示图像,只需执行以下操作:
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);
不必担心将图像放置在特定位置(当然,除非您有这样做的原因),但程序已经将图像放置在正确的位置,并按照您放置它们的顺序将它们添加到面板,因此担心将它们放在特定位置是浪费时间。希望这对您有帮助!
关于java - Java 中的平铺图片库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16389620/