文档库 最新最全的文档下载
当前位置:文档库 › Swing组件高级编程

Swing组件高级编程

Swing组件高级编程
1顶层容器 Swing的3个顶层容器类:
JFrame——每个包含Swing 组件的主窗口都应用JFrame 来实现
JApplet——每个包含Swing 组件的Applet 都应作为JApplet 的子类来实现
JDialog——要实现对话框,需要从JDialog派生一个类
都是重量级组件,分别继承了AWT组件Frame、Applet和Dialog;
每个顶层容器都有一个内容面板,通常直接或间接的容纳别的可视组件;
可以有选择地为顶层容器添加菜单,菜单被放置在顶层容器上,但是在内容面板之外。
2获得一个顶层容器
JApplet类的顶层容器由浏览器提供,通常我们不需要自己产生一个JApplet类的对象。JFrame和JDialog通过构造方法进行创建
JFrame();//建立一个新的JFrame,默认值是不可见的(Invisible)
JFrame(String title);//建立一个具有标题title的JFrame,默认值是不可见的(Invisilble)
JApplet();//建立一个JApplet
JDialog();建立一个non-moal对话框,无标题
JDialog(Dialog owner);//建立一个属于Dialog组件的对话框,为non-modal形式,无标题
JDialog(Dialog owner, boolean modal );//建立一个属于Dialog组件的对话框,可决定modal形式,无标题
JDialog(Dialog owner, String title);//建立一个属于Dialog组件的对话框,为non-modal形式,有标题
JDialog(Dialog owner, String title, boolean modal);//建立一个属于Dialog组件的对话框,可决定modal形式,有标题
JDialog(Frame owner);//建立一个属于Frame组件的对话框,为non-modal形式,无标题
JDialog(Frame owner, boolean modal);//建立一个属于Frame组件的对话框,可决定modal形式,无标题
JDialog(Frame owner, String title);//建立一个属于Frame组件的对话框,为non-modal形式,有标题
JDialog(Frame owner, String title, boolean modal);//建立一个属于Frame组件的对话框,可决定modal形式,有标题
说明:
JDialog必须实现对话框中的每一个组件
JOptionPane只要显示一段文字,或是做一些简单的选择的简单对话框
在javax.swing包内通过使用这个类提供的一些静态方法show×××Dialog,就可以产生四种简单的对话框
它们的方法参数中绝大部分(除了输入对话框可以不指定父窗口)都需要提供一个父窗口组件ParentComponent,只有关闭这些简单的对话框后,才可以返回到其父窗口,也就是说,它们绝大部分都是模态的
3中间层容器
中间层容器存在的目的仅仅是为了容纳别的组件,它分为两类
一般用途的
JPanel
JScrollPane
JSplitPane
JTabbedPane
JToolBar
特殊用途的
JInternalFrame
JRootPane(比较特殊,它由好几个部分构成,我们可以直接从顶层容器中获得一个JRootPane对象来直接使用,而不需要像别的中间容器那样,使用的时候需要新建一个对象)
4 中间层容器JPanel:
是一种经常使用的轻量级中间

容器
在默认状态下,除了背景色外它并不绘制任何东西
可以很容易的为它设置边框和绘制特性,我们可以把它设置为顶层容器contentPane,有效地利用JPanel可以使版面管理更为容易
可以使用布局管理器来规划它所容纳的组件的位置和大小
可以通过setLayout方法来改变其布局
也可以在创建一个JPanel对象时就为它确定某种布局方式,在默认状态下panel使用FlowLayout布局,将各组件布局在一行
4.1JPanel类常用API

