[英]swing components not showing up in JScrollPane
我正在尝试在可滚动窗格中加载一些图像。 但是由于某种原因,它没有显示出来。 这是我添加图像的代码。
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水平滚动器会显示出长度的变化,但是滚动窗格中没有内容。 请检查以下屏幕截图。 在“形状”标题下:您将看到一个带有扩展滚动条的空容器
问候,Aqif Hamid
问题出在这行代码上:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.