0

I am making a platformer game using Java. I have a character in the form of a JLable with an Image Icon that can be moved around using the arrow keys. I am using the setBounds() method to set the position of the JLabel, but this method only takes int values as x and y arguments, and I would like more precise control. Using a null layout, is it possible to use more precise values such as double to position a JLabel?

Thank you for your time, and have a great day.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Think about it. Can you have a half pixel or a 3/4 pixel? (the answer is no) –  May 30 '17 at 23:48

4 Answers4

4

Well if you are using JLabels then you are using Swing, and Swing has non-floating point coordinates system, so no you cannot.

Antoniossss
  • 31,590
  • 6
  • 57
  • 99
2

Looking at the JavaDocs for JLabel...

setLocation takes ints as parameters. There doesn't seem to be a way to use decimal coordinates.

Jeeter
  • 5,887
  • 6
  • 44
  • 67
1

JavaFX can do. However in Swing the coordinates are integer pixels.

You could draw scaled 2x2 in memory (Image getGraphics) and then rescale to achieve half int steps of 0.5; but that would blur (interpolated pixels) or flicker (best nearby match).

For zooming scalable vector graphics, .vg, using the batik library would be feasible.

For text subpixel hinting can on some LED screens position black text on thirds of a pixel, depending on the layout of the Red, Green and Blue subpixels.

In general it is not worth the effort to attempt the above. Except that JavaFX has nice animation support, CSS styling and animation effects.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
1

As others are saying, UI components are designed to position only with exact pixel coordinates.

You could store a location in double and then round it to int when you actually set the location. Something like this:

double velX = ..., velY = ...;
double x    = ..., y    = ...;

void example() {
    int t = 1000 / 30;
    new Timer(t, (ActionEvent e) -> {
        x += t * velX;
        y += t * velY;
        label.setLocation((int) Math.round(x),
                          (int) Math.round(y));
    }).start();
}

That way you can move in smaller increments. It just won't be visible.

There is a really great example of animating an image here in a way very similar to what you're describing which you should take a look at. Trying to position components is really more trouble than it's worth, in my opinion, especially if you're trying to make something like a game. Performing custom painting is more flexible. (The tutorial is here.)

Radiodef
  • 37,180
  • 14
  • 90
  • 125