3

Basically, I'm trying to move a JButton (or even a JLabel) inside a frame using the arrow keys. I've successfully figured out the part to detect the arrow key presses. Now all i want to do is to change the position of the button (or label) depending on the key pressed.

E.G. when I press the "UP" key, the button/label should move up by say 5 pixels. I couldn't find the property to change the position of the button.

Do I need to put button/label inside the panel or something like that?

Please help, its not a homework, just curious :)

4
  • What is the purpose of any of this? Jun 3, 2012 at 6:32
  • Lets say there is a maze. I want to allow user to move the jButton/jLabel through the maze using arrow keys.
    – md1hunox
    Jun 3, 2012 at 6:35
  • 4
    Don't use a label or button. Use a raw image and paint it wherever needed in a custom component. Jun 3, 2012 at 6:36
  • 2
    Rather consider this WONDERFUL EXAMPLE, SHARED BY @trashgod, which uses KeyBinding instead of KeyListeners, since you using Swing and not AWT and this simple example
    – nIcE cOw
    Jun 3, 2012 at 11:59

2 Answers 2

1

How I would do it is to use the Graphics instead of a Panel. So the bit of code that draws it could be:

    public class panel extends JPanel{
public int X = 50; //Starting x
public int Y = 50; //Starting y
public panel(){

}
public void paintComponent(Graphics g){
    super.paintComponent(g);
    this.setBackground(Color.WHITE);
    g.drawString("Hello this will be moved", X, Y);//<--- This draws the text
}

}

This bit of code will draw the text and repeatedly draw it. All you have to do is in the Key Listener or what ever was used, do;

  X++;

or:

  Y++;

That will add 1 everytime. So when you press the key it is moved one x pixel or y pixel or back or forth, depending on the ++ or --. Then add this to the JFrame and it will draw it on screen.

0

use of a raw image is much better in the application i'm doing but here is something that i accidently found while doing it ;)

This infact can be done by absolute positioning of label(dont know about button) ie. without use of any Layout Manager. all we have to do is the follwing:

setLayout(null);
Jlabel testLabel = new JLabel("Test Moving label");

now with that done. we have to set

testLabel.setBounds(XCoord+ insets().left, yCoord+ insets().top, 150, 25);

here xCoord and yCoord are the coordinates of the top left pixel of the label. the above line can be added to the actionListener. in my case its the action for pressing UP, RIGHT and LEFT arrow keys. we can increment and decrement the xCoord and yCoord accordingly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.