小白的JAVA学习笔记(十二)----图形用户接口(3)内部类与多重监听

版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/qq_41641805/article/details/81775660

一、内部类

1、一个类嵌套在另一个类内部,定义完全被外部类包起来就叫内部类

2、内部类可以使用外部类的所有方法与变量,包括有private标记的方法和变量

3、内部类只能任意存取它所属的外部类的内容,但外部类可以有很多内部类

4、内部类可以实现在同一个类中,实现同一个方法两次或者说用不同方法实现同一个接口方法

5、内部类的实例一定绑在外部类的实例上,通过创建外部类实例,再使用外部类实例创建内部类实例

//Author: ZJQ

public class Test {
    
	private int x;
	class Inclass{
		void go() {
			x=55;//内部类可调用外部类的所有变量
		}
	}
    void show() {
    	System.out.println(x);
    }
	public static void main(String[] args) {
		// TODO Auto-generated method stub
       Test t=new Test();
       Test.Inclass inner=t.new Inclass();
       inner.go();
       t.show();
	}

}

 二、实现多重监听(两个按钮的程序)

//Author: ZJQ
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//创建JPanel子类
class DrawPanel extends JPanel{
	public void paintComponent(Graphics g) {
		Graphics2D g2d=(Graphics2D) g;
		int red=(int)(Math.random()*255);
		int green=(int)(Math.random()*255);
		int blue=(int)(Math.random()*255);
		Color start=new Color(red,green,blue);
		red=(int)(Math.random()*255);
		green=(int)(Math.random()*255);
		blue=(int)(Math.random()*255);
		Color end=new Color(red,green,blue);
		GradientPaint gradient=new GradientPaint(30,30,start,100,100,end);
		//第1,2个参数代表起点,第3个参数代表起始颜色,第4,5个参数代表终点,第6个参数代表渐变层最后的颜色
		g2d.setPaint(gradient);//虚拟笔刷设为渐变层
		g2d.fillOval(30, 30, 100, 100);
	}
}
public class Test {
    JFrame frame;
    JButton button1,button2;
    public void go() {
    	frame=new JFrame();
        button1=new JButton("click to change color");
        button1.addActionListener(new ColorListener());
        button2=new JButton("click to change text");
        button2.addActionListener(new TextListener());
    	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	DrawPanel draw=new DrawPanel();
    	frame.getContentPane().add(BorderLayout.WEST,button1);
    	frame.getContentPane().add(BorderLayout.EAST,button2);
    	frame.getContentPane().add(BorderLayout.CENTER,draw);
    	frame.setSize(700, 700);
    	frame.setVisible(true);
    }
    class ColorListener implements ActionListener{
    	public void actionPerformed(ActionEvent event) {
    		frame.repaint();
    	}
    }
    class TextListener implements ActionListener{
    	public void actionPerformed(ActionEvent event) {
    		button2.setText("i've been clicked");
    	}
    }
	public static void main(String[] args) {
		// TODO Auto-generated method stub
        Test t=new Test();
        t.go();
	}

}

注:此时的主要GUI类不再implements接口,也不再实现ActionListener。

       由内部的两个类分别实现监听到不同事件后执行不同的方法,即实现用不同方法实现同一接口方法

                                                                                                                                                        BY   ZJQ

猜你喜欢

转载自blog.csdn.net/qq_41641805/article/details/81775660
今日推荐