简体   繁体   中英

Why it doesn't move?

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class Game implements KeyListener {

    static int imgx = 20;
    static int imgy = 20;
    JFrame fen = new JFrame();
    JPanel pan = new JPanel();

    public void display() {

        fen.add(pan);
        fen.addKeyListener(this);
        JLabel img = new JLabel();
        img.setText("zzz");
        img.setBounds(imgx, imgy, 20, 20);
        pan.add(img);
        fen.setVisible(true);
        fen.setSize(480, 272);
    }

    public static void main(String[] args) {
        Game disp = new Game();
        disp.display();
    }

    @Override
    public void keyTyped(KeyEvent e) {
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        if(e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("test");
           imgx -= 10;
           fen.revalidate();
        }
    }


}

Why, when I type left, the label doesn't move itself ? Please help me... I have had a key listener to the JFrame and why it doesn't go to my keyTyped event when I type left on my keyboard ?

Regarding keyListener.

From help of e.getkeyCode() :

Returns the integer keyCode associated with the key in this event. Returns: the integer code for an actual key on the keyboard. (For KEY_TYPED events, the keyCode is VK_UNDEFINED.)

Put your code in keyPressed or keyReleased methods and you will be good to go with code as is.

Worth mentioning is what was stated in this answer: https://stackoverflow.com/a/7071810/2581593 KeyTyped events recognize only printable characters keys, so it won't work with VK_LEFT anyway.

Regarding moving label around.

setBounds() makes sense only if layout of the component you want to put component with bounds is null .

Quoting java documentation once more:

Each JPanel object is initialized to use a FlowLayout, unless you specify differently when creating the JPanel.

In your case to be able to paint label img as given coordinates you need to add: pan.setLayout(null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM