Java:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class IconBewegtSich extends JFrame {
private JLabel LabelFigur1 = new JLabel();
private ImageIcon LabelFigur1Icon = new ImageIcon(getClass().getResource("images/FigurEins.png"));
public IconBewegtSich() {
super("IconBewegtSich");
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
int frameWidth = 295;
int frameHeight = 300;
setSize(frameWidth, frameHeight);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (d.width - getSize().width) / 2;
int y = (d.height - getSize().height) / 2;
setLocation(x, y);
setResizable(false);
Container cp = getContentPane();
cp.setLayout(null);
// start components
LabelFigur1.setBounds(88, 48, 81, 65);
LabelFigur1.setText("");
LabelFigur1.setIcon(LabelFigur1Icon);
cp.add(LabelFigur1);
// end components
setVisible(true);
}
public static void main(String[] args) {
new IconBewegtSich();
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
LabelFigur1.setLocation(LabelFigur1.getLocation().x +5, LabelFigur1.getLocation().y);
} else if (e.getKeyCode() == KeyEvent.VK_LEFT){
LabelFigur1.setLocation(LabelFigur1.getLocation().x -5, LabelFigur1.getLocation().y);
} else if(e.getKeyCode() == KeyEvent.VK_DOWN) {
LabelFigur1.setLocation(LabelFigur1.getLocation().x, LabelFigur1.getLocation().y+5);
} else if(e.getKeyCode() == KeyEvent.VK_UP) {
LabelFigur1.setLocation(LabelFigur1.getLocation().x, LabelFigur1.getLocation().y -5);
}
}
public void keyReleased(KeyEvent e) {
}
// end methods
} // end of class IconBewegtSich
Ich möchte ein jLabel auf Knopfdruck beliebeig bewegen. Der Code hat keine "fehler", aber mein Label bewegt sich nicht.