|
3Java金币
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class shili extends JFrame implements KeyListener{
//定义jpanel主件rect
Rect rect=null;
Rect Rect1=null;
JButton jbutton=null;
//定义构造方法
public shili()
{
//实例化面板主件
rect=new Rect();
Rect1=new Rect();
jbutton=new JButton("ooooo");
//在JFrame窗体中添加面板主键
this.add(rect);
//this.add(rect1);
this.add(jbutton,BorderLayout.SOUTH);
this.add(Rect1,BorderLayout.EAST);
// simevent.addActionListener(rect);
//设置窗体属性
this.setSize(300, 200);
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
this.setVisible(true);
jbutton.addActionListener(rect);
this.addKeyListener(rect);---------------一直怀疑问题出现在这里,但又不知道怎么改,整个程序按钮监听没有任何问题,但是键盘监听就没反应
}
public static void main(String args[])
{
// 向控制台输出信息
System.out.println("1");
//实例化JFrame窗体主件实例
shili shili=new shili();
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
//定义画板类Rect ----------------画出矩形,并且实现监听
class Rect extends JPanel implements ActionListener , KeyListener {
int x=2;
int y=3;
public Rect(){
}
//实现JPane的paint方法
public void paint (Graphics g){
//这个方法不可少
super.paint(g);
for(int i=1;i<3;i++)
{
g.drawRect(x,y,30,20);
System.out.println(x);
}
}
@Override
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
this.x++;
this.repaint();
System.out.println(x);
}
@Override
public void keyTyped(KeyEvent e)
{
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e)
{
// TODO Auto-generated method stub
if(e.getKeyCode()==KeyEvent.VK_RIGHT)
{x++;
System.out.println(x);
}
else if(e.getKeyCode()==KeyEvent.VK_UP)
{
y--;
}
else if(e.getKeyCode()==KeyEvent.VK_DOWN)
{
y++;
}
else if(e.getKeyCode()==KeyEvent.VK_LEFT)
{
x--;
}
this.repaint();// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
|
|