0

As part of an application I'm writing, I resize and move a picture of a pallet in a JLabel. Because the JLabel is in a JLayeredPane, I'm not using a layout manager, and as a result, ever time I resize the palletLabel's icon I use setBounds() to control its dimensions and location on the page. A picture of what it looks like is below:

enter image description here

The code that controls what happens when the pallet is image is resized is called each time the dimensions (specified by the JSpinners that can be seen to the left) are changed. The palletLabel is resized is below:

private void resizePalletImage(int[] size)
{
    Dimension dim = calculatePalletImageSize(size[1], size[0]);
    palletImage = ResizeImage.scaleImageByAbsoluteValues(originalPalletImage, dim);
    ImageIcon icon = new ImageIcon(palletImage);
    palletLabel.setIcon(icon);
    layerPanelHeight = layerCenterPanel.getHeight();
    //Have to set this twice, as the length hasn't "updated" by the time the first setBounds is called. Weird.
    palletLabel.setBounds(0, layerPanelHeight - palletLabel.getHeight(), icon.getIconWidth(), icon.getIconHeight());
    palletLabel.setBounds(0, layerPanelHeight - palletLabel.getHeight(), icon.getIconWidth(), icon.getIconHeight());
}
  • originalPalletImage is a high resolution copy of the original image, this is used to prevent blurring after lots of image resizing.
  • ResizeImage.scaleImageByAbsoluteValues is a static method that is used to resize the image. It just calls Image.getScaledInstance after a couple of calculations.
  • layerCenterPanel is the JLayeredPane upon which panelLabel sits.

As seen, I call setBounds() twice at the end. Initially it was only called once, and it resized the palletLabel, but it didn't use the values that had just been set earlier in the method, but rather the previous values, and the pallet image floated about where it shouldnt (as the previous value for palletLabel.getHeight() was being used). In other words, the method worked as intended but was always one iteration behind. I have solved this by just calling setBounds() twice and it now works exactly as intended. I am simply wondering why this is necessary, I tried putting setBounds() within an invokeLater but it had no effect.

Any input is welcome, Thanks.

Sam Hilton
  • 30
  • 6

0 Answers0