| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 3410 人关注过本帖
标题:如何在JFrame中添加jpanel,并在jpanel中绘制一个矩形,使用keylistener矩形 ...
取消只看楼主 加入收藏
李胜利
Rank: 1
等 级:新手上路
帖 子:15
专家分:0
注 册:2011-3-24
结帖率:50%
收藏
 问题点数:0 回复次数:1 
如何在JFrame中添加jpanel,并在jpanel中绘制一个矩形,使用keylistener矩形移动?????
package com.lishengli.homework;

import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Paint;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class KeyTest extends JFrame
{

    private JFrame jFrame;
   
    private JPanel jPanel;
   
    private Paint jPanelPanel;
   
    private MyPaint panel;
   
    private Graphics g;
   
    private int x1=20,y1=20,x2=40,y2=40;
   
   

    public KeyTest()
    {
        jFrame = new JFrame("welcome to tianyaleke...");
        panel = new MyPaint(x1,y1,x2,y2);
        
        panel.setFocusable(true);
        jFrame.add(panel);
        jFrame.setSize(400,400);

        jFrame.setDefaultCloseOperation(jFrame.EXIT_ON_CLOSE);
        jFrame.setVisible(true);

        panel.addKeyListener(new KeyAdapter()
        {
            public void keyPressed(KeyEvent e)
            {
                int key = e.getKeyCode();
                System.out.println(e.VK_UP);
                if(key==e.VK_UP)
                {
                    panel.repaint(x1-5,y1,x2-5,y2);
                    
                }
                else if(key==e.VK_DOWN)
                {
                    panel.repaint(x1+5,y1,x2+5,y2);
                }
                else if(key==e.VK_LEFT)
                {
                    panel.repaint(x1,y1-5,x2,y2-5);
                }
                else if(key==e.VK_RIGHT)
                {
                    panel.repaint(x1,y1+5,x2,y2+5);
                }
               
            }
        });
        
    }
   
    public static void main(String[] args)
    {

            EventQueue.invokeLater(new Runnable()
            {        
                public void run()
                {
                    KeyTest kt = new KeyTest();
                    kt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                }
            });

    }

}

class MyPaint extends JPanel
{
    private int x1,y1,x2,y2;
   
    public MyPaint(int x1,int y1,int x2,int y2)
    {
        this.x1 = x1;
        this.x2 = x2;
        this.y1 = y1;
        this.y2 = y2;
    }
    public void paintComponent(Graphics g)
    {
        g.fillRect(x1,y1,x2,y2);
    }
}
搜索更多相关主题的帖子: class 移动 private package public 
2011-11-30 21:39
李胜利
Rank: 1
等 级:新手上路
帖 子:15
专家分:0
注 册:2011-3-24
收藏
得分:0 
这是我写的实现不了,不知道为什么?求高手指教啊
2011-11-30 21:40
快速回复:如何在JFrame中添加jpanel,并在jpanel中绘制一个矩形,使用keylisten ...
数据加载中...
 
   



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

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