JPanel();//创建一个JPanel,默认布局是FlowLayout
JPanel(LayoutManager layout);//创建一个指定布局的JPanel
void add(Component comp);//添加组件
void add(Component comp, int index);把组件添加到特定位置上
int getComponentCount();//获得这个panel里所有组件的数量
Component getComponent(int index);//获得指定序号的某个组件
Component getComponentAt(int x, int y);//获得指定位置的某个组件
void remove(Component);//移除某个组件
void removeAll();//移除所有组件
void setLayout(LayoutManager layout);//设置布局
LayoutManager getLayout();//得到现有布局
void setBorder(Border border);//设置边框
5 JScrollPane(滚动条)容器
JScrollPane容器
当容器内要容纳的内容大于容器大小的时候,我们希望容器能够有一个滚动条,通过setBorder(Border border);拖动滑块,就可以看到更多的内容。JScrollPane就是能够实现这种功能的特殊容器
由九个部分组成,包括一个中心显示地带、四个角和四条边
5.1 JScrollPane(滚动条)常用API

static int HORIZONTAL_SCROLLBAR_ALWAYS//水平滚动条策略常数:总是显示
static int HORIZONTAL_SCROLLBAR_AS_NEEDED//水平滚动条策略常数:当显示内容水平区域大于显示区域时才出现
static int HORIZONTAL_SCROLLBAR_NEVER//水平滚动条策略常数:总是不显示
static int VERTICAL_SCROLLBAR_ALWAYS//垂直滚动条策略常数:总是显示
static int VERTICAL_SCROLLBAR_AS_NEEDED//垂直滚动条策略常数:当显示内容垂直区域大于显示区域时才出现
static int VERTICAL_SCROLLBAR_NEVER//垂直滚动条策略常数:总是不显示
JScrollPane()//建立一个空的JScrollPane对象
JScrollPane(Component view)//建立一个显示组件的JScrollPane对象,当组件内容大于显示区域时,自动产生滚动条
void setViewportView(Component)//设置JscrllPane要中心地带要显示的组件
void setVerticalScrollBarPolicy(int)
int getVerticalScrollBarPolicy() 设置或者读取垂直滚动条策略常数
void setHorizontalScrollBarPolicy(int)
int getHorizontalScrollBarPolicy() 设置或者读取水平滚动条策略常数
void setViewportBorder(Border)
Border getViewportBorder() 设置或者读取中心显示地带的边框
void setWheelScrollingEnabled(Boolean)
Boolean isWheelScrollingEnabled() 设置或者读取是否随着鼠标滚轮滚动出现或隐藏滚动

条,默认状态下为真
void setColumnHeaderView(Component)//设置显示在上面的边上的组件
void setRowHeaderView(Component)//设置显示在左面的边上的组件
void setCorner(String key,Component corner)//设置要显示在指定角上的组件,key的值为图9_18中表明的字符串之一
Component getCorner(String key)//获得指定角上的组件
6 中间层容器JSplitPane(分割窗口区域)
可以把两个组件显示在两个显示区域内,且随着区域间分隔线的拖动,区域内组件的大小也随之发生变动
它允许设置水平分割或者垂直分割;也允许设置动态拖曳功能(拖动分界线时两边组件是否会随着拖曳动态改变大小还是在拖曳结束后才改动)
我们通常先把组件放到Scroll Pane中,再把Scroll Pane放到Split Pane中。这样在每部分窗口中,都可以拖动滚动条看到组件的全部内容
6.1 JSplitPane常用API

