java图形界面事件处理
编程目的: 实现在窗口中放置按钮,选中按钮,然后利用键盘上的方向键移动该按钮,当放开方向键时,在文本框中显示按钮左上角的图标出现的问题:选中按钮后按方向键,按钮不会移动
package shijian;
import javax.swing.*;
import java.awt.event.*;
public class Sj11 extends JFrame
{
int x,y;
JButton bt=new JButton("移动我");
JTextField tf=new JTextField(50);
public Sj11(String s)
{
super(s);
setLayout(null);
setBounds(100,100,300,300);
bt.setBounds(30, 30, 80, 20);
bt.addKeyListener(new MyKey());
tf.setBounds(60, 200, 170, 20);
add(bt);
add(tf);
setVisible(true);
setResizable(false);
}
public static void main(String[] args)
{
Sj11 frm=new Sj11("键盘事件");
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class MyKey extends KeyAdapter
{
public void KeyPressed(KeyEvent e)
{
JButton but=(JButton)e.getSource();
x=but.getLocation().x;
y=but.getLocation().y;
if(e.getKeyCode()==KeyEvent.VK_UP)
{
y=y-2;
if(y<=0) y=0;
}
else if(e.getKeyCode()==KeyEvent.VK_DOWN)
{
y=y+2;
if(y>=240) y=240;
}
else if(e.getKeyCode()==KeyEvent.VK_LEFT)
{
x=x-2;
if(x<=0) x=0;
}
else if(e.getKeyCode()==KeyEvent.VK_RIGHT)
{
x=x+2;
if(x>=200) x=200;
}
but.setLocation(x,y);
}
public void KeyReleased(KeyEvent e)
{
String str="按钮左上角现在的位置是("+x+","+y+")";
tf.setText(str);
}
}
}