基本组件
先使用如下代码,设置基本窗口:
import javax.swing.*;
import java.awt.*;
public class Example3{
public static void main(String[] args){
JFrame win = new JFrame("基本组件");
win.setBounds(200,50,360,640);
win.setVisible(true);
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = win.getContentPane();
JPanel pan = new JPanel();
//......
//pan.add(xxx);
}
}
注意:使用命令行窗口执行java程序时,若程序中存在中文字符会导致显示乱码,此时可用utf-8的编码来处理,具体操作如下:
1.标签(JLable)
最简单的组件,用于显示单行静态文本。用户只能查看其内容而不能对其进行修改。标签类没有事件响应。
构造方法:
- JLabel lab = new JLable(“Hello world!!!”);
标签内容一般不需要改变,但也可以使用setText和setIcon方法进行改变
2.按钮(JButton)
构造方法:
- JButton button = new JButton(“登陆”);
常用方法:
- void setActionCommand(String);
- void addActionListener(ActionListener);
3.文本框(JTextField):单行文本
构造方法:
- JTextField tf = new JTextField(“aa”,8);
其他方法:
- public String getText()
- public String getSelectedText()
- public void setText(String s)
- public void setEchoChar(char c)
- public void setEditable(boolean b)
4.文本区(JTextArea):多行文本
构造方法:
- JTextArea ta = new JTextArea(“ab”,8,7);
其他方法:
- public getCaretPosition()
- public void insert(String str,int pos)
- public String getSelectedText()
- public int getSelectionStart()
- public int getSelectionEnd()
- public void replaceRange(String str,int start,int end)
应用中经常将文本区对象放入一个滚动窗格中,以使用滚动条功能,方法为:
JTextArea ta = new JTextArea(int height,int weight);
JScrollPane sp = new JScrollPane(ta);
5.单选按钮(JRadioButton)
构造方法(与JButton类似):
- JradioButton rbutt = new JradioButton(“男”,“true”);
常用方法:
- void addActionListener(ActionListener);
- void addItemListener(ItemListener);
- boolean isSelected();
- void setSelected(boolesan);
使用单选按钮时经常用到ButtonGroup类,如下:
创建按钮对象:
- ButtonGroup bg = new ButtonGroup();
创建若干单选按钮对象:
- JRadioButton b1 = new JRadioButton(“x”);
- JRadioButton b2 = new JRadioButton(“y”);
将各单选按钮添加到按钮组中:
- bg.add(b1);
- bg,add(b2);
将单选按钮添加到其他容器中:
- 容器对象.add(b1);
- 容器对象.add(b2);
注:按钮组维持只有一个单选按钮处于选择状态
6.复选框(JCheckbox)
构造方法:
- JCheckbox() 创建一个没有标签的复选框
- JCheckbox(Icon icon) 创建一个有图标的复选框
- JCheckbox(Icon icon,boolean sele) 创建一个有图标icon的复选框,初始状态为sels
- JCheckbox(String s) 创建一个有标签的复选框
- JCheckbox(String s,boolean b) 创建一个有标签的复选框,参数b设置初始状态
- JCheckbox(String str,Icon icon) 创建一个有str文字及图标icon的复选框
- JCheckbox(String str,Icon icon,boolean sele)创建一个有str文字及图标icon的复选框,初始状态为sele
常用方法:
- isSelected():返回复选框按钮的状态,返回类型是boolean。若放回true,则表示该按钮处于选中状态;否则处于未选中状态
- setSelected(boolean state):设置复选按钮的状态
7.列表框(JList)
构造方法:
- String ss[] = {“red”,“green”,“blue”};
- JList< String > list1 = new JList< String >(ss);
- JList< String > list2 = new JList< String >(Vector);
其他常用方法:
-
void addListSelecttionListener(…);
-
void setVisibleRowCount(int);
-
void setSelectionMode(int);
//取值如下(在ListSelectionModel中定义)
SINGLE_SELECTION
SINCLE_INTERVAL_SELECTION
MULTIPLE_INTERVAL_SELECTION(默认) -
int getSelectedIndex();
-
int[] getSelectedIndices();
-
Object getSelectedValue();
-
Object[] getSelectedValue();
8.下拉列表(JComboBox)
构造方法:
- String ss[] = {“red”,“green”,“blue”};
- JComboBox< String > cb1 = new JComboBox< String >(ss);
- JComboBox< String > cb2 = new JComboBox< String >(Vector);
常用方法:
- addItem() 添加一个项目到JComboBox
- get/setSelectedIndex() 获取/设置JComboBOX中选中项目的索引
- get/setSelectedItem() 获取/设置选中的对象
- removeAllItems() 从JComboBox删除所有对象
- removeItem() 从JComboBox删除特定对象
- setEditable 把一个组合框设置为可编辑的
9.密码域(JPasswordField)
构造方法(类似于JTextField)
- JPasswordField tf = new JPasswordField(“aa”,8);
常用方法:
- void addActionListener(ActionListener);
- char[] getPassword();
- void setEchoChar(char);
- char getEchoChar();
10.滑动条(JSlider)
构造方法:
- JSlider slider = new JSlider(JSlider.HORIZONTAL,0,100,10);
常用方法:
- void addChangeListener(ChangeListener);
- void setValue(int);
- int getValue();
- void setMajorTickSpacing(int);
- void setMinorTickSpacing(int);
- void setPaintTicks(boolean); //false
- void setPaintLabels(boolean); //false
- void setPaintTrack(boolean); //true
- void setSnapToTicks(boolean); //false
11.进度条(JProgressBar)
构造方法:
- JProgressBar(int,int,int);
- JProgressBar pb = new JProgressBar(JProgressBar.HORIZONTAL,0,100);
常用方法:
- void addChangeListener(ChangListener);
- void setValue(int); //设置当前值
- void setString(String); //设置显示的字符串
- void setStringPainted(boolean); //设置是否显示字符串,默认为false
- void setBorderPainted(boolean); //设置是否显示边框,默认为true
12.文件选择器(JFileChooser)
构造方法:
- JFileChooser fc1,fc2; //声明两个对象变量
- fc1 = new JFileChooser(); //使用系统默认目录
- fc2 = new JFileChooser(“d:\java”);
显示方法:
- int showOpenDialog(Component);
- int showSaveDialog(Component);
//分别用于显示标准的打开和保存对话框
//参数Component指定对话框依附的父组件
//返回值:APPROVE_OPTION 选择了确认
CANCEL_OPTION 选择了取消
ERROR_OPTION 出现了错误
其他常用方法:
- void setCurrentDirectory(File);
- void setMultiSelectionEnabled(boolean);
- File getSelectedFile();
- File[] getSelectedFiles();
- File getCurrentDirectory();
- String getName(File):
//取得文件/目录名称,不含路径,可用File类的getAbsolutePath()方法获取完整路径 - void setFileSelectionMode(int);
//FILES_ONLY 只能选择文件(默认)
DIRECTORIES_ONLY 只能选择目录
FILES_AND_DIRECTORIES 文件和目录都可选 - void setFileFilter(FileFilter);
13.颜色选择器(JColorChooser)
显示方法:
使用JColorChooser提供的类方法showDialog
static Color showDialog(
Component, //父组件
String, //标题
Color //初始颜色值
);
//返回值:新选择的颜色值Color
示例:
- Color c = JColorChooser.showDialog(this,“请选择颜色”,Color.red);
//得到颜色对象c后,即可在需要的地方使用
14.对话框(JOptionPane)
Confirm对话框:
int showConfirmDialog(Component,Object);
//显示含有Yes、No、Cancel按钮的确认框
//参数:父组件,显示信息
//返回值:
YES_OPTION 是
NO_OPTION 否
CANCEL_OPTION 撤销
OK_OPTION 确认
CLOSED_OPTION 关闭
Input对话框:
String showInputDialog(Component,Object);
//参数:父组件,显示信息
//返回值:
选择确认后返回输入的字符串
选择取消或关闭后返回null
Message对话框:
- void showMessageDialog(Component,Object);
//参数:父组件,显示信息
//没有返回值,只是用来显示一些信息
Option对话框:
int showOptionDialog(
Component, //父组件
Object, //显示信息
String, //标题
int, //标准选项按钮组类型
int, //标准信息图标类型
Icon, //自定义信息图标
Object[], //自定义选项按钮组
Object //自定义默认的选项按钮
);
15.微调器(JSpinner)
构造方法:
- JSpinner spinner = new JSpinner();
常用方法:
- void addChangeListener(ChangeListener);
- void setValue(Object);
- Object getValue();
- Object getNextValue();
- Object getPreviousValue();
16.计时器(Timer)
构造方法:
- Timer(int,ActionListener);
- Timer timer = new Timer(100,this);
常用方法:
- void start();
- void stop();
- void restar();
- void setDelay(int);
- void setRepeats(boolean);
- boolean isRunning();
17.组件的边框设置边框(Border)
创建边框(使用BorderFactory类的类方法)
- Border border1 = BorderFactory.createLineBorder(Color,int);
//创建一个具有指定颜色和宽度的线边框 - Border border2 = BorderFactory.createTitleBorder(String);
//创建一个新标题边框,采用默认设置,并指定了标题文本 - Border border3 = BorderFactory.createLoweredBevelBorder();
//创建一个具有凹出斜面边缘的边框 - Border border4 = BorderFactory.createRaisedBorder();
//创建一个具有凸出斜面边缘的边框 - Border border5 = BorderFactory.createEtchedBevelBorder();
//创建一个具有“浮雕化”外观效果的边框,将组件的当前背景色用于突出显示和阴影显示
使用setBorder(border)方法是在组件的边框
18.组件的分隔线(JSeparator)设置
构造方法:
- JSeparator separator1 = new JSeparator(); //默认水平
- JSeparator separator2 = new JSeparator(JSeparator.HORIZONTAL);
- JSeparator separator3 = new JSeparator(JSeparator.VERTICAL);
使用add(JSeparator)方法加到合适的位置
19.组件的颜色设置
设置颜色:
默认情况下,Java使用RGB(红/绿/蓝三基色,取值范围[0,255])颜色描述系统
描述颜色的类是java.awt.Color
颜色对象的创建:
- Color c1 = new Color(0,0,255);
- Color c2 = new Color.BLACK; //Color.black
直接使用Color类中定义的标准颜色常量 - Color c3 = JColorChooser.showDialog(Component,String,Color);
有Color对象后,可使用:
- setForeground(Color); //设置组件的前景色
- setBackground(Color); //设置组件的背景色
20.组件的字体设置
字体类:java.awt.Font
字体对象的创建:
- Font(String name,int style,int size);
//名称,如“隶书”
//风格,取值有PLAIN,BOLD,ITALIC
//大小,如 24,38
设置组件的字体:
- setFont(Font);
21.组件的光标设置
光标类:java.awt.Cursor
光标对象的获取:
- Cursor.getPredefinedCursor(int);
//如:DEFAULT_CURSOR、HAND_CURSOR、WAIT_CURSOR、TEXT_CORSOR、CROSSHAIR_CURSOR
设置组件的光标:
- setCursor(Cursor.HAND_CURSOR);
22.中间容器的使用
JPanel
创建对象:
- JPanel p = new JPanel();
默认布局为FlowLayout,可以改变,如
- p.setLayout(new GridLayout(2,3));
添加组件:
- p.add(组件对象);
JScrollPane
- JTextArea ta = new JTextArea(50,50);
- JScrollPane sp = new JScrollPane(ta);
JSplitPane
- JTextArea ta = new JTextArea(50,50);
- JPanel p = new JPanel();
- JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_APLIT,ta,p);
另一种方式:
- JSplitPane sp = new JSplitPane(JSplitPane.VERTICAL_SPLIT,true,ta,p);
JTabbedPane
- JTabbedPane tp = new JTabbedPane();
- tp.setTabPlacement(int);
- tp.addChangeListener(ChangeListener);
- JPanel p = new JPanel();
- tp.addTab(“p”,p);
- tp.removeTabAt(0);
- int n = tp.getTabCount();
- JInternalFrame
根据上面介绍的基本组件,在同一页面实现:
import javax.swing.*;
import java.awt.*;
public class Example3{
public static void main(String[] args){
JFrame win = new JFrame("基本组件");
win.setBounds(200,50,360,640); //设置窗口位置和大小
win.setVisible(true); //设置窗口可见
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置关闭窗口时退出程序
Container con = win.getContentPane();
JPanel pan = new JPanel();
JLabel l_name = new JLabel("姓名"); //设置文本
pan.add(l_name);
JTextField tf_name = new JTextField(26); //设置文本框长度
pan.add(tf_name);
JLabel l_ma = new JLabel("密码");
pan.add(l_ma);
JPasswordField password = new JPasswordField(26);
password.setEchoChar('*'); //设置密码的隐形显示
pan.add(password);
JLabel l_sex = new JLabel("性别");
pan.add(l_sex);
JRadioButton male = new JRadioButton("男",true); //设置单选按钮
JRadioButton female = new JRadioButton("女");
ButtonGroup group = new ButtonGroup();
group.add(male);
group.add(female);
pan.add(male);
pan.add(female);
JLabel l_hobby = new JLabel("爱好");
JCheckBox[] hobby = {new JCheckBox("音乐"),new JCheckBox("书法"),new JCheckBox("绘画")}; //设置多选按钮
pan.add(l_hobby);
pan.add(hobby[0]);
pan.add(hobby[1]);
pan.add(hobby[2]);
JLabel l_course = new JLabel("选课");
pan.add(l_course);
String[] coursesNames = {"Java","Python","Ruby","Go","C++","数据结构","操作系统","网络原理","计算机系统概论"};
JList<String> course; //设置列表框
course = new JList<String>(coursesNames);
pan.add(course);
JLabel l_depar = new JLabel("院系");
pan.add(l_depar);
String[] departmentNames = {"计科","网络工程","物联网","电子信息工程"};
JComboBox<String> department = new JComboBox<String>(departmentNames); //设置复选框
department.setEditable(false); //设置组合框不可编辑
pan.add(department);
JLabel l_lb = new JLabel("年龄");
pan.add(l_lb);
JSpinner jsp = new JSpinner(); //添加年龄微调器
jsp.setValue(new Integer(20));
pan.add(jsp);
con.add(pan);
JLabel l_jf = new JLabel("滑滑滑滑滑动条");
pan.add(l_jf);
JSlider addition = new JSlider(JSlider.HORIZONTAL,0,100,50); //设置滑动条
addition.setMajorTickSpacing(10);
addition.setMinorTickSpacing(5);
addition.setPaintTicks(true);
addition.setPaintLabels(true);
addition.setSnapToTicks(true);
pan.add(addition);
JButton b_sub = new JButton("确认"); //设置按钮
pan.add(b_sub);
JButton b_save = new JButton("保存");
pan.add(b_save);
JTextArea ta = new JTextArea(10,30); //设置为本区
JScrollPane sp = new JScrollPane(ta);
pan.add(sp);
JProgressBar progbar = new JProgressBar(JProgressBar.HORIZONTAL,0,100); //设置进度条
progbar.setStringPainted(true);
pan.add(progbar);
}
}