图形界面系列教材 (五)- Swing 中的组件列表
JAVA的图形界面下有两组控件,一组是awt,一组是swing。
一般都是使用swing
步骤1:标签
步骤2:使用JLabel显示图片
步骤3:按钮
步骤4:复选框
步骤5:单选框
步骤6:按钮组
步骤7:下拉框
步骤8:对话框
步骤9:文本框
步骤10:密码框
步骤11:文本域
步骤12:进度条
步骤13:文件选择器
示例 1 : 标签
Label用于显示文字
|
示例 2 : 使用JLabel显示图片
java GUI 显示图片是通过在label上设置图标实现的
注: 这里的图片路径是e:/project/j2se/shana.png,所以要确保这里有图片,不然不会显示
注: 图片的后缀名和真实格式,必须保持一致,否则很有可能无法正常显示。 什么意思呢?就是文件本来是jpg的,但是仅仅是把后缀名修改成了png,那么会导致显示失败。
|
示例 3 : 按钮
JButton 普通按钮
|
示例 4 : 复选框
JCheckBox 复选框
使用isSelected来获取是否选中了
|
示例 5 : 单选框
JRadioButton 单选框
使用isSelected来获取是否选中了
在这个例子里,两个单选框可以被同时选中,为了实现只能选中一个,还需要用到ButtonGroup
|
示例 6 : 按钮组
ButtonGroup 对按钮进行分组,把不同的按钮,放在同一个分组里 ,同一时间,只有一个 按钮 会被选中
|
示例 7 : 下拉框
JComboBox 下拉框
使用getSelectedItem来获取被选中项
使用setSelectedItem() 来指定要选中项
|
示例 8 : 对话框
JOptionPane 用于弹出对话框
JOptionPane.showConfirmDialog(f, "是否 使用外挂 ?");
表示询问,第一个参数是该对话框以哪个组件对齐
JOptionPane.showInputDialog(f, "请输入yes,表明使用外挂后果自负");
接受用户的输入
JOptionPane.showMessageDialog(f, "你使用外挂被抓住! 罚拣肥皂3次!");
显示消息
|
示例 9 : 文本框
JTextField 输入框
setText 设置文本
getText 获取文本
JTextField 是单行文本框,如果要输入多行数据,请使用JTextArea
tfPassword.grabFocus(); 表示让密码输入框获取焦点
|
示例 10 : 密码框
JPasswordField 密码框
与文本框不同,获取密码框里的内容,推荐使用getPassword,该方法会返回一个字符数组,而非字符串
|
示例 11 : 文本域
JTextArea:文本域。
和文本框JTextField不同的是,文本域可以输入多行数据
如果要给文本域初始文本,通过\n来实现换行效果
JTextArea通常会用到append来进行数据追加
如果文本太长,会跑出去,可以通过setLineWrap(true) 来做到自动换行
|
示例 12 : 进度条
|
示例 13 : 文件选择器
JFileChooser 表示文件选择器
使用FileFilter用于仅选择.txt文件
|
fc.showOpenDialog(); 用于打开文件
fc.showSaveDialog(); 用于保存文件
|