今天的分享内容,有一下三点:
1. 图片按钮
图片按钮 见明知意,我们之前在JLabel中嵌入过图片,这次我们将图片嵌入到按钮当中,然后按钮上就会显示出一个 图片按钮。实现方式很简单,我们在下面写一个简单小demo,以供大家查阅
public class Test1ImageButton extends JFrame {
public static void main(String[] args) {
new Test1ImageButton();
}
public Test1ImageButton(){
Container contentPane = getContentPane();
URL url = Test1ImageButton.class.getResource("tc.jpg");
Icon icon =new ImageIcon(url);
JButton jButton = new JButton();
jButton.setIcon(icon);
jButton.setToolTipText("兔C的图片按钮"); //鼠标悬浮的提示文本
contentPane.add(jButton);
this.setVisible(true);
this.setSize(500,300);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
运行之后,我们会发现 图片变成了一个按钮,并且鼠标悬浮的时候,还会显示我们设置的文本信息。
我这里没放效果图,是因为直至现在,我的图片还是没有显示出来,但是code的确写的没有问题,而且在获取图片的时候 debug 跑 也能读取到图片的存放路径。
这个问题,我还在搞,搞清楚之后,会第一时间分享给大家,也希望大家看到博文的时候,帮我找一下问题,大家集思广益,相互指教,谢谢了。
2. 单选框
玩过了图片按钮,我们来搞一下单选框。
先说一下实现的思路。
- 我们先去获取图片的路径,读到图片之后,我们开始设置按钮
- 单选框的按钮 要用 JRadioButton 这个对象 设置完按钮之后
- 还需要用一下 ButtonGroup 对象,来进行分组的设置,即同时选用一个按钮的效果,创建好对象,将我们创建的 JRadioButton 全部存入到 ButtonGroup 当中
- 在将 JRaidoButton 按钮 全部放入到 contentPane 容器当中 并设置布局
- 基础设置完善
先来看一下效果图:
如图所示,默认是不选中的,选中时 也只能选用一个按钮。
实现代码:
public class Test2Button extends JFrame {
public static void main(String[] args) {
new Test2Button();
}
public Test2Button(){
Container contentPane = getContentPane();
URL url = Test2Button.class.getResource("tc.jpg");
Icon icon = new ImageIcon(url);
JRadioButton jRadioButton1 = new JRadioButton("jRadioButton1");
JRadioButton jRadioButton2 = new JRadioButton("jRadioButton2");
JRadioButton jRadioButton3 = new JRadioButton("jRadioButton3");
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(jRadioButton1);
buttonGroup.add(jRadioButton2);
buttonGroup.add(jRadioButton3);
contentPane.add(jRadioButton1,BorderLayout.CENTER);
contentPane.add(jRadioButton2,BorderLayout.NORTH);
contentPane.add(jRadioButton3,BorderLayout.SOUTH);
this.setVisible(true);
this.setBounds(220,220,620,400);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
3. 多选框
看完了单选框,最后在来看一下多选框的使用,多选框也叫做复选框,概念嘛 也是见名知意,就是可以同时进行多选用的复用效果
如图上展示:
我们在来看一下 code 的实现
public class Test3Button extends JFrame {
public static void main(String[] args) {
new Test3Button();
}
public Test3Button(){
//创建出复选按钮
JCheckBox jCheckBox1 = new JCheckBox("账户");
JCheckBox jCheckBox2 = new JCheckBox("密码");
Container contentPane = getContentPane();
contentPane.add(jCheckBox1,BorderLayout.WEST);
contentPane.add(jCheckBox2,BorderLayout.EAST);
setVisible(true);
setBounds(220,220,640,400);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
很简单吧,其实学习GUI编程,个人感觉都是很基础的东西,当然说的是学习过程中,真去写一些小东西,确实还是有一点点逻辑的,还是比较好玩的,但是在学习过程中,确实没什么难度,无非就是一些记不住的单词,但是在使用上,除了对象不常用 不认识,并没有什么难度,都是差不多的小逻辑。