'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 1:[1]
No need to use null layouts and component absolute positioning since your image sprites shouldn't be JLabels or other components but rather create BufferedImage sprites and then draw them in a single drawing JPanel's paintComponent method as per the painting tutorials -- Lesson: Performing Custom Painting.
Draw the background image(s) first in a static position, and then move the position of the sprites via g.drawImage(...)
override's x and y parameters. Drive the animation via a Swing Timer which uses an ActionListener or via other listeners such as Key Bindings.
Solution 2:[2]
JLabel label=new JLabel("");
Image img=new ImageIcon(this.getClass().getResource("hancie.png")).getImage();
label.setIcon(new ImageIcon(img));
label.setBounds(10,50,200,200);
label.setBorder(new LineBorder(Color.BLACK,4));
frame.add(label);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Hovercraft Full Of Eels |
Solution 2 | Hancie Phago |