如何在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);
}
}