标题:java图形界面事件处理
取消只看楼主
winner1995
Rank: 2
等 级:论坛游民
帖 子:64
专家分:41
注 册:2015-10-11
结帖率:88.89%
已结贴  问题点数:20 回复次数:1 
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);
        }
    }

}
搜索更多相关主题的帖子: shijian package public import super 
2017-03-10 10:03
winner1995
Rank: 2
等 级:论坛游民
帖 子:64
专家分:41
注 册:2015-10-11
得分:0 
好  谢啦

唯望君安~
2017-03-28 12:24



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-474917-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.245152 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved