I am trying to learn how to use JAVA's GUI library Swing. What I am trying to do is place 2 images of disks in a row and 3 images of printers in the row below them. Each disk image should be in the middle of two printer images. I am (unfortunately) using GridBagLayout
to achieve this. I am trying to construct a grid of 12 columns and have each printer take 4 and each disk 6. I then tried to set the objects' anchors to GridBagConstraints.PAGE_END
so the images are in the bottom middle part of the cell. No matter what I do I can't get the disks to align properly, I spent a tremendous amount of time trying to fix this.
Here is my function that creates the objects:
private void placeIcon(Container pane, GridBagConstraints c, int x, int y, String imagePath,
String imageLabel, int gridWidth) {
BufferedImage printerIcon;
try {
printerIcon = ImageIO.read(new File(imagePath));
} catch (IOException e) {
e.printStackTrace();
return;
}
JLabel textLabel = new JLabel(imageLabel + Integer.toString(x + 1),
SwingConstants.CENTER);
JPanel iconPanel = new JPanel();
iconPanel.setLayout(new GridBagLayout());
textLabel.setPreferredSize(new Dimension(100,10));
GridBagConstraints iconConstr = new GridBagConstraints();
iconConstr.gridx = 0;
iconConstr.gridy = 0;
iconConstr.insets = new Insets(10, 3, 1, 3);
iconConstr.anchor = GridBagConstraints.PAGE_END;
iconConstr.weightx = 1;
iconConstr.weighty = 1;
iconPanel.add(textLabel, iconConstr);
JLabel iconLabel = new JLabel(new ImageIcon(printerIcon));
iconLabel.setPreferredSize(new Dimension(250,250));
iconConstr.gridx = 0;
iconConstr.gridy = 1;
iconConstr.insets = new Insets(1, 3, 1, 3);
iconConstr.anchor = GridBagConstraints.PAGE_END;
iconConstr.weightx = 1;
iconConstr.weighty = 1;
iconPanel.add(iconLabel, iconConstr);
c.gridx = x;
c.gridy = y;
c.weightx = 1;
c.weighty = 1;
c.anchor = GridBagConstraints.PAGE_END;
c.gridwidth = gridWidth;
c.insets = new Insets(25, 10, 1, 10);
pane.add(iconPanel, c);
}
Calling it like this to create the printer and disk images:
private void placeAllPrinterIcons(Container pane, GridBagConstraints c, int yPos) {
String imgPath = "bin/images/printer_icon.png";
String label = "Printer ";
placeIcon(pane, c, 0, yPos, imgPath, label, 4);
placeIcon(pane, c, 4, yPos, imgPath, label, 4);
placeIcon(pane, c, 8, yPos, imgPath, label, 4);
}
private void placeAllDiskIcons(Container pane, GridBagConstraints c, int yPos) {
String imgPath = "bin/images/disk_icon.png";
String label = "Disk ";
placeIcon(pane, c, 0, yPos, imgPath, label, 6);
placeIcon(pane, c, 6, yPos, imgPath, label, 6);
}
Container pane = getContentPane();
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
placeAllDiskIcons(pane, c, 0);
placeAllPrinterIcons(pane, c, 1);