当前位置: 代码迷 >> J2SE >> 为什么小弟我的keylistener不响应(加入了一个小线程)帮帮小弟我
  详细解决方案

为什么小弟我的keylistener不响应(加入了一个小线程)帮帮小弟我

热度:113   发布时间:2016-04-24 16:19:26.0
为什么我的keylistener不响应(加入了一个小线程)帮帮我
package   thread;

import   java.awt.BorderLayout;
import   java.awt.DisplayMode;
import   java.awt.event.KeyEvent;
import   java.awt.event.KeyListener;

import   javax.swing.ImageIcon;
import   javax.swing.JFrame;
import   javax.swing.JLabel;
import   javax.swing.JSlider;
import   javax.swing.JToolBar;
import   javax.swing.event.ChangeEvent;
import   javax.swing.event.ChangeListener;

public   class   ProtectedScreen   extends   JFrame   implements   Runnable,   KeyListener{

//球左上角坐标
private   int   x;
private   int   y;
//球大小
private   int   ballWidth;
private   int   ballHeight;  
private   int   interval;   //运动幅度
private   int   speed;   //小球运动速度  
private   int   direction;   //小球的运动方向

private   static   int   NW   =   0;
private   static   int   NE   =   1;
private   static   int   SW   =   2;
private   static   int   SE   =   3;

private   JLabel   ball   ;
private   JToolBar   toolBar;  
private   JSlider   slider;

public   ProtectedScreen(){

initToolBar();
initBall();

this.addKeyListener(this);
// this.requestFocus();
// this.requestFocusInWindow();
// this.getContentPane().addKeyListener(this);
// this.getContentPane().requestFocus();
this.getContentPane().setLayout(new   BorderLayout());
this.getContentPane().add(toolBar,   BorderLayout.NORTH);
this.getContentPane().add(ball,   BorderLayout.SOUTH);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(800,   600);
this.setTitle( "屏幕保护 ");
// this.setFullScreen();
}

/* private   void   setFullScreen()   {
  DisplayMode   displayMode;
  displayMode   =   new   DisplayMode(800,   600,   16,
                                DisplayMode.REFRESH_RATE_UNKNOWN);
    SimpleScreenManager   screen   =   new   SimpleScreenManager();
    screen.setFullScreen(displayMode,   this);
}*/

private   void   initBall()   {
x   =   50;  
y   =   50;
ballWidth   =   100;
ballHeight   =   50;
interval   =   5;
speed   =   1000   /   slider.getValue();
ImageIcon   icon   =   new   ImageIcon( "Blue   hills.jpg ");
ball   =   new   JLabel(icon);
ball.setBounds(x,   y,   ballWidth,   ballHeight);
}

private   void   initToolBar()   {
if(toolBar   ==   null)   {
toolBar   =   new   JToolBar();
toolBar.setFloatable(true);
//初始化slider
slider   =   new   JSlider();
slider.setMinimum(1);
slider.setMaximum(100);
slider.setValue(30);
// slider.setExtent(5);
slider.addChangeListener(new   ChangeListener(){

public   void   stateChanged(ChangeEvent   e)   {
speed   =   1000   /   ((JSlider)e.getSource()).getValue();