import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;public class KeyMoveBackground extends JFrame{
private JLabel label;
public KeyMoveBackground(){
super();
this.setResizable(false);
this.setVisible(true);
Container c = this.getContentPane();
this.setTitle("方向键移动背景");
this.setBounds(100,100,500,375);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel();
ImageIcon icon = new ImageIcon(getClass().getResource("Penguins.jpg"));
ImageIcon glassImg = new ImageIcon(getClass().getResource("QQ截图20120303162426.png"));
label.setIcon(icon);
label.setSize(icon.getIconWidth(),icon.getIconHeight());
label.setLocation(-icon.getIconWidth()/3,-icon.getIconHeight()/3);
c.add(label);
JLabel glassLabel = new JLabel(glassImg);
JPanel glassPane = new JPanel(new BorderLayout());
glassPane.add(glassLabel);
glassPane.setOpaque(false);
this.setGlassPane(glassPane);
this.getGlassPane().setVisible(true);
this.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
do_label_keyPress(e);
}
});

}
 
protected void do_label_keyPress(final KeyEvent e){
int code = e.getKeyCode();
Point location = label.getLocation();
int step=3;
switch(code){
case KeyEvent.VK_RIGHT:
if(location.x > (getWidth() - label.getWidth()))
label.setLocation(location.x-step,location.y);
break;
case KeyEvent.VK_LEFT:
if(location.x<0)
label.setLocation(location.x+step,location.y);
break;
case KeyEvent.VK_UP:
if(location.y < 0)
label.setLocation(location.x,location.y+step);
break;
case KeyEvent.VK_DOWN:
if(location.y > (getHeight()-label.getHeight()))
label.setLocation(location.x, location.y+step);
break;
default:
break;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new KeyMoveBackground();
}}