Java事件处理机制的两个案例

第一个案例,实现按钮控制面板颜色

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class Test extends JFrame implements ActionListener{

    public static void main(String[] args) {
    	
    	// TODO, add your application code
    	Test test=new Test();	
    }
    JPanel jp=null;
    JButton jb1=null;
    JButton jb2=null;
    public Test()
    {
    	jp=new JPanel();
    	jb1=new JButton("黑色");
    	jb1.addActionListener(this);
    	jb2=new JButton("红色");
    	jb2.addActionListener(this);
    	this.add(jb1,BorderLayout.NORTH);
    	this.add(jp);
    	this.add(jb2,BorderLayout.SOUTH);
    	this.setSize(400,300);
    	this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	this.setVisible(true);
    }
    
    public void actionPerformed(ActionEvent e)
    {
    	if(e.getSource()==jb1)
    	{
    		jp.setBackground(Color.black);	
    		System.out.println("Black");
    	}else if(e.getSource()==jb2)
    	{
    		jp.setBackground(Color.red);
    	}
    }
}

第二个案例,实现小球的上下左右移动

在这里插入图片描述

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class Test extends JFrame  {

    public static void main(String[] args) {
    	
    	// TODO, add your application code
    	Test test=new Test();	
    }
    GamePanel gp=null;
    public Test()
    {
    	gp=new GamePanel();
    	this.addKeyListener(gp);
    	this.add(gp);
    	this.setSize(400,300);
    	this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	this.setVisible(true);
    }
}
class GamePanel extends JPanel implements KeyListener
{
	int x=10;
	int y=10;
	int speed=5;
	public void paint(Graphics g)
	{
		super.paint(g);
		g.setColor(Color.black);
		g.fillRect(0,0,400,300);
		g.setColor(Color.green);
		g.fillOval(x,y,20,20);
	}

	public void keyReleased(KeyEvent e)
	{
		
	}
	public void keyTyped(KeyEvent e)
	{
		
	}
	public void keyPressed(KeyEvent e)
	{
		if(e.getKeyCode()==KeyEvent.VK_UP)
		{
			System.out.println("UP");
			y-=speed;
		}else if(e.getKeyCode()==KeyEvent.VK_DOWN)
		{
			y+=speed;
		}else if(e.getKeyCode()==KeyEvent.VK_LEFT)
		{
			x-=speed;
		}else if(e.getKeyCode()==KeyEvent.VK_RIGHT)
		{
			x+=speed;
		}
		this.repaint();
	}	
}

猜你喜欢

转载自blog.csdn.net/AnalogElectronic/article/details/88784440