2
所以我試圖讓一個JLabel(「玩家」)在我選擇的方向上移動10個像素,正如你可以在下面的代碼中看到的一樣,但我無法做到工作。我已經運行了它,並按下了一個箭頭鍵,但沒有發生任何事情,所以我希望你們可以幫助我^^。不能用箭頭鍵移動JLabel
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Random;
public class Main extends JFrame {
JLabel player = new JLabel();
JLabel separator = new JLabel();
JLabel object = new JLabel();
public Main() {
setSize(400, 500);
setLayout(null);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setTitle("BenTY");
separator.setOpaque(true);
separator.setBackground(Color.black);
separator.setBounds(0, 400, 400, 1);
add(separator);
player.setBackground(Color.black);
player.setOpaque(true);
player.setBounds(195, 390, 10, 10);
player.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent ke)
{
if(ke.getKeyCode() == KeyEvent.VK_DOWN)
{
player.setBounds(player.getX(), player.getY()+10, 10, 10);
repaint();
}
if(ke.getKeyCode() == KeyEvent.VK_UP)
{
player.setLocation(player.getX(), player.getY() - 10);
repaint();
}
if(ke.getKeyCode() == KeyEvent.VK_LEFT)
{
player.setLocation(player.getX()-10,player.getY());
repaint();
}
if(ke.getKeyCode() == KeyEvent.VK_RIGHT)
{
player.setLocation(player.getX()+10,player.getY());
repaint();
}
}
});
add(player);
Random random = new Random();
int oLocationX = random.nextInt(40) * 10;
int oLocationY = random.nextInt(40) * 10;
object.setBackground(Color.red);
object.setOpaque(true);
object.setBounds(oLocationX, oLocationY, 10, 10);
add(object);
}
public static void main(String[] args) {
Main ui = new Main();
ui.setVisible(true);
}
}
的編碼差BTW遺憾:d
'順便說一句編碼差的問題:D':使用一致的括號放置(相同的行與下一行)將會是一個更好的代碼開始。否則,不要原諒它!你來這裏學習! – tilpner