br451l
br451l

Reputation: 1

Move JButton every click (KeyEvent)

I was trying to create a simple game. For this, i created a JButton that moves down and up, but it only works one time when i click the Down and Up arrows. Can i make it moves every time I click these arrows? I have already tried the while loop, but it didn't work.

Here is the code:

jb = new JButton();
jb.setBounds(40, 40, 60, 40);
jb.setBackground(Color.BLUE);
jb.addKeyListener(new KeyListener() {
    @Override
    public void keyTyped(KeyEvent e) {
        // TODO Auto-generated method stub
    }

    @Override
    public void keyReleased(KeyEvent e) {
        // TODO Auto-generated method stub
    }

    @Override
    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();
        int y = 40;
        if (key == KeyEvent.VK_DOWN) {
            y += 4;
            jb.setBounds(40, y, 60, 40);
        } else if (key == KeyEvent.VK_UP) {
            y -= 4;
            jb.setBounds(40, y, 60, 40);
        }
    }
});

Upvotes: 0

Views: 97

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347332

As already stated by Marcos, you need to know "where" the button is currently, before you update it.

However, I would recommend using the "actual" location of the button instead of some variable, which may not represent the true state, for example...

@Override
public void keyPressed(KeyEvent e) {
    int key = e.getKeyCode();
    int y = jb.getY();
    
    if (key == KeyEvent.VK_DOWN) {
        y += 4;
        jb.setBounds(40, y, 60, 40);
    } 
    else if (key == KeyEvent.VK_UP) {
        y -= 4;
        jb.setBounds(40, y, 60, 40);
    } 
}

Having said that, I would avoid using KeyListener and as a personal preference, try and decouple the workflow.

Instead, I'd make use of the Key Bindings API, and try and make the movement workflow more decoupled (less constrained to the physical control), but, that's me.

Upvotes: 1

Marcos Vasconcelos
Marcos Vasconcelos

Reputation: 18276

You must keep the reference of the older position by changing it scope to the class instead of the method you using:

        int y = 40;
        @Override
        public void keyPressed(KeyEvent e) {
            int key = e.getKeyCode();

This is the necessary to make it work

Upvotes: 1

Related Questions