当前位置: 代码迷 >> J2SE >> 一个让label在背景图片上移动的程序,不知道为什么不能接受键盘的消息解决方法
  详细解决方案

一个让label在背景图片上移动的程序,不知道为什么不能接受键盘的消息解决方法

热度:56   发布时间:2016-04-24 01:06:02.0
一个让label在背景图片上移动的程序,不知道为什么不能接受键盘的消息
Java code
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();    }}


------解决方案--------------------
把do_label_keyPress里面的if语句去掉就能移动了,应该是楼主你的if语句有问题吧
  相关解决方案