我从JFileChooser获取文件并通过阅读BufferedImage
并放入JLabel来显示它们,但是有一个问题是我的图像没有完全显示在JLabel中。这是我的代码
public class ImagePreview
{
JPanel PicHolder= new JPanel();
public ImagePreview()
{
JButton GetImages = new JButton("Browse Images");
GetImages.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent evt)
{
CreatePreviews();
};
});
PicHolder.add(GetImages);
JFrame MainFrame = new JFrame("Image Preview");
MainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MainFrame.getContentPane().add(PicHolder);
MainFrame.pack();
MainFrame.setVisible(true);
}
public void CreatePreviews()
{
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
File[] selectedCarImages = chooser.getSelectedFiles();
for(int a=0; a<selectedImages.length; a++)
{
try
{
BufferedImage myPicture = ImageIO.read(new File(selectedImages[a].getAbsolutePath()));
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
PicHolder.add(picLabel);
}
}
}
public static void main(String[] args)
{
java.awt.EventQueue.invokeLater(() -> {
new ImagePreview();
});
}
}
当我运行此代码时,它会显示用户选择的图像,但它们会自动显示在JLabel中并且不会完全显示。
这里有什么问题?为什么JLabel没有显示完整的图像?
答案 0 :(得分:3)
您将所有组件和图片添加到具有默认FlowLayout
的单个面板。相反,使用GridLayout
作为图片标签,并将浏览按钮添加到框架的默认BorderLayout
,如下所示。
经测试:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class ImagePreview {
JFrame mainFrame = new JFrame("Image Preview");
JPanel picHolder = new JPanel(new GridLayout(0, 1));
public ImagePreview() {
JButton getImages = new JButton("Browse Images");
getImages.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent evt) {
CreatePreviews();
}
});
mainFrame.add(getImages, BorderLayout.NORTH);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.add(new JScrollPane(picHolder));
mainFrame.pack();
mainFrame.setLocationByPlatform(true);
mainFrame.setVisible(true);
}
public void CreatePreviews() {
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
chooser.showOpenDialog(mainFrame);
File[] selectedImages = chooser.getSelectedFiles();
for (int a = 0; a < selectedImages.length; a++) {
try {
BufferedImage myPicture = ImageIO.read(new File(selectedImages[a].getAbsolutePath()));
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
picHolder.add(picLabel);
mainFrame.pack();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(() -> {
new ImagePreview();
});
}
}