📄 buttongrouptest.java
字号:
/**
* 单选按钮的测试
*/
import java.awt.Toolkit;
import java.awt.Image;
import java.awt.Dimension;
import java.awt.Container;
import java.awt.Color;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.ButtonGroup;
import javax.swing.JRadioButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ButtonGroupTest
{
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("单选按钮的测试");//设置框架的标题
JPanel centerPanel = new JPanel();
con.add(centerPanel, BorderLayout.CENTER);
ButtonPanel southPanel = new ButtonPanel(centerPanel);
con.add(southPanel, BorderLayout.SOUTH);//将面板添加到内容窗格中
}
}
/**
* 这是继承了JPanel面板类
*/
class ButtonPanel extends JPanel
{
private JPanel centerPanel;
JRadioButton yellow;
JRadioButton blue;
JRadioButton red;
public ButtonPanel(JPanel centerPanel)
{
this.centerPanel = centerPanel;
yellow = new JRadioButton("yellow");
blue = new JRadioButton("blue");
red = new JRadioButton("red");
ButtonGroup group = new ButtonGroup();//生成按钮组对象
//将按钮添加到按钮组对象中
group.add(yellow);
group.add(blue);
group.add(red);
//将按钮添加到面板中
add(yellow);
add(blue);
add(red);
//添加按钮事件处理
ButtonAction action = new ButtonAction();
yellow.addActionListener(action);
blue.addActionListener(action);
red.addActionListener(action);
setBackground(Color.blue);//设置面板的背景颜色
}
class ButtonAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if(yellow.isSelected())
centerPanel.setBackground(Color.yellow);
else if (blue.isSelected())
centerPanel.setBackground(Color.blue);
else if (red.isSelected())
centerPanel.setBackground(Color.red);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -