实训作业-------窗口

编写一个通过按钮给窗口转换颜色的程序。

package computerOperation;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class YouColor implements ActionListener {
	JFrame f;
	JPanel p1,p2;
	JButton b[];
	String a[] = {"红色","绿色","蓝色"};
	
	public void ColorLayout(){
		f = new JFrame();
		p1 = new JPanel();
		f.add(p1,BorderLayout.NORTH);
		b = new JButton[a.length]; 
		for(int i = 0; i < a.length ; i++ ){
			b[i] = new JButton(a[i]);
			b[i].addActionListener(this);
			p1.add(b[i]);
		}
		p2 = new JPanel();
		f.add(p2, BorderLayout.CENTER);
		f.setVisible(true);
		f.setSize(400, 300);
		f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		
	}
	
	public static void main (String[] args){
		new YouColor().ColorLayout();
	}

	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == b[0]){
			p2.setBackground(Color.red);
		}
		else if(e.getActionCommand().equals("绿色")){
			p2.setBackground(Color.green);
		}
		else{
			p2.setBackground(Color.blue);
		}
	}

}

个人感想:

初步学会了如何创建事件处理,以及获取事件源

posted @ 2019-06-14 21:08  爱的晚上  阅读(101)  评论(0编辑  收藏  举报