I'm trying to create a JScrollPane
that contains a gallery of Images and JFreeCharts
. For now I'm just using colored rectangles to test.
I've got two problems, first of which is that I don't quite understand my own code (it somewhat does what I need it to but I'm not sure why).
My main confusion here is, and please see the code below, the need for a panel that holds my image-holding panels:
panel.add(panelHolder[m][n]);
I would think that I could just add the panels directly to the scrollPanel
instead
scrollPanel.add(panelHolder[m][n])
But when I do so the scrollPanel
will appear empty.
My second problem can be seen in the following screenshot: There are massive gaps between the images, and the sizes of these seem to change when I play with the rectangle size? I've tried giving panel
a GridLayout
to avoid margins but this doesn't change anything.
//Load Images
Image img = ImageIO.read(new File("H:\\testimg.PNG"));
BufferedImage bimg = toBufferedImage(img);
ImageIcon icon1 = new ImageIcon(bimg);
JLabel iconholder = new JLabel(icon1);
Image img1 = ImageIO.read(new File("H:\\testimg2.PNG"));
BufferedImage bimg1 = toBufferedImage(img1);
ImageIcon icon2 = new ImageIcon(bimg1);
JLabel iconholder1 = new JLabel(icon2);
Image img2 = ImageIO.read(new File("H:\\testimg3.PNG"));
BufferedImage bimg2 = toBufferedImage(img2);
ImageIcon icon3 = new ImageIcon(bimg2);
JLabel iconholder2 = new JLabel(icon3);
//Create Tab
int i=4;
int j=2;
JPanel[][] panelHolder = new JPanel[i][j];
GridLayout glay = new GridLayout(i,j);
glay.setVgap(0);
glay.setHgap(0);
JPanel panel = new JPanel(glay);
JScrollPane scrollPanel = new JScrollPane(panel);
//Put image holding panels in scrollPanel
for(int m = 0; m < i; m++) {
for(int n = 0; n < j; n++) {
panelHolder[m][n] = new JPanel();
panel.add(panelHolder[m][n]);
}
}
scrollPanel.setPreferredSize(new Dimension(410, 50));
scrollPanel.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPanel .setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPanel.getVerticalScrollBar().setUnitIncrement(16);
//Put Images in
panelHolder[0][0].add(iconholder);
panelHolder[3][0].add(iconholder1);
panelHolder[1][1].add(iconholder2);