0

I have been working on building a simple game using JFrame, JLabel, and buttons to execute different commands. However, the problem that I have been encountering is that I am unable to move around items in the JFrame no matter what I do. I am doing this in replit if it makes a difference.

This is what the current code for one of my labels looks like but the setLocation and setBounds do not seem to be working. I've also tried the setX and Y alignment methods but those have not worked either.

ImageIcon darm = new ImageIcon("Sprites/front.png");
JLabel dLabel = new JLabel(front);
Dimension dSize = dLabel.getPreferredSize();
dLabel.setBounds(400, 400, 500, 500);
dLabel.setLocation(400,150);
window.getContentPane().add(dLabel);
dLabel.setVisible(true); 
window.setLayout(null);
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • What is replit? (It's almost impossible to make animations the way you are doing it, with the GUI code. I'd use something like LibGDX or LWJGL.) – markspace Jun 16 '21 at 12:43
  • Generally, you define a JFrame and a drawing JPanel. You move objects on the drawing JPanel by changing the x and y locations of the object. The Oracle tutorial, [Performing Custom Painting](https://docs.oracle.com/javase/tutorial/uiswing/painting/index.html) will explain how this is done. – Gilbert Le Blanc Jun 16 '21 at 13:38

1 Answers1

0

Generally when creating a game you would have a "game panel" that contains all your game logic. Then you either:

  1. add components to the game panel or
  2. paint objects on the game panel

When using Swing components the components would be created and added to the panel in the constructor of your "GamePanel" class. The basic logic would be something like:

setLayout(null);
label = new JLabel( icon );
label.setSize( label.getPreferredSize() );
label.setLocation(100, 100);
add(label);

Your game logic would then just use label.setLocation(...) to dynamically move the component as required.

Then in your main() method where you create the frame the basic logic would be:

GamePanel panel = new GamePanel();
JFrame frame = new JFrame();
frame.add(panel);
frame.setVisible( true );

However, most people would prefer to paint objects in a game as it is more efficient then creating Swing components. Check out: get width and height of JPanel outside of the class for an example of animation of multiple objects.

camickr
  • 321,443
  • 19
  • 166
  • 288