我正在尝试在可滚动窗格中加载一些图像。但由于某种原因,它没有出现。这是我添加图像的代码。
private JFileChooser fileChooser = new JFileChooser(){
@Override
public void approveSelection(){
File files[] = fileChooser.getSelectedFiles();
JPanel panel = new JPanel(new GridLayout(files.length, 1));
for(int lop=0; lop< files.length; lop++){
BufferedImage image = null;
try {
image = ImageIO.read(files[lop]);
} catch (IOException ex) {}
BufferedImage img = new BufferedImage(100, 100, 1);
Graphics2D g = img.createGraphics();
g.drawImage(image, 0, 0, 100, 100, null);
g.dispose();
ImageIcon icon = new ImageIcon(img);
JLabel lable = new JLabel(icon);
panel.add(lable);
}
jScrollPane1.getViewport().add(panel);
super.approveSelection();
}
};
使用上面的fileCHooser,我选择一些图像加载到垂直scrollPane中,不知何故,scrollPane水平滚动条显示长度的变化,但滚动窗格中没有内容。请检查以下屏幕截图。在Shapes的标题下:您将看到一个带有扩展滚动条的空容器
的问候, Aqif Hamid
答案 0 :(得分:3)
问题在于这行代码:
jScrollPane1.getViewport().add(new JFrame().add(panel));
为什么要创建JFrame?
您应该像这样创建JScrollPane:
jScrollPane = new JScrollPane(panel);
或者像这样设置滚动窗格的视图:
jScrollpane.setViewportView(panel);
此外,您应该只使用panel.add(lable)
。 GridLayout会将标签放在适当的位置。
你不应该忽视异常。将空catch块转换为:
try {
image = ImageIO.read(files[lop]);
}
catch (IOException ex) {
throw new RuntimeException(ex);
}