java 图像库,Java平铺图像库

I was wondering how to go about making an image gallery like this one:

MgRh2.png

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:

BeGWh.png

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!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值