static int HORIZONTAL_SPLIT;//水平分割常数
static int VERTICAL_SPLIT;//垂直分割常数
JSplitPane();//创建一个JSplitPane,以水平方向排列,两边各是一个button,没有动态拖曳功能
JSplitPane(int newOrientation);//建立一个指定分割方向的JSplitPane,没有动态拖曳功能,参数为两个分割常数之一
JSplitPane(int newOrientation,Boolean newContinuousLayout);//指定分割方向,并可指定是否有动态拖曳功能
JSplitPane(int newOrientation,Boolean newContinuousLayout,Component newLeftComponent,Component newRightComponent);//指定分割方向、是否具有动态拖曳功能,和两侧组件
JSplitPane(int newOrientation,Component newLeftComponent,Component newRightComponent);//指定分割方向和两侧组件,无自动拖曳功能
void setOrientation(int newOrientation)
int getOrientation() 设置或获得分割方向
void setDividerSize(int)
int getDividerSize() 设置或读取分隔线条的粗细
void setContinuousLayout(boolean nCL)
boolean isContinuousLayout() 设置或读取是否使用动态拖曳功能
void setOneTouchExpandable(Boolean oTE)
boolean is OneTouchExpandable() 设置或读取是否在分隔线上显示一个控键来完全扩展和完全压缩单侧内容。
void remove(Component comp)
void add(Component comp) 删除或添加组件。只可以添加两个组件
void setDividerLocation(double)
void setDividerLocation(int)
int getDividerLocation() 设置或读取分隔线条的位置。设置参数可以是double型的百分数,也可以是int型的象素值
6.2程序示例:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
public class SplitPaneDemo implements ListSelectionListener {
private Vector imageNames;
private JLabel picture;
private JList list;
private JSplitPane splitPane;
public SplitPaneDemo() {
ResourceBundle imageResource;
try { //Read image names from a properties file

imageResource = ResourceBundle.getBundle("imagenames");
String imageNamesString = imageResource.getString("images");
imageNames = parseList(imageNamesString);
} catch (MissingResourceException e) {
System.exit(1);
}
list = new JList(imageNames);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setSelectedIndex(0);
list.addListSelectionListener(this);
JScrollPane listScrollPane = new JScrollPane(list);
ImageIcon firstImage = new ImageIcon("./build/classes/"+(String)imageNames.firstElement());
picture = new JLabel(firstImage);
picture.setPreferredSize(new Dimension(firstImage.getIconWidth(),firstImage.getIconHeight()));
JScrollPane pictureScrollPane = new JScrollPane(picture);
splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,listScrollPane, pictureScrollPane);
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(150);
Dimension minimumSize = new Dimension(100, 50);
listScrollPane.setMinimumSize(minimumSize);
pictureScrollPane.setMinimumSize(minimumSize);
splitPane.setPreferredSize(new Dimension(400, 200));
}
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting())
return;
JList theList = (JList)e.getSource();
if (theList.isSelectionEmpty()) {
picture.setIcon(null);
} else {
int index = theList.getSelectedIndex();
ImageIcon newImage = new ImageIcon("./build/classes/"+ (String)imageNames.elementAt(index));
picture.setIcon(newImage);
picture.setPreferredSize(new Dimension(newImage.getIconWidth(),newImage.getIconHeight() ));
picture.revalidate();
}
}
protected static Vector parseList(String theStringList) {
Vector v = new Vector(10);
StringTokenizer tokenizer = new StringTokenizer(theStringList, " ");
while (tokenizer.hasMoreTokens()) {
String image = tokenizer.nextToken();
v.addElement(image);
}
return v;
}
public static void main(String s[]) {
JFrame frame = new JFrame("SplitPaneDemo");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
SplitPaneDemo splitPaneDemo = new SplitPaneDemo();
frame.getContentPane().add(splitPaneDemo.getSplitPane());
frame.pack();
frame.setVisible(true);
}
}
程序说明:
将一个JList组件放在一个JScrollPane容器中
将一个绘有图片的JLabel放在另一个JScrollPane容器中
将两个JScrollPane容器放到一个JSplitPane容器中
该类实现了ListSelectionListener接口,对列表选择事件可以做出反应,使JLable显示出不同的图片
7中间层

容器JTabbedPane(标签)
如果一个窗口的功能有几项,我们可以给每项设置一个标签,每个标签下面包含为完成此功能专用的若干组件
用户要使用哪项功能,只用点击相应的标签,就可以进入相应的页面
7.1JTabbedPane常用API

