java画图板显示图片
时间: 2024-01-08 21:21:15 浏览: 36
以下是一个Java画图板显示图片的例子:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class DrawPad extends JFrame implements ActionListener {
private JLabel imageLabel;
public DrawPad() {
// 创建一个JFrame窗口
JFrame frame = new JFrame("画图板");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
// 创建一个JLabel用于显示图片
imageLabel = new JLabel();
frame.add(imageLabel);
// 创建一个按钮用于选择图片
JButton chooseButton = new JButton("选择图片");
chooseButton.addActionListener(this);
frame.add(chooseButton, BorderLayout.SOUTH);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("选择图片")) {
// 弹出文件选择对话框
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
// 获取选择的文件路径
String imagePath = fileChooser.getSelectedFile().getPath();
// 加载图片并显示在JLabel上
ImageIcon imageIcon = new ImageIcon(imagePath);
imageLabel.setIcon(imageIcon);
}
}
}
public static void main(String[] args) {
new DrawPad();
}
}
```