天天看点

十二,图形用户接口

1.GUI

创建GUI程序
监听 事件源和事件
实现按下按钮的功能
1.需要被按下时要执行的方法 
2.检测按钮被按下的方法
监听:如果类想知道按钮的ActionEvent就要实现ActionListener这个接口 按钮会在该事件发生时调用该接口上的方法
public class SimpleGui1 implements ActionListener{   //继承监听接口
	public static void main( String [] args ){
				SimpleGui1 gui = new SimpleGui1();
				gui.go();
		}
		public void go(){
			JFrame frame  = new JFrame();
			JButton button = new JButton( "Click me" );
			button.addActionListener( this );    //添加监听
			frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
			frame.getContentPane().add( button );
			frame.setSize( 300, 300 );
			frame.setVisible( true );
		}
		
		//编译器会确保你实现此接口的actionPerformed();
		public void actionPerformed( ActionEvent event ){
			button.setText( "I have been changed!" );
		}
}
           

2.图形界面

    在GUI上添加东西的方法

1.在frame上放置widget( 按钮,窗体,radiobutton ....)
2.在widget上绘制2D图形
	使用graphics对象绘制图像 graphics.fillOval( 70, 70, 100, 100 ); ...
3.在widget上绘制JPEG图
	graphics.drawImage( myPic, 10,10, this );
           

3.自己创建的绘图组件

创建出具有绘图功能的widget 然后把widget放在frame上
创建JPanle的子类并覆盖掉 paintComponent()这个方法
import java.awt.*;
import javax.swing.*;

class MyDrawPanel extends JPanel{
	public void paintComponent( Graphics g ){
		g.setColor( Color.red );
		g.fillRect( 20, 50, 100, 100 );
	}
}
           

4.内部类

一个类可以嵌套在另一个类的内部只要确定内部内的定义是包在外部内的括号中就可以
class MyOuterClass{
	class MyInnerClass{
		void go();
	}
}
内部类可以使用外部类所有的方法与变量

创建内部类的实例  如果你从外部类的程序代码中初始化内部类,此时内部对象会绑在该外部对象上
现在可以实现两个按钮的程序
public class TwoButtons{
	JFram frame;
	JLable lable;
	public static void main( String [] args ){
			TwoButtons gui = new TwoButtons();
			gui.go();
	}
	
	public void go(){
		frame = new JFrame();
		frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
		
		JButton labelButton = new JButton( "Change Lable" );
		labelButton.addActionListener( new LabelListener() );
		
		JButton colorButton = new JButton( "chang color" );
		colorButton.addActionListener( new ColorButton() );
		
		lable = new JLable( "I am lable");
		MyDrawPanel drawPanle = new  MyDrawPanel();
		
		frame.getContentPane().add( BorderLayout.SOUTH, colorButton );
		frame.getContentPane().add( BorderLayout.CENTER, drawPanle);
		frame.getContentPane().add( BorderLayout.EAST, labelButton);
		frame.getContentPane().add( BorderLayout.WEST, lable);
		
		frame.setSize( 300,  300 );
		frame.setVisible( true );
	}
	
	//声明内部类
	class LabelListener implements ActionListener{
			public void actionPerformed( ActionEvent event){
					Label.setText( "outch" ); 
				}
	} //关闭内部类
	//声明内部类
	class colorButton implements ActionListener{
			public void actionPerformed( ActionEvent event){
					Frame.repaint();
				}
		}
}