我正试图让这个JLabel移动,我尝试了所有的代码,但它只是不起作用。它似乎永远不会起作用,我已将repaint()
放在任何有意义的地方以及移动代码中,它似乎仍然无法以任何方式工作。我只是没有尝试用导入的图像来做,因为找到一个好的方法也很难。
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
public class Move extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Move frame = new Move();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Move() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel label = new JLabel("");
label.setIcon(new ImageIcon(Move.class.getResource("/images/Untitled-2.png")));
label.setBounds(192, 130, 87, 58);
contentPane.add(label);
label.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent ke) {
if(ke.getKeyCode() == KeyEvent.VK_DOWN) {
label.setLocation(label.getX(),label.getY()+1);
label.repaint();
}
if(ke.getKeyCode() == KeyEvent.VK_UP) {
label.setLocation(label.getX(),label.getY()-1);
label.repaint();
}
if(ke.getKeyCode() == KeyEvent.VK_LEFT) {
label.setLocation(label.getX()+1,label.getY());
label.repaint();
}
if(ke.getKeyCode() == KeyEvent.VK_RIGHT) {
label.setLocation(label.getX()-1,label.getY());
label.repaint();
}
label.repaint();
}
});
}
}
答案 0 :(得分:0)
将KeyListener
附加到Move
实例本身,而不是附加到其中的label
,即只使用以下内容:
addKeyListener(new KeyAdapter() { ...
删除那些冗余的label.repaint();
语句。
将所有内容放在一起时,Move()
构造函数的最后部分应如下所示:
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent ke) {
if (ke.getKeyCode() == KeyEvent.VK_DOWN)
label.setLocation(label.getX(), label.getY() + 1);
if (ke.getKeyCode() == KeyEvent.VK_UP)
label.setLocation(label.getX(), label.getY() - 1);
if (ke.getKeyCode() == KeyEvent.VK_LEFT)
label.setLocation(label.getX() - 1, label.getY());
if (ke.getKeyCode() == KeyEvent.VK_RIGHT)
label.setLocation(label.getX() + 1, label.getY());
}
});