-1

What I want to accomplish is simple, I press a JButton (called 'right') and the x bounds of a JLabel is increased by 100, effectively moving the JLabel 100 pixels to the right. I have been experimenting with stuff such as :

        if(clicked == right) {
            piece.getBounds().x = +100;
        }

and I tried :

        if(clicked == right) {
            piece.addBounds(100,0,0,0);
        }

the method addBounds was undefined for type JLabel so I tried :

        if(clicked == right) {
            piece.setBounds(+100,0,0,0);
        }

and clearly all of the above didn't work, but were worth the try. Is there a way to do what I'm tried to do?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Connor W
  • 21
  • 3
  • It seems this might be better achieved by changing the values of an `EmptyBorder` applied to a single label, or by abandoning using a component completely and doing custom painting of a string or image. What is the ultimate purpose of all this 'moving a label'? See also [What is the XY problem?](http://meta.stackexchange.com/q/66377) – Andrew Thompson Nov 22 '16 at 02:58
  • What's the `LayoutManager` of the component the label lives in? A minimal, complete example would help to help you. – Hendrik Nov 22 '16 at 08:49

2 Answers2

0

The bounds are actually a Rectangle, and so you can get the JLabel's Bounds, advance its x position, and then set the bounds by calling the appropriate methods:

Rectangle bounds = piece.getBounds();  // get the bounds
bounds.x += 100;    // increment the x value
piece.setBounds(bounds);   // re-set the new bounds

repaint();   // call repaint on the container that holds the JLabel so it is repainted
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
0

If I remember correctly, the swing components in Java are required to be repainted when a change is made to them.

Try simply calling the "repaint()" method when the button has been pressed and your changes to the component should update.

A. Cucci
  • 170
  • 10