使用JFrame实现图片切换功能

jframe已是过气组件,了解即可

代码如下:

package awt;

import javax.swing.;
import java.awt.
;
import java.awt.event.ActionEvent;
import java.io.File;

/**

  • @author hefaqiang

  • @version 1.0

  • @description: TODO

  • @date 2023/6/27 10:57
    */
    public class AwtTest {
    public static void main(String[] args) {
    String absPath = “C:\Users\longyuan\Desktop\图片”;
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    Dimension screenSize = toolkit.getScreenSize();

     JFrame jFrame = new JFrame("图片浏览");
     jFrame.setResizable(true);
     //设置窗口大小
     jFrame.setBounds(0, 0, screenSize.width, screenSize.height);
     //设置画板中组件以卡片方式展示
     CardLayout cardLayout = new CardLayout();
     //创建画板
     JPanel p1 = new JPanel();
     p1.setLayout(cardLayout);
     //设置背景颜色
     p1.setBackground(Color.WHITE);
     //设置画板大小
     p1.setBounds(0, 0, screenSize.width, screenSize.height - 100);
    
     File dir = new File(absPath);
     if (dir.exists()) {
         String[] files = dir.list();
         int i = 0;
         for (String file : files) {
             JLabel label = new JLabel();
             ImageIcon imageIcon = new ImageIcon(String.format("%s\\%s", absPath, file));
             //添加图片
             label.setIcon(imageIcon);
             label.setBounds(0, 0, imageIcon.getIconWidth(), imageIcon.getIconHeight());
             p1.add(i++ + "", label);
         }
     }
     jFrame.add(p1);
    
     JPanel p2 = new JPanel();
     p2.setBackground(Color.lightGray);
     p2.setBounds(0, screenSize.width, screenSize.width, 100);
    
     JButton next = new JButton("上一张");
     //监听事件
     next.addActionListener((ActionEvent e) -> cardLayout.next(p1));
     JButton pre = new JButton("下一张");
     pre.addActionListener((ActionEvent e) -> cardLayout.previous(p1));
    
     p2.add(pre);
     p2.add(next);
    
     jFrame.add(p2, BorderLayout.SOUTH);
     jFrame.setVisible(true);
    

    }
    }

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值