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

📄 fourbutton.java

📁 编程之道--java程序设计入门源代码
💻 JAVA
字号:
/**
 * 显示四个不同外观的按钮
 */
import java.awt.Toolkit;
import java.awt.Image;
import java.awt.Dimension;
import java.awt.Container;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class FourButton
{
	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("四个不同外观的按钮");//设置框架的标题
				
		ButtonPanel panel = new ButtonPanel();//得到定制的面板
		con.add(panel);//将面板添加到内容窗格中
	}
}

/**
 * 这是继承了JPanel面板类
 */
class ButtonPanel extends JPanel
{
		
	public ButtonPanel()
	{
		//默认的按钮
		JButton defaultButton = new JButton();
		//带有图标的按钮
		JButton iconButton = new JButton(new ImageIcon("duke.gif"));
		//带有标签的按钮
		JButton textButton = new JButton("有标签的按钮");
		//带有标签与图标的按钮
		final JButton textAndIconButton = new JButton("标签", new ImageIcon("duke.gif"));
		
		defaultButton.addActionListener(new PanelColorAction(Color.yellow));
		iconButton.addActionListener(new PanelColorAction(Color.black));
		
		//利用匿名内部类实现另一个按钮背景颜色的改变
		textButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent event)
			{
				Color buttonColor = textAndIconButton.getBackground();
				if(buttonColor == Color.pink)
					textAndIconButton.setBackground(Color.red);
				else
					textAndIconButton.setBackground(Color.pink);
			}});
		//将按钮添加到面板中
		add(defaultButton);
		add(iconButton);
		add(textButton);		
		add(textAndIconButton);
		
		setBackground(Color.blue);//设置面板的背景颜色
	}
	
	/**
	 * 这是实现了面板背景颜色的改变
	 */
	private class PanelColorAction implements ActionListener
	{
		private Color backgroundColor;
		
		public PanelColorAction(Color c)
		{
			backgroundColor = c;
		}
		
		//实现面板背景色的设定
		public void actionPerformed(ActionEvent event)
		{
			setBackground(backgroundColor);
		}
	}	
}

⌨️ 快捷键说明

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