JTabbedPane();//创建一个tabbed pane。标签条位置在顶部
JtabbedPane(int tabPlacement);//创建一个tabbed pane,并设置其标签位置。参数为从SwingConstants接口中继承来的TOP、BOTTOM、LEFT、RIGHT之一。
void addTab(String title, Icon icon,Component comp, String tip)
void addTab(String title, Icon icon,Component comp)
void addTab(String, Component) 增加一个标签页,第一个String参数指定显示在标签上的文本,可选的Icon参数制定标签图标,Component参数指定选择此标签页时要显示的组件,最后一个可选的String参数是提示信息
void insertTab(String title, Icon icon, Component comp, String tip,int index);//在指定位置index插入一个标签页,第一个标签页的index是0,其余参数意义同addTab方法
removeTabAt(int index);//删除指定位置的标签页
int indexOfTabComponent comp);、int indexofTab(String title);、int indexofTab(Icon icon);//返回有指定组件、标题或图标的标签页序号
void setSelectedIndex(int)
void setSelectedComponent(Component comp) 选择指定序号或组件的标签页。选择的效果是将显示此标签页所含的所有内容
void setComponentAt(int index, Component comp)
Component getComponentAt(int index) 设置或读取指定序号标签页上的组件
void setEnabledAt(int index, Boolean enabled);//设置指定序号标签页是否可选
7.2程序示例:
import javax.swing.JTabbedPane;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.*;
public class TabbedPaneDemo extends JPanel {
public TabbedPaneDemo() {
ImageIcon icon = new ImageIcon("images/middle.gif");
JTabbedPane tabbedPane = new JTabbedPane();
Component panel1 = makeTextPanel("Blah");
tabbedPane.addTab("One", icon, panel1, "Does nothing");
tabbedPane.setSelectedIndex(0);
Component panel2 = makeTextPanel("Blah blah");
tabbedPane.addTab("Two", icon, panel2, "Does twice as much nothing");
Component panel3 = makeTextPanel("Blah blah blah");
tabbedPane.addTab("Three", icon, panel3, "Still does nothing");
Component panel4 = makeTextPanel("Blah blah blah blah");
tabbedPane.addTab("Four", icon, panel4, "Does nothing at all");
//Add the tabbed pane to this panel.
setLayout(new GridLayout(1, 1));
add(tabbedPane);
}
protected Component makeTextPanel(String text) {
JPanel panel = new JPanel(false);
JLabel filler = new JLabel(text);
filler.setHorizontalAlignment(JLabel.CENTER);

panel.setLayout(new GridLayout(1, 1));
panel.add(filler);
return panel;
}
public static void main(String[] args) {
JFrame frame = new JFrame("TabbedPaneDemo");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
frame.getContentPane().add(new TabbedPaneDemo(),BorderLayout.CENTER);
frame.setSize(400, 125);
frame.setVisible(true);
}
}
说明:
在构造函数中创建四个JPanel类型的对象
并将其依次添加到一个JTabbedPane类的对象容器中
最后再将该JTabbedPane类的对象容器放在一个JFrame对象的内容面板中
8中间层容器JToolBar(工具栏)
一般我们在设计界面时,会将所有功能分类放置在菜单中(JMenu),但当功能相当多时,可能会使成用户为一个简单的操作反复地寻找菜单中相关的功能
可以把一些常用的功能以工具栏的方式呈现在菜单下,这就是JToolBar容器类的好处
我们可以将JToolBar设计为水平或垂直方向的,也可以以鼠标拉动的方式来改变
8.1JToolBar常用API

