⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 buttoneventtest3.java

📁 JSF 演示代码
💻 JAVA
字号:
/**
 * 利用按钮动作控制面板背景色
 */
import java.awt.Toolkit;
import java.awt.Image;
import java.awt.Dimension;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class ButtonEventTest3
{
	public static void main(String[] args)
	{
		ButtonFrame frame = new ButtonFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.show();
	} 
}

/**
 * 这是定制自己的按钮框架
 */
class ButtonFrame extends JFrame
{
	private static final int WIDTH = 400;
	private static final int HEIGHT = 300;
	
	public ButtonFrame()
	{
		Container con = getContentPane();//得到了内容窗格
		
		Toolkit kit = Toolkit.getDefaultToolkit();
		Dimension screenSize = kit.getScreenSize();
		int width = screenSize.width;
		int height = screenSize.height;
		int x = (width - WIDTH)/2;
		int y = (height - HEIGHT)/2;
		setLocation(x, y);//设置坐标起点
		setSize(WIDTH, HEIGHT);//设置框架的大小
		Image image = kit.getImage("duke.gif");// duke.gif为图像文件名
		setIconImage(image);//设置框架图标
		setTitle("按钮改变面板的背景色");//设置框架的标题
		setResizable(false);//设置用户不可以改变框架的大小
		
		ButtonPanel panel = new ButtonPanel();//得到定制的面板
		con.add(panel);//将面板添加到内容窗格中
	}
}

/**
 * 这是继承了JPanel面板类
 */
class ButtonPanel extends JPanel
{
	public ButtonPanel()
	{
		makeButton("yellow", Color.yellow);
		makeButton("blue", Color.blue);
		makeButton("red", Color.red);

	}
	
	private void makeButton(String buttonName, Color backgroundColor)
	{
		JButton button = new JButton(buttonName);
		add(button);
		ColorAction action = new ColorAction(backgroundColor);
		button.addActionListener(action);
	}

	
	/**
	 * 这是实现了动作监听器接口的内部类
	 */
	private class ColorAction implements ActionListener
	{
		private Color backgroundColor;
		
		public ColorAction(Color c)
		{
			backgroundColor = c;
		}
		
		//当产生某个动作时,会自动调用该方法,实现背景色的设定
		public void actionPerformed(ActionEvent event)
		{
			setBackground(backgroundColor);
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -