gpt4 book ai didi

java - 在 Swing 中加载多个文件

转载 作者:行者123 更新时间:2023-12-01 18:43:24 28 4
gpt4 key购买 nike

如何在 Swing 中加载多个文件?

我有一个文件上传按钮,然后我以字节形式保存文件,如何更改代码以便我可以上传多个文件。我已经尝试了很多次,但遇到了麻烦..我希望有人可以帮助我

byte[] FileSurat;
String FilenameSurat;
File imageSurat;

private void botton10ActionPerformed(java.awt.event.ActionEvent evt) {
if (idPemohon == 0 && idRencanaTapak == 0){
JOptionPane.showMessageDialog(this, "Pilih Data Yang akan di Upload");
}else{

JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File(System.getProperty("user.home")));
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.addChoosableFileFilter(new FileNameExtensionFilter("Images", "jpg", "png", "gif", "bmp"));
chooser.setAcceptAllFileFilterUsed(true);

int i = chooser.showOpenDialog(this);
if (i == JFileChooser.APPROVE_OPTION) {
if(labelSurat != null){

FileSurat = null;
FilenameSurat = null;
jPanel2.remove(labelSurat);
jPanel2.validate();
jPanel2.repaint();
}
try {
imageSurat = chooser.getSelectedFile();
String filename = chooser.getSelectedFile().getName();
String extension = "";

int y = filename.lastIndexOf('.');
if (y > 0) {
extension = filename.substring(y+1);
}

String xx = chooser.getTypeDescription(imageSurat);
if("JPEG image".equals(xx) || "PNG image".equals(xx) || "JPG image".equals(xx) || "GIF image".equals(xx) || "BMP image".equals(xx)){
BufferedImage originalImage = ImageIO.read(imageSurat);
if(originalImage == null){
JOptionPane.showMessageDialog(rootPane, "Format file corrupt");
}else{
int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
BufferedImage resizeImageJpg = resizeImage(originalImage, type);
photoSurat = new ImageIcon(toImage(resizeImageJpg));
}
}else{
ico = new File(getClass().getResource("/images/no-image.png").getFile());
BufferedImage originalImage = ImageIO.read(ico);
int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();

BufferedImage resizeImageJpg = resizeImage(originalImage, type);
photoSurat = new ImageIcon(toImage(resizeImageJpg));
}

FilenameSurat = extension;
FileSurat = new byte[(int) imageSurat.length()];
FileInputStream fileInputStream = new FileInputStream(imageSurat);
fileInputStream.read(FileSurat);

//jPanel2.removeAll();


labelSurat = new JLabel("", photoSurat, JLabel.RIGHT);
jPanel2.add(labelSurat);

ico = null;
repaint();
chooser.setCurrentDirectory(imageSurat);
} catch (IOException ex) {
Logger.getLogger(formUtama.class.getName()).log(Level.SEVERE, null, ex);
}

}
}
}

最佳答案

您将 JFileChooser 切换为允许 multiple selection ,然后使用 JFileChooser#getSelectedFiles方法来获取File数组而不是单个文件。

使用您拥有的相同代码循环数组,就完成了

关于java - 在 Swing 中加载多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18976179/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com