JToolBar();//创建一个工具栏
JToolBar(int orientation);//创建一个工具栏,可以指定其朝向orientation
JToolBar(String name);//创建一个工具栏,指定游离工具栏显示的名称name
JToolBar(String name,int orientation);//创建一个工具栏,可以指定其朝向orientation,为SwingConstants中的HORIZONTAL或VERTICLE,也可以指定游离工具栏显示的名称name。
void add(Component);//为工具栏添加一个组件
void addSeparator();//在末尾增加一个分隔线
void setFloatabled(Boolean floatabled)
Boolean isFloatable() 设置或读取工具栏是否可以游离,成为一个独立的窗口
8.2程序示例:
import javax.swing.JToolBar;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
public class ToolBarDemo extends JFrame {
protected JTextArea textArea;
protected String newline = "\n";
public ToolBarDemo() {
//Do frame stuff.
super("ToolBarDemo");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JToolBar toolBar = new JToolBar(); //Create the toolbar.
addButtons(toolBar);
//Create the text area used for output.
textArea = new JTextArea(5, 30);
JScrollPane scrollPane = new JScrollPane(textArea);
//Lay out the content pane.
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
contentPane.setPreferredSize(new Dimension(400, 100));
contentPane.add(toolBar, BorderLayout.NORTH);
content

Pane.add(scrollPane, BorderLayout.CENTER);
setContentPane(contentPane);
}
protected void addButtons(JToolBar toolBar) {
JButton button = null;
//first button
button = new JButton(new ImageIcon("./build/classes/left.gif"));
button.setToolTipText("This is the left button");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
displayResult("Action for first button");
}
});
toolBar.add(button);
//second button
button = new JButton(new ImageIcon("./build/classes/middle.gif"));
button.setToolTipText("This is the middle button");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
displayResult("Action for second button");
}
});
toolBar.add(button);
//third button
button = new JButton(new ImageIcon("./build/classes/right.gif"));
button.setToolTipText("This is the right button");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
displayResult("Action for third button");
}
});
toolBar.add(button);
}
protected void displayResult(String actionDescription) {
textArea.append(actionDescription + newline);
}
public static void main(String[] args) {
ToolBarDemo frame = new ToolBarDemo();
frame.pack();
frame.setVisible(true);
}
}
说明:
创建了三个按钮,并为每个按钮添加了事件监听器
将三个按钮放在一个JToolBar容器中
将JToolBar容器放在顶层容器的内容面板中
将一个包含JtextArea组件的JScrollPane容器也放在顶层容器的内容面板中
9中间层容器JInternalFram
9.1 JInternalFrame
如果要实现在一个主窗口中打开很多个文档,每个文档各自占用一个新的窗口,就需要使用JInternalFrame容器类
JInternalFrame的使用跟JFrame几乎一样,可以最大化、最小化、关闭窗口、加入菜单
唯一不同的是JInternalFrame是轻量级组件,因此它只能是中间容器,必须依附于顶层容器上
通常我们会将internal frame加入JDesktopPane类的对象来方便管理,JDesktopPane继承自JLayeredPane,用来建立虚拟桌面。
9.2 JInternalFrame常用API

