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

📄 jtogglebuttontest.java

📁 编程之道--java程序设计入门源代码
💻 JAVA
字号:
/**
 * JToggleButton按钮的测试
 */
import java.awt.Container;
import java.awt.Color;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JToggleButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

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

/**
 * 这是定制自己的按钮框架
 */
class JToggleButtonFrame extends JFrame
{
	private static final int WIDTH = 400;
	private static final int HEIGHT = 300;
	
	public JToggleButtonFrame()
	{
		setSize(WIDTH, HEIGHT);//设置框架的大小		
		setTitle("JToggleButton按钮的测试");//设置框架的标题
		
		Container con = getContentPane();//得到了内容窗格
		
		JPanel centerPanel = new JPanel();
		JPanel westPanel = new JPanel();
		JPanel eastPanel = new JPanel();
		
		westPanel.add(new JButton("WEST"));
		eastPanel.add(new JButton("EAST"));
		
		//设置面板的背景色
		centerPanel.setBackground(Color.gray);
		westPanel.setBackground(Color.gray);
		eastPanel.setBackground(Color.gray);
		
		con.add(centerPanel, BorderLayout.CENTER);
		con.add(westPanel, BorderLayout.WEST);
		con.add(eastPanel, BorderLayout.EAST);
				
		ButtonPanel southPanel = new ButtonPanel(centerPanel, westPanel, eastPanel);//得到定制的面板	
		con.add(southPanel, BorderLayout.SOUTH);//将面板添加到内容窗格中
	}
}

/**
 * 这是继承了JPanel面板类
 */
class ButtonPanel extends JPanel
{
	private JToggleButton yellow;
	private JToggleButton blue;
	private JToggleButton red;
	private JPanel centerPanel;
	private JPanel westPanel;
	private JPanel eastPanel;
		
	public ButtonPanel(JPanel centerPanel, JPanel westPanel, JPanel eastPanel)
	{
		this.centerPanel = centerPanel;
		this.westPanel = westPanel;
		this.eastPanel = eastPanel;
		
		yellow = new JToggleButton("yellow");
		blue = new JToggleButton("blue");
		red = new JToggleButton("red");
		
		//将按钮添加到面板中
		add(yellow);
		add(blue);
		add(red);
		
		//添加按钮事件处理
		ButtonAction action = new ButtonAction();
		yellow.addActionListener(action);
		blue.addActionListener(action);
		red.addActionListener(action);
		
		setBackground(Color.pink);//设置面板的背景颜色
	}
	
	class ButtonAction implements ActionListener
	{
		public void actionPerformed(ActionEvent event)
		{
			if(yellow.isSelected())
				centerPanel.setBackground(Color.yellow);
			else
				centerPanel.setBackground(Color.gray);			
			if (blue.isSelected())
				westPanel.setBackground(Color.blue);
			else
				westPanel.setBackground(Color.gray);
			if (red.isSelected())
				eastPanel.setBackground(Color.red);
			else				
				eastPanel.setBackground(Color.gray);							
		}
	}
}

⌨️ 快捷键说明

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