当前位置:课程学习>>第八章 图形界面程序设计>>文本学习>>知识点二
Swing是用于图形用户界面开发的一个全面解决方案,包括250多个类,在这里不能一一列出。本书仅使用Swing用户界面。
一、标签
标签类JLabel是用于显示文字或图标的简单组件。JLabel的构造方法包括:
public JLabel()
public JLabel(Icon icon)
public JLabel(Icon icon, int horizontalAlignment)
public JLabel(String text)
public JLabel(String text, Icon icon, int horizontalAlignment)
public JLabel(String text, int horizontalAlignment)
在构造方法中,text指定标签的文字,icon指定标签的图标,horizontalAlignment指定文本或图标的水平对齐方式。
JLabel实例维护的属性包括:
表8.3 JLabel的属性
属性名 |
数据类型 |
访问 |
缺省值 |
disabledIcon |
Icon |
SG |
灰色过滤图标 |
displayedMnemonic |
Int |
SG |
—— |
horizontalAlignment |
Int |
CSG |
LEFT |
horizontalTextPosition |
Int |
SG |
RIGHT |
Icon |
Icon |
CSG |
null |
iconTextGap |
Int |
SG |
4个像素 |
labelFor |
Component |
SG |
null |
Text |
String |
CSG |
“” |
verticalAlignment |
Int |
SG |
CENTER |
verticalTextPosition |
int |
SG |
CENTER |
注:在访问中,C=可在构造时设置/G=获取方法/S=设置方法
disabledIcon:标签被禁用时显示的图标。
displayedMnemonic:设置LabelFor属性后显示的助记符。
horizontalAlignment:标签内容的水平对齐方式。取值包括:SwingConstants.LEFT、SwingConstants.RIGHT和SwingConstants.CENTER。
horizontalTextPosition:文本相对于图标的水平位置;与水平对齐方式的有效值相同。
icon:标签在启用时显示的图标。
iconTextGap:标签的文本与图标之间的间隙,以像素点为单位。
labelFor:一个组件,它在标签的助记符被键入时获得焦点。
Text:标签显示的文本。
verticalAlignment:标签内容的垂直对齐方式。取值包括:SwingConstants.TOP、SwingConstants.BOTTOM和SwingConstants.CENTER。
【例8.8】建立JLabel的实例
//JLabelTest.java
import javax.swing.*;
import java.awt.*;
public class JLabelTest extends JFrame {
Icon icon = new ImageIcon("icon.gif");
JLabel defaultLabel = new JLabel(),
textLabel = new JLabel("text"),
textIconLabel = new JLabel("text", icon, SwingConstants.CENTER),
iconLabel = new JLabel(icon);
public JLabelTest() {
getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER, 25, 25));
getContentPane().add(defaultLabel);
getContentPane().add(textLabel);
getContentPane().add(textIconLabel);
getContentPane().add(iconLabel);
}
public static void main(String[] args) {
JLabelTest frame = new JLabelTest();
frame.setTitle("JLable Test");
frame.setSize(400, 150);
frame.setVisible(true);
}
}
运行结果:
在实例中显示了四个标签组件,分别是默认标签(空)、文本标签、图标和文本标签、图标标签。
二、按钮
按钮类是Swing的重要组成部分,JButton类实现了按钮抽象。JButton的构造方法包括:
public JButton()
public JButton(Icon icon)
public JButton(String text)
public JButton(String text, Icon icon)
在构造方法中,text指定按钮上的文本,icon指定按钮上的图标。
JButton实例维护的属性包括:
表8.4 JButton的属性
属性名 |
数据类型 |
访问 |
缺省值 |
actionCommand |
String |
SG |
按钮文本 |
borderPainted |
boolean |
SG |
true |
defaultButton |
boolean |
G |
false |
defaultCapable |
boolean |
SG |
true |
disabledIcon |
icon |
SG |
灰色图标 |
focusPainted |
boolean |
SG |
true |
horizontalAlignment |
int |
SG |
CENTER |
horizontalTextPosition |
int |
SG |
RIGHT |
Icon |
icon |
CSG |
null |
Label |
String |
CSG |
“” |
Margin |
Insets |
SG |
0 |
Mnemonic |
int |
SG |
—— |
Model |
ButtonModel |
SG |
DefaultButtonModel |
pressedIcon |
Icon |
SG |
null |
rolloverIcon |
Icon |
SG |
null |
Selected |
boolean |
SG |
false |
Text |
String |
CSG |
“” |
verticalAlignment |
int |
SG |
CENTER |
verticalTextPosition |
int |
SG |
CENTER |
注:在访问中,C=可在构造时设置/G=获取方法/S=设置方法
actionCommand:字符串,标识与一个按钮相关的命令。缺省值为该按钮的文本。
borderPainted:确定是否绘制按钮的边框。
defaultButton:指示按钮是否为根窗格的缺省按钮。
defaultCapable:指示按钮是否能作为根窗格的缺省按钮。
disabledIcon:按钮禁用时显示的图标。缺省时图标为该按钮的灰色版本。
focusPainted:当按钮具有焦点时,是否绘制一个焦点指示标志。
horizontalAlignment:按钮内容的水平对其方式,取值为JButton.LEFT、JButton.RIGHT和JButton.CENTER。
horizontalTextPosition:文本相对于图标的水平位置。
icon:按钮上显示的图标。
label:按钮上显示的文本。可以用text属性代替。
margin:按钮的边框与其内容之间的间隙。
mnemonic:用于激活按钮的热键。
model:按钮的模型。
pressedIcon:当按钮按下时显示的图标。
rolloverIcon:当光标进入按钮时显示的图标。
selected:从AbstractAction继承而来,对JButton的实例没有意义。
text:按钮上显示的文本。
verticalAlignment:文本相对于图标的垂直对其方式。
verticalTextPosition:文本相对于图标的垂直位置。
按钮所支持的监听器接口为:ActionListener。
【例8.9】使用按钮组件的实例。
//JButtonTest.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JButtonTest extends JFrame implements ActionListener {
Icon icon = new ImageIcon("icon.gif");
private JButton defBtn = new JButton("default button", icon);
private JButton regBtn = new JButton("regular button");
public JButtonTest() {
getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER, 25, 25));
getContentPane().add(defBtn);
getContentPane().add(regBtn);
getRootPane().setDefaultButton(defBtn);
defBtn.setActionCommand("default");
regBtn.setActionCommand("regular");
defBtn.addActionListener(this);
regBtn.addActionListener(this);
}
public static void main(String[] args) {
JButtonTest frame = new JButtonTest();
frame.setTitle("JButton Test");
frame.setSize(400, 150);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("default")) {
JOptionPane.showMessageDialog(this, "Click default button!");
}
if (e.getActionCommand().equals("regular")) {
JOptionPane.showMessageDialog(this, "Click regular button!");
}
}
}
运行结果:
在例子中,为框架添加了两个按钮,其中default button包含图标,且设定为默认按钮,而regular button仅为一般的文字按钮。为了响应按钮点击事件,分别为两个按钮设置了actionCommand属性,目的是在actionPerformed方法中作不同处理。点击不同的按钮将显示相应的消息对话框。
三、文本域
JTextField组件显示单行可编辑文本,它只使用单一字体和颜色。它的构造方法包括:
public JTextField()
public JTextField(int columns)
public JTextField(String initialString)
public JTextField(String initialString, int columns)
initialString指定了文本域的默认文本,columns指定了文本域的宽度。JTextField实例维护的属性包括:
表8.5 JTextField的属性
属性名 |
数据类型 |
访问 |
缺省值 |
actionCommand |
String |
SG |
text field text |
Columns |
int |
SG |
0 |
horizontalAlignment |
int |
SG |
LEFT |
horizontalVisibility |
BoudedRangeModel |
G |
BoundedRangeModel |
scrollOffset |
int |
SG |
0 |
注:在访问中,C=可在构造时设置/G=获取方法/S=设置方法
actionCommand:当单行文本域激发一个动作事件时,该属性被设置为这个事件的动作命令。缺省值为单行文本域的内容。
columns:列宽被设置为文本域中当前字体的字符m的宽度。
horizontalAlignment:文本域内显示的文本的水平对齐方式。取值为JTextField.LEFT、TextField.CENTER和JTextField.RIGHT。
horizontalVisibility:确定文本域的哪个部分是可视的。
scrollOffset:确定单行文本域的哪个部分是可视的。滚动偏移由单行文本域的水平可视性作为可视值来维护。
【例8.10】使用文本域组件的实例。
//JTextFieldTest.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JTextFieldTest extends JFrame implements ActionListener {
private JTextField conText = new JTextField("Please input text: ", 20);
private JButton btn = new JButton("OK");
public JTextFieldTest() {
getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER, 25, 25));
getContentPane().add(conText);
getContentPane().add(btn);
btn.setActionCommand("btn");
btn.addActionListener(this);
}
public static void main(String[] args) {
JTextFieldTest frame = new JTextFieldTest();
frame.setTitle("JTextField Test");
frame.setSize(400, 150);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("btn"))
JOptionPane.showMessageDialog(this, conText.getText());
}
}
运行结果:
实例中包含一个文本域,默认的文本为”Please input text: ”,点击按钮后弹出消息对话框,显示文本域的内容。JTextField的getText方法能够获得文本域的内容。
JPasswordField是JTextField的派生类,实现文本域的字符隐藏功能。
JPasswordField的构造方法与JTextField类似。
JPasswordField实例所维护的属性包括:
表8.6 JPasswordField的属性
属性名 |
数据类型 |
访问 |
缺省值 |
echoChar |
char |
SG |
与界面的样式有关 |
Password |
char[] |
G |
—— |
注:在访问中,C=可在构造时设置/G=获取方法/S=设置方法
echoChar:输入字符时在口令域中显示的字符。
password:字符数组,包含输入到口令域中的字符。
在JPasswordField中,需要调用getPassword方法来获得口令域的内容。
四、文本区
文本区组件JTextArea作为多行文本域,可以显示多行纯文本。它的构造方法包括:
public JTextArea()
public JTextArea(int rows, int cols)
public JTextArea(String initialString)
public JTextArea(String initialString, int rows, int cols)
其中,initialString指定文本区的文字,rows和cols分别指定了行数和列数。
JTextArea实例维护的属性包括:
表8.7 JTextArea的属性
属性名 |
数据类型 |
访问 |
缺省值 |
Columns |
int |
CSG |
0 |
lineCount |
int |
G |
0 |
lineWrap |
boolean |
SG |
false |
Rows |
int |
SG |
0 |
tabSize |
int |
SG |
from document |
wrapStyleWord |
boolean |
SG |
false |
注:在访问中,C=可在构造时设置/G=获取方法/S=设置方法
columns:文本区的显示列数。类似地,列宽是多行文本区的当前字体的m字符的宽度。
lineCount:文本区中包含的文本行数。
lineWrap:决定文本是否能在文本区的右边界处实现换行。换行类型由wrapStyleWord属性来确定。
rows:文本区中显示的文本行数。
tabSize:按下Tab键时所能插入的字符数。
wrapStyleWord:取值为true时,以单词为界进行换行;取值为false时,以字符为界进行换行。
【例8.11】使用文本区组件的实例。
//JTextAreaTest.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JTextAreaTest extends JFrame implements ActionListener {
private JTextArea area = new JTextArea(4, 20);
private JPanel p = new JPanel();
private JButton btn1 = new JButton("no wrap");
private JButton btn2 = new JButton("word wrap");
private JButton btn3 = new JButton("char wrap");
public JTextAreaTest() {
p.setLayout(new FlowLayout(FlowLayout.CENTER, 2, 8));
p.add(btn1);
p.add(btn2);
p.add(btn3);
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
getContentPane().add(area, BorderLayout.NORTH);
getContentPane().add(p, BorderLayout.CENTER);
}
public static void main(String[] args) {
JTextAreaTest frame = new JTextAreaTest();
frame.setTitle("JTextArea Test");
frame.setSize(280, 140);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("no wrap")) {
area.setLineWrap(false);
}
if (e.getActionCommand().equals("word wrap")) {
area.setLineWrap(true);
area.setWrapStyleWord(true);
}
if (e.getActionCommand().equals("char wrap")) {
area.setLineWrap(true);
area.setWrapStyleWord(false);
}
}
}
运行结果:
(a) 不换行
(b) 按单词换行
(c) 按字符换行
实例中包含一个文本区,三个按钮分别设置文本区换行的方式。
五、列表框
Swing的列表框类JList显示一个可选取对象列表。它支持三种选取模式:单选取、单间隔选取和多间隔选取。JList组件的主要工作:数据处理、项选取和单元绘制分别委托ListModel、ListSelectionModel和ListCellRenderer等接口来完成。
JList的构造方法包括:
public JList(Object [] stringItems)
public JList(Vector stringItems)
在构造方法中,stringItems指定列表项。
JList实例维护的属性非常多,其中涉及到选取的属性包括:
表8.8 JList的属性
属性名 |
数据类型 |
访问 |
缺省值 |
selectedIndex |
int |
SG |
-1 |
selectedIndices |
int [] |
SG |
int [0] |
selectedValue |
Object |
SG |
null |
selectedValues |
Object [] |
G |
Object [0] |
selectionMode |
int |
SG |
MULTIPLE_ INTERVAL_ SELECTION |
visibleRowCount |
int |
SG |
8 |
注:在访问中,C=可在构造时设置/G=获取方法/S=设置方法
selectedIndex:列表框选定项的序号。
selectedIndices:列表框中多个选定项的序号。
selectedValue:列表框中的第一个选定值。
selectedValues:对象数组,列表框中的多个选定项。
selectionMode:指定选取方式。取值为SINGLE_SELECTION(单项)、SINGLE_INTERVAL_SELECTION(单区间项)和MULTIPLE_INTERVAL_SELECTION(多区间项)。其中,单区间项允许选择多项,但是选定的项必须是连续的,而多区间项允许选择多组连续项。
visibleRowCount:列表框显示的可见行数。
JList类所支持的监听器接口为:ListSelectionListener,监听器必须实现valueChanged方法处理列表项选取事件。需要注意的是ListSelectionListener包含在javax.swing.event包中。
【例8.12】在列表框中进行选取的例子。
// JListSelectionTest.java
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
public class JListSelectionTest extends JFrame implements ListSelectionListener {
private String[] items = {"item [0]", "item [1]", "item [2]", "item [3]", "item [4]", "item [5]"};
private JList list = new JList(items);
private String s = "Selected indices: ";
private JLabel label = new JLabel(s);
public JListSelectionTest() {
getContentPane().add(list, BorderLayout.WEST);
getContentPane().add(label, BorderLayout.CENTER);
list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
list.addListSelectionListener(this);
}
public static void main(String[] args) {
JListSelectionTest frame = new JListSelectionTest();
frame.setTitle("JList Selection Test");
frame.setSize(400, 150);
frame.setVisible(true);
}
public void valueChanged(ListSelectionEvent e) {
int[] selected = list.getSelectedIndices();
String selStr = s;
for (int i = 0; i < selected.length; i++) {
selStr += Integer.toString(selected[i]);
if (i < selected.length - 1)
selStr += ",";
}
label.setText(selStr);
}
}
运行结果:
在实例中,实现了监听器接口ListSelectionListener,在改变列表框选项时,更新标签。
因为JList类本身没有提供对数据操纵的方法,要在列表框中添加或者删除项目,需要实现列表框模型接口ListModel。DefaultListModel类实现了ListModel接口,并把数据存储和获取的工作委托给Vector的一个实例,从而对数据进行处理。
【例8.13】操纵列表框数据的实例。
//JListDataTest.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JListDataTest extends JFrame implements ActionListener {
private JPanel p = new JPanel();
private JTextField text = new JTextField(10);
private JButton addBtn = new JButton("Add");
private JButton removeBtn = new JButton("Remove");
private JList list = new JList();
private DefaultListModel model = new DefaultListModel();
public JListDataTest() {
p.add(text);
p.add(addBtn);
p.add(removeBtn);
addBtn.addActionListener(this);
removeBtn.addActionListener(this);
getContentPane().add(p, BorderLayout.NORTH);
getContentPane().add(list, BorderLayout.CENTER);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setModel(model);
}
public static void main(String[] args) {
JListDataTest frame = new JListDataTest();
frame.setTitle("JList Data Test");
frame.setSize(400, 150);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Add"))
if (!text.getText().trim().equals(""))
model.addElement(text.getText().trim());
if (e.getActionCommand().equals("Remove"))
if (list.getSelectedIndex() != -1)
model.removeElementAt(list.getSelectedIndex());
}
}
运行结果;
在实例中,在文本域内填写内容,点击Add按钮后,数据被插入到列表框从列表框中选取某项,点击Remove按钮实现移除。数据的操纵是通过DefaultListModel的addElement和removeElementAt方法实现的,还有许多类似的数据操纵方法。
六、组合框
JComboBox类实现的组合框是由一个可编辑区和一个可选取项的下拉列表组成的。与JList类似,JComboBox把数据管理工作交给实现ComboBoxModel接口的一个对象来处理。DefaultComboBoxModel类实现了ComboBoxModel接口,提供数据存储方法。JComboBox可以通过addItem和removeItem等方法实现对可选项进行处理。
JComboBox的构造方法包括:
表8.9 JComboBox的属性
属性名 |
数据类型 |
访问 |
缺省值 |
selectedIndex |
int |
SG |
-1 |
selectedItem |
Object |
SG |
null |
public JComboBox()
public JComboBox(Object [] stringItems)
public JComboBox(Vector stringItems)
构造方法中,stringItems指定了组合框的项目列表。
JComboBox实例维护的涉及到选取的属性为:
注:在访问中,C=可在构造时设置/G=获取方法/S=设置方法
selectedIndex:组合框列表中选取项的索引。
selectedItem:当前在组合框中选取的对象。
JComboBox类所支持的监听器接口为:ItemListener,监听器必须实现itemStateChanged方法处理列表项选取事件。
【例8.14】组合框的实例
//JComboBoxTest.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JComboBoxTest extends JFrame implements ItemListener {
private String[] items = {"吉林省", "黑龙江省", "辽宁省"};
private JComboBox province = new JComboBox(items);
private JComboBox city = new JComboBox();
public JComboBoxTest() {
getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER, 25, 25));
getContentPane().add(province);
getContentPane().add(city);
province.setEditable(false);
province.addItemListener(this);
city.setEditable(true);
province.setSelectedIndex(0);
RefreshCity();
}
public static void main(String[] arg) {
JComboBoxTest frame = new JComboBoxTest();
frame.setTitle("JComboBox Test");
frame.setSize(400, 150);
frame.setVisible(true);
}
public void itemStateChanged(ItemEvent e) {
RefreshCity();
}
public void RefreshCity() {
city.removeAllItems();
if (province.getSelectedItem().toString().equals("吉林省")) {
city.addItem("长春市");
city.addItem("吉林市");
} else if (province.getSelectedItem().toString().equals("黑龙江省")) {
city.addItem("哈尔滨市");
city.addItem("齐齐哈尔市");
city.addItem("牡丹江市");
city.addItem("佳木斯市");
} else if (province.getSelectedItem().toString().equals("辽宁省")) {
city.addItem("沈阳市");
city.addItem("大连市");
}
}
}
运行结果;
实例包含了两个组合框,前者列举省份名,后者列举城市名。选取省份后,城市列表相应刷新,其中城市组合框允许编辑。
七、复选框
复选框是具有两种状态的按钮。它们通常显示文本,并有一个指示它们当前是否被选取的可视指示器。Swing中的复选框组件为JCheckBox类。
JCheckBox类的构造方法包括:
public JCheckBox()
public JCheckBox(Icon icon)
public JCheckBox(Icon icon, boolean selected)
public JCheckBox(String text)
public JCheckBox(String text, boolean selected)
public JCheckBox(String text, Icon icon)
public JCheckBox(String text, Icon icon, boolean selected)
其中,text指定了复选框的文本,icon指定了复选框的图标,selected指定复选框初始时是否被选中。
JCheckBox所支持的监听器接口为:ItemListener。
【例8.15】复选框组件的实例
//JCheckBoxTest.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JCheckBoxTest extends JFrame implements ItemListener {
private JPanel p = new JPanel();
private JCheckBox oddPages = new JCheckBox("Odd Pages");
private JCheckBox evenPages = new JCheckBox("even Pages");
private JCheckBox collate = new JCheckBox("Collate");
private JCheckBox lastFirst = new JCheckBox("Last Page First");
private JLabel label = new JLabel();
public JCheckBoxTest() {
p.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
p.add(oddPages);
p.add(evenPages);
p.add(collate);
p.add(lastFirst);
getContentPane().add(p, BorderLayout.NORTH);
getContentPane().add(label, BorderLayout.CENTER);
oddPages.addItemListener(this);
evenPages.addItemListener(this);
collate.addItemListener(this);
lastFirst.addItemListener(this);
}
public static void main(String[] args) {
JCheckBoxTest frame = new JCheckBoxTest();
frame.setTitle("JCheckBox Test");
frame.setSize(400, 150);
frame.setVisible(true);
}
public void itemStateChanged(ItemEvent e) {
String s = "Odd Pages:" + oddPages.isSelected() + ",";
s += "Even Pages:" + evenPages.isSelected() + ",";
s += "Collate:" + collate.isSelected() + ",";
s += "Last Page First:" + lastFirst.isSelected();
label.setText(s);
}
}
运行结果:
实例包含四个用来选取打印选项的复选框。这是个复选框放在一个组中。不论何时选取或取消选取了一个复选框,都会用当前状态更新标签。
八、单选按钮
单选按钮总是用于显示一组相互排斥的选项,即通常是放置在一个按钮组的。
JRadioButton的构造方法包括:
public JRadioButton ()
public JRadioButton (Icon icon)
public JRadioButton (Icon icon, boolean selected)
public JRadioButton (String text)
public JRadioButton (String text, boolean selected)
public JRadioButton (String text, Icon icon)
public JRadioButton (String text, Icon icon, boolean selected)
其中,text指定了单选按钮的文本,icon指定了单选按钮的图标,selected指定单选按钮初始时是否被选中。
JRadioButton所支持的监听器接口为:ItemListener。
【例8.16】单选按钮组件的实例
//JRadioButtonTest.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JRadioButtonTest extends JFrame {
private JRadioButton printAll, printRange;
JLabel startPage, endPage;
JTextField startField, endField;
public JRadioButtonTest() {
ButtonGroup group = new ButtonGroup();
printAll = new JRadioButton("Print All");
printRange = new JRadioButton("Print Range");
startPage = new JLabel("Start Page:");
endPage = new JLabel("End Page:");
startField = new JTextField(2);
endField = new JTextField(2);
printRange.setSelected(true);
getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER, 5, 40));
getContentPane().add(printAll);
getContentPane().add(printRange);
getContentPane().add(startPage);
getContentPane().add(startField);
getContentPane().add(endPage);
getContentPane().add(endField);
group.add(printAll);
group.add(printRange);
printAll.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (printAll.isSelected()) {
startPage.setEnabled(false);
startField.setEnabled(false);
endPage.setEnabled(false);
endField.setEnabled(false);
}
}
});
printRange.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (printRange.isSelected()) {
startPage.setEnabled(true);
startField.setEnabled(true);
endPage.setEnabled(true);
endField.setEnabled(true);
}
}
});
}
public static void main(String[] args) {
JRadioButtonTest frame = new JRadioButtonTest();
frame.setTitle("JRadioButton Test");
frame.setSize(400, 150);
frame.setVisible(true);
}
}
运行结果:
实例包含两个单选按钮,可用于选取要打印的页码范围。这两个单选按钮是相互排斥的,当选取其中之一时,另一个就取消选取。当选取Print All按钮时,禁用标签和文本域;选取Print Range按钮则启用标签和文本域,能够指定打印页码的范围。
九、滚动条
滚动条组件JScrollBar实现了可视区域的扩展,分为垂直滚动条和水平滚动条两种。它作为一个单独的组件,需要自行处理滚动事件。
滚动条的构造方法包括:
表 8.10 JScrollBar的属性
属性名 |
数据类型 |
访问 |
缺省值 |
blockIncrement |
int |
SG |
与界面样式有关 |
maximum |
int |
CSG |
100 |
minimum |
int |
CSG |
0 |
orientation |
int |
CSG |
VERTICAL |
unitIncrement |
int |
SG |
与界面样式有关 |
value |
int |
CSG |
0 |
valueIsAdjusting |
boolean |
SG |
false |
visibleAmount |
int |
CSG |
0 |
public JScrollBar()
public JScrollBar(int orientation)
public JScrollBar(int orientation, int value, int extent, int minimum, int maximum)
在构造方法中,orientation指定了滚动条的方向,value指定了滚动条的值,extent制定了部分可见值,而minimum和maximum分别指定了滚动条的最小值和最大值。第一个构造方法创建的垂直滚动条。
JScrollBar实例维护的属性包括:
注:在访问中,C=可在构造时设置/G=获取方法/S=设置方法
blockIncrement:调整块引起的滚动条值的改变量,通常该值为一页数据。
maximum:滚动条所代表的最大值。
minimum:滚动条所代表的最小值。
orientation:滚动条的方向。取值为:JScrollBar.HORIZONTAL或JScrollBar.VERTICAL。
unitIncrement:调整单元所引起的滚动条值的改变量,通常该值为一行数据。
value:滚动条的滑块的左边界或上边界所代表的当前值。
valueIsAdjusting:如果该值为true,则滚动条的滑块正在被拖动。
visibleAmount:当前可见的视图量。滚动条滑块的大小与可见量成比例。
滚动条类支持的监听器是AdjustmentListener接口。
【例8.17】滚动条使用的实例
//JScrollBarTest.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JScrollBarTest extends JFrame implements AdjustmentListener {
private JScrollBar jsbVert, jsbHort;
MessagePanel panel;
public JScrollBarTest() {
jsbVert = new JScrollBar(JScrollBar.VERTICAL);
jsbHort = new JScrollBar(JScrollBar.HORIZONTAL);
panel = new MessagePanel();
getContentPane().add(jsbVert, BorderLayout.EAST);
getContentPane().add(jsbHort, BorderLayout.SOUTH);
getContentPane().add(panel, BorderLayout.CENTER);
jsbVert.addAdjustmentListener(this);
jsbHort.addAdjustmentListener(this);
}
public static void main(String[] args) {
JScrollBarTest frame = new JScrollBarTest();
frame.setTitle("JScrollBar Test");
frame.setSize(400, 150);
frame.setVisible(true);
}
public void adjustmentValueChanged(AdjustmentEvent e) {
if (e.getSource() == jsbVert) {
double value = jsbVert.getValue();
double maximumValue = jsbVert.getMaximum();
double newY = (value * panel.getSize().height / maximumValue);
panel.setYCoordinate((int) newY);
panel.repaint();
}
if (e.getSource() == jsbHort) {
double value = jsbHort.getValue();
double maximumValue = jsbHort.getMaximum();
double newX = (value * panel.getSize().width / maximumValue);
panel.setXCoordinate((int) newX);
panel.repaint();
}
}
}
class MessagePanel extends JPanel {
private String message = "Welcome to Java";
private int xCoordinate = 60;
private int yCoordinate = 60;
public void setMessage(String message) {
this.message = message;
}
public void setXCoordinate(int x) {
this.xCoordinate = x;
}
public void setYCoordinate(int y) {
this.yCoordinate = y;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString(message, xCoordinate, yCoordinate);
}
}
运行结果:
实例中,使用水平和垂直滚动条来调整面板中显示消息的位置。
十、选项卡
选项卡窗格JTabbedPane提供了方便访问多个面板的途径。包含在JTabbedPane中的选项卡有一个组件与之相关联,用户通过点击带文本和(或)图标的卡片就可以在一组面板之间切换。
JTabbedPane的构造方法包括:
public JTabbedPane()
public JTabbedPane(int tabPlacement)
tabPlacement指定了选项卡的放置位置。
JTabbedPane实例维护的属性包括:
表8.11 JTabbedPane的属性
属性名 |
数据类型 |
访问 |
缺省值 |
componentAt |
Component |
SG |
null |
iconAt |
Icon |
SG |
—— |
selectedComponent |
Component |
SG |
—— |
selectedIndex |
int |
SG |
—— |
tabCount |
int |
G |
—— |
tabPlacement |
int |
CSG |
TOP |
tabRunCount |
int |
G |
—— |
titleAt |
String |
SG |
—— |
注:在访问中,C=可在构造时设置/G=获取方法/S=设置方法
componentAt:代表一个选项卡的组件,这个选项卡是用索引标识的。
iconAt:代表在一个启用的选项卡中显示的图标。
selectedComponent:选项卡窗格总是有一个已选取的选项卡,而selectedComponent代表与这个已选取选项卡相关的组件。
selectedIndex:选项卡既可以用一个索引值选取,也可以用它们的相关组件选取。
tabCount:包含在选项卡窗格中的选项卡数,属性为只读。
tabPlacement:确定选项卡窗格中的选项卡的显式位置。取值为:JTabbedPane.TOP、JTabbedPane.BOTTOM、JTabbedPane.LEFT和JTabbedPane.RIGHT。
tabRunCount:表示具有选项卡的行数或列数。属性为只读。
titleAt:代表一个选项卡显示的字符串。
JTabbedPane类支持的监听器接口为:ChangListener。
【例8.18】选项卡使用的实例
//JTabbedPaneTest.java
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
public class JTabbedPaneTest extends JFrame {
private JTabbedPane tp;
private JPanel panel1, panel2;
private JLabel label;
public JTabbedPaneTest() {
tp = new JTabbedPane();
panel1 = new JPanel();
panel2 = new JPanel();
label = new JLabel();
panel1.add(new JButton("button in panel 1"));
panel2.add(new JButton("button in panel 2"));
tp.add(panel1, "Panel One");
tp.addTab("Panel Two", new ImageIcon("doc.gif"), panel2, "tooltip text");
getContentPane().add(tp, BorderLayout.CENTER);
getContentPane().add(label, BorderLayout.SOUTH);
tp.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
JTabbedPane tabbedPane = (JTabbedPane) e.getSource();
int index = tabbedPane.getSelectedIndex();
String s = tabbedPane.getTitleAt(index);
label.setText(s + " selected");
}
});
}
public static void main(String[] args) {
JTabbedPaneTest frame = new JTabbedPaneTest();
frame.setTitle("JTabbedPane Test");
frame.setSize(400, 150);
frame.setVisible(true);
}
}
运行结果:
实例中演示了一个包含两个选项卡的选项窗格,其中第二个选项卡同时显示文本和图标。每个选项卡包含一个按钮组件,点击不同的选项卡后,底部的窗格指示被选择的选项卡名称。
十一、对话框
对话框在外观上与框架是类似的,具有边框和标题栏,通常标题栏上还有一个关闭框,用于清除对话框。对话框作为一种容器,可以添加各种组件。
Swing对话框分为两种:模态对话框和非模态对话框。其中,模态对话框正在显示时,不能访问这个对话框的父窗口中的其他窗口,直至对话框被清除。非模态对话框没有这个限制,Swing对话框在缺省时是非模态的。
对话框类JDialog的构造方法包括:
表8.12 JDialog的属性
属性名 |
数据类型 |
访问 |
缺省值 |
contentPane |
Container |
SG |
JPanel实例 |
defaultCloseOperation |
int |
SG |
HIDE_ON_ClOSE |
jMenuBar |
JMenuBar |
SG |
null |
locationRelativeTo |
Component |
S |
—— |
public JDialog()
public JDialog(Frame owner)
public JDialog(Frame owner, boolean modal)
public JDialog(Frame owner, String title)
public JDialog(Frame owner, String title, boolean modal)
其中,owner指定了对话框的父窗口,model确定该对话框是否为模态,title指定对话框的标题。
JDialog实例维护的属性包括:
注:在访问中,C=可在构造时设置/G=获取方法/S=设置方法
contentPane:JDialog实例中的组件被放置在该容器内。
defaultCloseOperation:在关闭对话框时将要执行的一个操作。取值为:WindowContants.HIDE_ON_CLOSE、WindowConstants.DISPOSE_ON_CLOSE和WindowConstants.DO_NOTHING_ON_CLOSE。
jMenuBar:与对话框相关联的菜单栏。
locationRelativeTo:指定对话框将要显示的位置。如果传送给setLocationRelativeTo的组件是null,则对话框将在屏幕坐标的(0, 0)处显示。如果组件不是null,但是在调用setLocationRelativeTo时是不可见的,则对话框将在屏幕中间显示。
【例8.19】对话框使用的实例
//JDialogTest.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JDialogTest extends JFrame implements ActionListener {
private JPanel buttonsPanel = new JPanel();
private JButton showButton = new JButton("show dialog ..."),
okButton = new JButton("OK"),
cancelButton = new JButton("Cancel");
private JTextArea text = new JTextArea("content...");
private JDialog dialog = new JDialog();
public JDialogTest() {
getContentPane().add(showButton);
showButton.addActionListener(this);
buttonsPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 5));
buttonsPanel.add(okButton);
buttonsPanel.add(cancelButton);
dialog.getContentPane().add(buttonsPanel, BorderLayout.SOUTH);
dialog.getContentPane().add(text, BorderLayout.CENTER);
}
public static void main(String[] args) {
JDialogTest frame = new JDialogTest();
frame.setTitle("JDialog Test");
frame.setSize(400, 150);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == showButton) {
dialog.setTitle("Contraint Dialog");
dialog.setSize(300, 120);
dialog.setModal(true);
dialog.setLocationRelativeTo(JDialogTest.this);
dialog.show();
}
}
}
运行结果:
在实例中,点击show dialog按钮,创建并显示一个模态对话框,其中对话框窗格上包含了一个文本域和两个按钮组件。
Swing还提供了选项窗格类JOptionPane。JOptionPane提供了一组静态方法,用于创建简单的对话框,如表所示。JOptionPane创建的对话框均为模态对话框。
表 8.13由静态JOptionPane方法创建的对话框类型
对话框类型 |
描述 |
返回值 |
配置项 |
消息 |
显示一个消息和一个OK按钮 |
—— |
标题、消息、消息类型、图标 |
确认 |
询问一个问题,选择按钮来回答 |
代表所选按钮的整数 |
标题、消息、消息类型、图标选项类型(按钮) |
输入 |
用一个文本域、组合框或列表来提示输入 |
代表响应的字符串 |
标题、消息、消息类型、图标选择值、初始值 |
选项 |
除按钮行中的对象是完全可配置的外,其余与确认对话框相似 |
代表所选按钮的整数 |
标题、消息、消息类型、选项类型(按钮)、图标选项、初始值 |
消息对话框显示一个信息消息,并且只有一个标签为OK的按钮。创建消息对话框的static JOptionPane方法。
public static void showMessageDialog(Component parentComponent, Object message)
public static void showMessageDialog(Component parentComponent, Object message, String title, int messageType)
public static void showMessageDialog(Component parentComponent, Object message, String title, int messageType, Icon icon)
创建消息对话框时所使用的参数包括;
表 8.14创建消息对话框时所使用的参数
属性 |
允许值 |
缺省 |
parentComponent |
任何可见组件 |
必须指定 |
message |
对象 |
必须指定 |
title |
字符串 |
“message” |
messageType |
ERROR_MESSAGE(错误)、 INFORMATION_MESSAGE(信息)、 PLAIN_MESSAGE(纯文本)、 QUESTION_MESSAGE(询问)、 WARNING_MESSAGE(警告) |
INFORMATION_ MESSAGE |
icon |
图标 |
根据 messageType 确定 |
确认对话框提出一个问题,这个问题需要用户选择一个按钮来回答。在确认对话框中显示的按钮可以用预先确定的按钮选项来配置。静态JOptionPane方法返回整数值,指示被选择的按钮。创建确认对话框的静态方法包括:
public staic int showConfirmDialog(Component parentComponent, Object message)
public staic int showConfirmDialog(Component parentComponent, Object message, String title, int optionType)
public staic int showConfirmDialog(Component parentComponent, Object message, String title, int optionType, int messageType)
public staic int showConfirmDialog(Component parentComponent, Object message, String title, int optionType, int messageType, Icon icon)
创建确认对话框时所使用的参数包括;
表 8.15创建确认对话框时所使用的参数
属性 |
允许值 |
缺省 |
parentComponent |
任何可见组件 |
必须指定 |
message |
对象 |
必须指定 |
title |
字符串 |
“select an Option |
messageType |
ERROR_MESSAGE(错误)、 INFORMATION_MESSAGE(信息) PLAIN_MESSAGE(纯文本)、 QUESTION_MESSAGE(询问)、 WARNING_MESSAGE(警告) |
QUESTION_MESSAGE |
icon |
图标 |
根据messageType确定 |
optionType |
YES_NO_OPTION、 YES_NO_CANCEL_OPTION、 OK_CANCEL_OPTION |
YES_NO_OPTION |
输入对话框允许把数据输入到对话框中。指定一个对象数组作为可选取的值,而且可以指定一个特定的对象作为初始选取值。可用于输入对话框的Swing组件包括:JTextField、JComboBox或JList。
创建输入对话框的静态方法包括:
public staic String showInputDialog(Object message)
public staic String showInputDialog(Component parentComponent, Object message)
public staic String showInputDialog(Component parentComponent, Object message, String title, int messageType)
public staic object showInputDialog(Component parentComponent, Object message, String title, int messageType, Icon icon, Object[] selectionValues, Object initialSelectionValue)
创建确认对话框时所使用的参数包括;
表 8.16创建确认对话框时所使用的参数
属性 |
允许值 |
缺省 |
parentComponent |
任何可见组件 |
必须指定 |
message |
对象 |
必须指定 |
title |
字符串 |
“select an Option |
messageType |
ERROR_MESSAGE(错误)、 INFORMATION_MESSAGE(信息) PLAIN_MESSAGE(纯文本)、 QUESTION_MESSAGE(询问)、 WARNING_MESSAGE(警告) |
QUESTION_MESSAGE |
icon |
图标 |
根据messageType确定 |
selectionValues |
对象数组 |
null |
initialSelectionValue |
对象引用 |
null |
【例8.20】使用JOptionPane创建对话框
//JOptionPaneTest,java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JOptionPaneTest extends JFrame implements ActionListener {
private JPanel buttonsPanel = new JPanel();
private JButton messageButton = new JButton("message button"),
confirmButton = new JButton("confirm button"),
inputButton = new JButton("input button");
private JLabel label = new JLabel();
public JOptionPaneTest() {
buttonsPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
buttonsPanel.add(messageButton);
buttonsPanel.add(confirmButton);
buttonsPanel.add(inputButton);
messageButton.addActionListener(this);
confirmButton.addActionListener(this);
inputButton.addActionListener(this);
getContentPane().add(buttonsPanel, BorderLayout.CENTER);
getContentPane().add(label, BorderLayout.SOUTH);
}
public static void main(String[] args) {
JOptionPaneTest frame = new JOptionPaneTest();
frame.setTitle("JOptionPane Test");
frame.setSize(400, 150);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == messageButton) {
JOptionPane.showMessageDialog(messageButton, "information",
"message dialog", JOptionPane.INFORMATION_MESSAGE);
label.setText("message dialog");
}
if (e.getSource() == confirmButton) {
int result = JOptionPane.showConfirmDialog(confirmButton,
"Please make an option", "confirm dialog", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE);
switch (result) {
case JOptionPane.CLOSED_OPTION:
label.setText("confirm selected: Close");
break;
case JOptionPane.YES_OPTION:
label.setText("confirm selected: Yes");
break;
case JOptionPane.NO_OPTION:
label.setText("confirm selected: No");
break;
case JOptionPane.CANCEL_OPTION:
label.setText("confirm selected: Cancel");
break;
}
}
if (e.getSource() == inputButton) {
String s = (String) JOptionPane.showInputDialog(inputButton,
"Please input the answer", "input dialog");
if (s == null)
label.setText("input answer: Cancel");
else
label.setText("input answer: " + s);
}
}
}
运行结果:
实例中,主框架窗口包含三个按钮和一个标签组件,点击按钮分别创建并显示以上三类对话框,并将选择的结果显示在标签中。
十二、菜单
Swing组件提供了三个层次的菜单类。最上层的是菜单栏类JMenuBar,用来存放菜单。JMenu是菜单类,JMenuItem、JCheckBoxMenuItem(带复选框的菜单项)和JRadioButtonMenuItem(带单选按钮的菜单项)类用于构建菜单项。
JMenuItem的构造方法包括:
public JMenuItem()
public JMenuItem(Icon icon)
public JMenuItem(String text)
public JMenuItem(String text, Icon icon)
public JMenuItem(String text, int mnemonic)
其中,icon和text分别指定了菜单项的图标和文字,mnemonic指定了菜单项的助记符键。
菜单项支持的监听器接口为ActionListener。
另外,可以为菜单项指定一个快捷键,这个快捷键由KeyStoke类的实例表示,用键盘来激活与菜单项相关联的动作。
助记符键要与特定界面样式的”Meta”键一起使用(例如Windows界面样式中对应的Alt键),助记符只有一个字符,如”x”,此时”x”必须与Alt键一起使用,才能激活与之相关联的组件。
快捷键与特定界面样式无关,只调用与菜单项相关联的动作,而不显示菜单。
【例8.21】菜单项的使用实例
//JMenuItemTest.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JMenuItemTest extends JFrame implements ActionListener {
Icon icon = new ImageIcon("doc.gif");
JMenuBar mb = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem newItem = new JMenuItem("New", icon);
JMenuItem openItem = new JMenuItem("Open");
JMenuItem saveItem = new JMenuItem("Save");
JMenuItem exitItem = new JMenuItem("Exit");
JMenu pullMenu = new JMenu("Pull");
JCheckBoxMenuItem checkboxItem = new JCheckBoxMenuItem("Checkbox");
JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem("Radio");
JLabel label = new JLabel();
public JMenuItemTest() {
this.setJMenuBar(mb);
getContentPane().add(label, BorderLayout.SOUTH);
mb.add(fileMenu);
fileMenu.add(newItem);
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.addSeparator();
fileMenu.add(pullMenu);
fileMenu.addSeparator();
fileMenu.add(exitItem);
pullMenu.add(checkboxItem);
pullMenu.add(radioItem);
fileMenu.setMnemonic('F');
exitItem.setMnemonic('X');
KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_X, Event.CTRL_MASK);
exitItem.setAccelerator(ks);
exitItem.addActionListener(this);
}
public static void main(String[] args) {
JMenuItemTest frame = new JMenuItemTest();
frame.setTitle("JMenuItem Test");
frame.setSize(400, 150);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == exitItem)
label.setText("Exit");
}
}
运行结果:
在实例中创建了一个MenuBar实例和两个JMenu实例,通过调用add方法将菜单项添加到菜单中,构成二级菜单结构。其中,New菜单带有图标,二级菜单包含复选或单选形式的菜单项。Exit菜单项带有助记符和快捷键。addSeparator方法为菜单添加分隔线。