-1

我正在尝试在可滚动窗格中加载一些图像。但由于某种原因,它没有出现。这是我添加图像的一段代码。

 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,我选择了一些图像加载到垂直滚动窗格中,不知何故,滚动窗格水平滚动显示长度变化,但滚动窗格中没有内容。请检查以下屏幕截图。在 Shapes 标题下:您将看到一个带有扩展滚动条的空容器

截屏

问候, 阿基夫·哈米德

4

1 回答 1

3

The problem is with this line of code:

jScrollPane1.getViewport().add(new JFrame().add(panel));

Why do you create a JFrame?

You should just create the JScrollPane like this:

jScrollPane = new JScrollPane(panel);

Or set the view of the scrollpane like this:

jScrollpane.setViewportView(panel);

Also, you should just use panel.add(lable). The GridLayout will put the label at the appropriate location. And you should not ignore exceptions. Transform the empty catch block to:

try {                
    image = ImageIO.read(files[lop]);
} 
catch (IOException ex) {
    throw new RuntimeException(ex);
}
于 2012-06-24T19:57:10.883 回答