JInternalFrame();//创建一个子窗口对象
JInternalFrame(String title);//创建一个子窗口对象,设置标题
JInternalFrame(String title, boolean resizable);//创建一个子窗口对象,设置标题
JInternalFrame(String title, boolean resizable,boolean closable);//创建一个子窗口对象,设置标题
JInternalFrame(String title, boolean resizable, boolean closable, boolean maximizable);//创建一个子窗口对象
JInternalFrame(String, boolean resizable, boolean closab

le, boolean maximizable,boolean iconifiable);//创建一个子窗口对象,依次设置标题、是否可改变大小、可关闭、可最大最小化、是否有图标。默认状态下都是不可以。
void setContentPane(Container c)或Container getContentPane();//设置或获得internal frame的内容面板,通常包括除菜单以外的所有可视组件
void setJMenuBar(JMenuBar m)
JMenuBar getJMenuBar() 设置或获得internal frame的菜单
void setVisible(boolean b);//此方法从Component类继承。设置是否可见。应该在将internal frame加到其父窗口之前调用。
void setLocation(int x, int y);//设置相对于父窗口的位置。指定左上角坐标
void setBounds(int x, int y, int width, int height);//设置位置和大小
Void addInternalFrameListener(InternalFrameListener l);//添加事件监听器,相当于windowlistener
void setSelected(boolean b)
boolean isSelected() 设置或获得当前是否被激活。
void setFramedIcon(Icon icon)
Icon getFrameIcon() 设置或获得显示在internal frame标题栏中的图标
10原子组件
10.1Swing原子组件有很多种, 与顶层容器和中间容器相比,原子组件用法都比较简单,可分为三类
显示不可编辑信息
JLabel、JProgressBar、JToolTip
有控制功能、可以用来输入信息
JButton、JCheckBox、JRadioButton、JComboBox、JList、JMenu、JSlider、JSpinner、JTextComponent
能提供格式化的信息并允许用户选择
JColorChooser、JFileChooser、JTable、JTree
10.2第一类原子组件
10.2.1解说
JLabel(标签):该组件上可以显示文字和图像,并能指定两者的位置
JProgressBar(工具条):在一些软件运行时,会出现一个进度条告知目前进度如何。通过使用该组件我们可以轻松地为软件加上一个进度条
JToolTip(提示信息)
通常不必直接处理JToolTip类
通常使用setToolTipText()方法为组件设置提示信息
有的组件例如JTabbedPane由多个部分组成,需要鼠标在不同部分停留时显示不同的提示信息,这时可以在其addTab()方法中设置提示信息参数,也可以通过setTooltipTextAt方法进行设置
10.2.2程序例:
随时间增加,进度条输出进度变化情况,同时标签上显示出当前进度。鼠标移到两组件时,显示提示信息
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
public class Ex11_9 implements ChangeListener {
JLabel label;
JProgressBar pb;
public Ex11_9() {
int value=0;
JFrame f=new JFrame("第一类原子组件演示");
Container contentPane=f.getContentPane ();
label=new JLabel("",JLabel.CENTER);
label.setToolTipText("显示进度信息");
pb=new JProgressBar();
pb.setOrientation(JProgressBar.HORIZONTAL); //设置进度条方向
pb.setMinimum(0); //设置最小值
pb.setMaximum(100); //设置最大值
pb.setValue(value); //初值
pb.setStringPainted(tr

ue); //设置进度条上显示进度
pb.addChangeListener(this); //增加时间监听器
pb.setToolTipText ("进度条"); //设置提示信息
contentPane.add(pb,BorderLayout.CENTER);
contentPane.add(label,BorderLayout.SOUTH);
f.setSize(400,60);
f.setVisible(true);
for(int i=1;i<=500000000;i++) {
if(i%5000000==0)
pb.setValue(++value); //改变进度条的值,触发ChangeEvent
}
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
public static void main(String[] args) { new Ex11_8(); }
public void stateChanged(ChangeEvent e) {
int value=pb.getValue();
label.setText ("目前已完成进度:"+value+"%");
}
}
说明
Ex11_9类实现ChangeListener接口,实现了stateChanged方法
main方法中随着程序的运行,不断改变进度条的当前值,触发stateChanged方法,在JLable组件上显示当前进度信息
通过Component类的setTooltipText(String s)方法为组件添加提示信息
11按钮类
11.1按钮类
AbstractButton抽象类是众多按钮类的基类,继承它的类包括
JButton
JToggleButton——表示有两个选择状态的按钮
CheckBox(多选按钮)
JRadioButton(单选按钮)
JMenuItem——在菜单中使用
JCheckBoxMenuItem(多选按钮)
JRadioButtonMenuItem(单选按钮)
JMenu(一般的菜单项)
11.2列表框
列表框JList
除了JCheckBox以外,JList也可以选择一到多个选项
有几种各有特色的构造方法(选项是否可添加、删除)
也提供了很多API可以用来设置各选项的显示方式(在一列还是若干列)、选择模式(一次可选几项及是否可连续)等
因为JList通常含有很多选项,所以经常把它放在一个JScrollPane对象里面
JList的事件处理一般可分为两类
取得用户选取的项目,事件监听器是ListSelectionListener
对鼠标事件作出响应,其事件监听器是MouseListener
11.3复选框
复选框JComboBox
允许用户在许多选项中选其一,可以有两种非常不一样的格式
默认状态是不可编辑的模式,其特色是包括一个按钮和一个下拉列表,用户只能在下拉列表提供的内容中选其一
另一种是可编辑的模式,其特色是多了一个文本区域,用户可以在此文本区域内填入列表中不包括的内容
复选框只需要很少的屏幕区域,而一组JRadioBox、JCheckBox、JList占据的空间比较大
12连续数值选择
连续数值选择
JSlider
空间大
好像电器用品上机械式的控制杆,我们可以设置它的最小、最大、初始刻度,还可以设置它的方向,还可以为其标上刻度或文本
在JSlider上移动滑动杆,会产生ChangeEvent事件
JSpinner
空间小
类似于可编辑的JComboBox,是种复合组件,由三个部分组成:向上按钮、向下按钮和一个文本编辑区
可以通过按钮来选择待选项,也可以

直接在文本编辑区内输入
和JComboBox不同的是,它的待选项不会显示出来
13文本组件
允许用户在里边编辑文本,能满足复杂的文本需求
都继承自JTextComponent抽象类,可分为三类
JTextField、JPasswordField、JFormattedTextField
它们只能显示和编辑一行文本,像按钮一样,它们可以产生ActionEvent事件,因此通常用来接受少量用户输入信息并在输入结束进行一些事件处理
JTextArea
它可以显示和编辑多行文本,但是这些文本只能是单一风格的,因此通常用来让用户输入任意长度的无格式文本或显示无格式的帮助信息
JEditorPane、JTextPane
可以显示和编辑多行多种式样的文本,嵌入图像或别的组件
14颜色选择对话框(JColorChooser)
可以让用户选择所需要的颜色
通常使用这个类的静态方法showDialog()来输出标准的颜色选择对话框,其返回值就是选择的颜色
也可以通过静态方法createDialog()方式输出个性化的颜色选择对话框,例如为其添加菜单、定义其事件处理程序,这个方法的返回值就是一个对话框
15JFileChooser文件选择对话框
让用户选择一个已有的文件或者新建一个文件
可以使用JFileChooser的showDialog、showOpenDialog或showSaveDialog()方法来打开文件对话框,但是它仅仅会返回用户选择的按钮(确认还是取消)和文件名(如果确认的话),接下来的要实现的例如存盘或者打开的功能还需要程序员自己编写
这个类提供了专门的方法用于设置可选择的文件类型,还可以指定每类文件使用的类型图标
16JTable表格
和其相关的还有一些接口和类,包括TableModel、AbstractTableModel、DefaultTableModel、SelectionModel、TableColumnModel
可为表格设计显示外观(是否有滚动条、调整某一列宽其它列宽变化情形)、显示模式(根据数据类型的不同有不同的排列显示方式、为某一字段添加复选框JComboBox)、选择模式(单选、多选、连续选、任意选)
在JTable的事件大致均针对表格内容的异操作处理,我们称为TableModelEvent事件。通过addTableModelListener方法为表格添加此种事件监听器
17JTree
用来产生树状结构来直观地表现层次关系,有根节点、树枝节点、树叶节点
构造方法有多种,参数可以是一个Hashtable,也可以是TreeNode或TreeModel对象
可以使用JComponent提供的putClientProperty方法来设置JTree外观,也可以使用TreeCellRenderer来个性化各类节点的显示样式
18 Action对象
18.1 Action的用途
Action接口是对ActionListener接口的一个有用的扩展,它的继承关系如下
public interface Action extends ActionListener
在很多既有菜单又有工具栏的应用程序中,我们可以看到某条菜单和工具栏的功能是相同的,按照前面所讲的方法,我

们需要为每个组件一一添加事件监听器,并在其处理程序中写入相同的代码,程序就会显得比较繁琐。在这种场合,可以考虑使用Action对象实现此功能
还可以通过它对不同组件的显示文字、图标、快捷键、提示文字、是否可用等属性进行统一的设置
18.2创建Action对象
通常我们首先需要创建一个继承抽象类AbstractAction类的子类,然后再实例化这个子类
AbstractAction抽象类提供了Action接口的默认实现,而且还提供了一些获取和设置Action域属性的方法。我们在继承它创建自己需要的子类的时候,只需要通过这些方法
设置需要的属性值
定义actionPerformed方法
18.3使用Action对象
可通过GUI组件的setAction方法把Action关联到此GUI组件。每个具有addActionListener方法的组件也都具有setAction方法
但setAction方法并不是addActionLilstener方法的替换:Action是一个事件监听器,如果除此之外还需要添加别的监听器,则应该使用addActionListener方法
对给定的GUI组件,你可以调用setAction不止一次,但组件和上一个Action对象之间的关联会被删除
18.4效果
通过setAction方法把Action对象关联到某GUI组件后,会有如下效果
此组件的属性会被升级到符合这个Action对象的属性,例如如果设置了Action对象的文字和图标值,那么组件的文字和图标也会被重新设置成同样的值。
这个Action对象会被注册为此组件的一个事件监听器对象
如果改变了Action对象的属性或方法,则所有和它关联的组件的使能状态也会发生相应改变
18,5实例:
/* Uses actions with a tool bar and a menu. */
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JToolBar;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.JMenuItem;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
public class ActionDemo extends JFrame {
protected JTextArea textArea;
protected String newline = "\n";
protected Action leftAction;
protected Action middleAction;
protected Action rightAction;
public ActionDemo() {
super("ActionDemo");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
//Create the toolbar and menu.
JToolBar toolBar = new JToolBar();
JMenu mainMenu = new JMenu("Menu");
createActionComponents(toolBar, mainMenu);
//Create the text area used for output.
textArea = new JTextArea(5, 30);
JScrollPane scrollPane = new JScrollPane(textArea);
//Lay out th

e content pane.
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
contentPane.setPreferredSize(new Dimension(400, 150));
contentPane.add(toolBar, BorderLayout.SOUTH);
contentPane.add(scrollPane, BorderLayout.CENTER);
setContentPane(contentPane);
//Set up the menu bar.
JMenuBar mb = new JMenuBar();
mb.add(mainMenu);
mb.add(createAbleMenu());
setJMenuBar(mb);
}

protected void createActionComponents(JToolBar toolBar,
JMenu mainMenu) {
JButton button = null;
JMenuItem menuItem = null;
//first button and menu item
leftAction = new AbstractAction("Go left",
new ImageIcon("./build/classes/left.gif")) {
public void actionPerformed(ActionEvent e) {
displayResult("Action for first button/menu item", e);
}
};
button = toolBar.add(leftAction);
button.setText(""); //an icon-only button
button.setToolTipText("This is the left button");
menuItem = mainMenu.add(leftAction);
menuItem.setIcon(null); //arbitrarily chose not to use icon in menu
//second button and menu item
middleAction = new AbstractAction("Do something",
new ImageIcon("./build/classes/middle.gif")) {
public void actionPerformed(ActionEvent e) {
displayResult("Action for second button/menu item", e);
}
};
button = toolBar.add(middleAction);
button.setText("");
button.setToolTipText("This is the middle button");
menuItem = mainMenu.add(middleAction);
menuItem.setIcon(null); //arbitrarily chose not to use icon in menu
//third button and menu item
rightAction = new AbstractAction("Go right",
new ImageIcon("./build/classes/right.gif")) {
public void actionPerformed(ActionEvent e) {
displayResult("Action for third button/menu item", e);
}
};
button = toolBar.add(rightAction);
button.setText("");
button.setToolTipText("This is the right button");
menuItem = mainMenu.add(rightAction);
menuItem.setIcon(null); //arbitrarily chose not to use icon in menu
}
protected JMenu createAbleMenu() {
JMenu ableMenu = new JMenu("Action State");
JCheckBoxMenuItem cbmi = null;
cbmi = new JCheckBoxMenuItem("First action enabled");
cbmi.setSelected(true);
cbmi.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
JCheckBoxMenuItem mi = (JCheckBoxMenuItem)(e.getSource());
boolean selected =(e.getStateChange() == ItemEvent.SELECTED);
leftA

ction.setEnabled(selected);
}
});
ableMenu.add(cbmi);
//…这里省略了增加另外两个类似的菜单复选框的语句…
return ableMenu;
}
protected void displayResult(String actionDescription,ActionEvent e) {
String s = ("Action event detected by: "
+ actionDescription
+ newline
+ " Event source: " + e.getSource()
+ newline);
textArea.append(s);
}

public static void main(String[] args) {
ActionDemo frame = new ActionDemo();
frame.pack();
frame.setVisible(true);
}
}
说明
创建了三个Action对象,在每个对象中定义了文本、图片等属性以及actionPerformed方法
分别为三组按钮、菜单分别添加三个Action对象,使组内的按钮、菜单具有相同的功能
创建了三个复选框菜单选项,在其事件监听器ItemListener()中改变Action对象的enabled属性,因此可以同时改变按钮、菜单的使能状态

相关文档
相关文档 最新文档