javaswingcss-positionimageicon

Absolute Positioning Image Icons in java swing


So I am trying to write for my project essentially a pokemon battle between 3 different pokemon using java swing. However the part which is stalling me is the animations. I tried using a null layout with setLocation so that I can move the imageicons based on a timer but the issue is, as you probably know, the imageicons won't show up in the null layout. Is there anyway to change it so that it will work this way. This is how I have declared my pictures

java.net.URL torterraPic = getClass().getResource("torterra-1.gif");

ImageIcon torterra = new ImageIcon(new ImageIcon(torterraPic).getImage().getScaledInstance(100, 100, Image.SCALE_DEFAULT));

then I place my Image Icon in a JLabel which I add to the frame and then I do setLocation to chose where it goes.

I understand that it is discouraged to use absolute positioning but I feel that this is the best way to do this (assuming it is possible to add a picture) because that way I can manipulate the setLocation to make it move upwards during the attack. I have tried using gridbag and grid layout to try to do it but neither are as convenient for me.

So if there is someway to make this workout please tell me. Thanks in advance!


Solution

  • I tried using a null layout with setLocation so that I can move the imageicons based on a timer but the issue is, as you probably know, the imageicons won't show up in the null layout.

    Yes they will but you are now responsible to doing the layout manager functions, which means you need to set the location and size of the label.

    Typically you would do something like:

    label.setIcon(...);
    label.setSize( label.getPreferredSize() ):
    label.setLocation(...);
    

    Then in your animation you just change the location as desired.