Java 100-003:利用按钮实现更换背景的效果

package java01;

import java.awt.Color;
import java.awt.event.*;

import javax.swing.*;

/**
 *   我的java每天100行代码003
 *  利用按钮实现更换背景的效果
 * @author Administrator
 *
 */
public class java003{
	public static void main(String[] args) {
		ButtonFrame frame = new ButtonFrame();
		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.pack();
	}
}

class ButtonFrame extends JFrame{
	private JPanel buttonPanel;
	private static final int DEFAULT_WIDTH = 300;
	private static final int DEFAULT_HEIGHT = 200;
	
	public ButtonFrame() {
		setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
		
		JButton yellowButton = new JButton("yellow");
		JButton blueButton = new JButton("blue");
		JButton redButton = new JButton("red");
		
		buttonPanel = new JPanel();
		
		buttonPanel.add(yellowButton);
		buttonPanel.add(blueButton);
		buttonPanel.add(redButton);
		
		add(buttonPanel);
		
		ActionListener yellowAction = new ColorAction(Color.YELLOW);
		ActionListener blueAction = new ColorAction(Color.BLUE);
		ActionListener redAction = new ColorAction(Color.RED);
		
		yellowButton.addActionListener(yellowAction);
		blueButton.addActionListener(blueAction);
		redButton.addActionListener(redAction);
		
	}
	//静态内部类
	private class ColorAction implements ActionListener{
		private Color backgroundColor;
		
		public ColorAction(Color c){
			backgroundColor = c;
		}
		
		public void actionPerformed(ActionEvent e) {
			buttonPanel.setBackground(backgroundColor);
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_43356439/article/details/85019933