我使用JFileChooser
实现了此代码以浏览图像,但问题是我无法实现在本地磁盘上保存图像的代码。
要么
如果可能,我直接想要在新的JFrame
类中显示此图像,这将是一个动态链接
private void btnBrowseVideo1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser fileChooser = new JFileChooser();
fileChooser.showOpenDialog(null);
mediaUrl = null;
String path = "";
path = fileChooser.getSelectedFile().toString();
path = path.trim();
// System.out.println("URI : "+mediaUrl);
if (path.endsWith(".jpg") || path.endsWith(".JPG")) {
lblBrowseImage.setText(path);
} else {
JOptionPane.showMessageDialog(this, "SELECT .jpg FILE!!!!");
}
}
答案 0 :(得分:1)
我希望我对这个问题的解释是正确的。查看ImageIO read()
和write()
方法以加载和保存图片。另外,请参阅Working with Images和How to Use Labels教程以获取更多详细信息和示例。
为简单起见,这是一个显示用户在标准对话框中选择的图像的示例:
import java.awt.BorderLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
public class ShowImage {
private static void createAndShowUI() {
final JFrame frame = new JFrame("Load Image");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton loadButton = new JButton("Display Image");
loadButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser(
System.getProperty("user.home"));
fc.addChoosableFileFilter(new FileNameExtensionFilter(
"Image files", new String[] { "png", "jpg", "jpeg",
"gif" }));
if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
try {
Image image = ImageIO.read(fc.getSelectedFile());
if (image != null) {
JPanel panel = new JPanel(new BorderLayout(10, 10));
panel.add(new JLabel(fc.getSelectedFile().toString()),
BorderLayout.NORTH);
panel.add(new JLabel(new ImageIcon(image)));
JOptionPane.showMessageDialog(frame, panel);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
});
frame.add(loadButton);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
ex.printStackTrace();
}
createAndShowUI();
}
});
}
}