刚刚一个大二学妹请教我怎么用Swing实现点击一个按钮显示一张照片,用简单的办法实现了一下。
package com.fzshuai.test;
import javax.swing.*;
import java.awt.*;
/**
* @author fzshuai
* @date 2022/04/29 19:27
* @since 1.0
*/
public class DemoFrame extends JFrame {
JPanel panel;
JLabel label;
JButton btn;
// ImageIcon IMG = new ImageIcon(
// Toolkit.getDefaultToolkit().createImage(DemoFrame.class.getResource("/QQ截图20220421173615.png")));
ImageIcon IMG = new ImageIcon("C:/Users/fzshuai/Desktop/QQ截图20220424001608.png");
public DemoFrame() {
panel = new JPanel();
label = new JLabel();
btn = new JButton("显示图片");
panel.add(label);
panel.add(btn);
add(panel, BorderLayout.SOUTH);
// 按钮点击事件
btn.addActionListener(e -> {
label.setIcon(IMG);
});
}
public static void main(String[] args) {
DemoFrame frame = new DemoFrame();
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}