12.4.3 Swing基本组件

如前所述,Swing组件与AWT组件基本类似,只是类名比AWT组件前多一个字母“J”,如:JButton(按键)、JLabel(标签)、JTextField(单行文本框)、JTextArea(文本输入区)、JCheckBox(复选框)、JRadioButton(单选按钮)、JList(列表框)、JComboBox(下拉列表)等,因此对这些基本组件的使用方法可以参考本章第3节。下面,我们直接通过示例程序了解上述组件的基本用法。

例1:Swing基本组件的使用

import javax.swing.*;

import java.awt.*;

public class SwingTest{ 

  JFrame f = new JFrame("测试"); 

  //定义一个按钮,并为之指定图标 

  Icon okIcon = new ImageIcon("ico/ok.png"); 

  JButton ok = new JButton("确认" , okIcon); 

  //定义一个单选按钮,初始处于选中状态 

  JRadioButton male = new JRadioButton("男" , true); 

  //定义一个单按钮,初始处于没有选中状态 

  JRadioButton female = new JRadioButton("女" , false); 

  //定义一个ButtonGroup,用于将上面两个JRadioButton组合在一起 

  ButtonGroup bg = new ButtonGroup(); 

  //定义一个复选框,初始处于没有选中状态。 

  JCheckBox married = new JCheckBox("是否已婚?" , false); 

  String[] colors = new String[]{"红色" , "绿色"  , "蓝色"}; 

  //定义一个下拉选择框 

  JComboBox colorChooser = new JComboBox(colors); 

  //定义一个列表选择框 

  JList colorList = new JList(colors); 

  //定义一个8行、20列的多行文本域 

  JTextArea ta = new JTextArea(8, 20); 

  //定义一个40列的单行文本域 

  JTextField name = new JTextField(40);

  public void init(){ 

  //创建一个装载了文本框、按钮的JPanel 

  JPanel bottom = new JPanel(); 

  bottom.add(name); 

  bottom.add(ok); 

  f.add(bottom , BorderLayout.SOUTH); 

  //创建一个装载了下拉选择框、三个JCheckBox的JPanel 

  JPanel checkPanel = new JPanel(); 

  checkPanel.add(colorChooser); 

  bg.add(male); 

  bg.add(female); 

  checkPanel.add(male); 

  checkPanel.add(female); 

  checkPanel.add(married); 

  //创建一个垂直排列组件的Box,装多行文本域JPanel 

  Box topLeft = Box.createVerticalBox(); 

  //使用JScrollPane作为普通组件的JViewPort 

  JScrollPane taJsp = new JScrollPane(ta); 

  topLeft.add(taJsp); 

  topLeft.add(checkPanel); 

  //创建一个垂直排列组件的Box,盛装topLeft、colorList 

  Box top = Box.createHorizontalBox(); 

  top.add(topLeft); 

  top.add(colorList); 

  //将top Box容器添加到窗口的中间 

  f.add(top); 

  //设置关闭窗口时,退出程序 

  f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

  f.pack(); 

  f.setVisible(true); 

  } 

  public static void main(String[] args) { 

  //设置Swing窗口使用Java风格 

  JFrame.setDefaultLookAndFeelDecorated(true);

  new SwingTest ().init(); 

  } 

程序的运行结果如下:

 

例2:JList组件的使用

import java.awt.*;

import javax.swing.*;

import javax.swing.event.*;

import java.awt.event.*;

class JListTest extends JFrame{

private JList list = new JList();

private JTextArea ta = new JTextArea(6,8);

public JListTest(String title){

  super(title);

  String[] citys =

  {"北京","天津","上海","广州","深圳","南京","重庆","沈阳","西安"};

  list.setListData(citys);

  Container contentPane = this.getContentPane();

  contentPane.setLayout(new FlowLayout(5));//在界面上显示5行

  list.setVisibleRowCount(5);

  contentPane.add(new JScrollPane(list));//使JList带有滚动条

  contentPane.add(ta);

  //注册监听器

  list.addListSelectionListener(new MyListSelectionListener());

  pack();//重新调整

  setVisible(true);

  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

//处理ListSelection事件

private class MyListSelectionListener implements ListSelectionListener {

  public void valueChanged(ListSelectionEvent arg0) {

StringBuffer selectedCitys = new StringBuffer();

Object[] selectedItems = list.getSelectedValues();

for(int i=0;i<selectedItems.length;i++){

  selectedCitys.append(selectedItems[i].toString()+"\n"); 

}

ta.setText(selectedCitys.toString());

pack();

  } 

}

}

public class ListTest {

public static void main(String[] args) {

  new JListTest("JList测试");

}

}

程序运行结果如下:

 

除上述常用组件外,Swing还提供了很多其它有用的组件,包括:

1、JToolBar

JToolBar(工具栏)是提供快速访问常用菜单命令的一个按钮栏,一般和菜单栏一起出现,当然也可独立出现。JToolBar提供了四个构造方法用于创建JToolBar对象。

构造方法  说明

JToolBar() 创建新的工具栏;默认的方向为 HORIZONTAL

JToolBar(int orientation) 创建具有指定 orientation 的新工具栏

JToolBar(String name)  创建一个具有指定 name 的新工具

JToolBar(String name,

int orientation) 创建一个具有指定 name 和 orientation 的新工具栏

工具栏的添加很简单,直接使用JFrame的add方法即可完成添加,工具栏内可添加按钮等组件。

2、JOptionPane

JOptionPane提供了许多对话框样式,该类能够让你在不编写任何专门对话框代码的情况下弹出一个简单的对话框。

JOptionPane类提供了7个构造方法用于创建JOptionPane的类对象,不过在实际使用时,通常不是用new方式创建,而是使用JOptionPane类提供的一些静态方法产生。JOptionPane有四个静态方法来显示这些简单对话框:

(1)showMessageDialog:提示信息对话框,这种对话框通常只含有一个“确定”按钮。

(2)showConfirmDialog:确认对话框,这类对话框通常会询问用户一个问题,要求用户做YES/NO的回答。

(3)showOptionDialog:选择对话框,这类对话框可以让用户自己定义对话框的类型。

(4)showInputDialog:输入对话框,这类对话框可以让用户输入相关的信息,当用户完成输入并按下确定按钮后,系统会得到用户所输入的信息。

3、JFileChooser 文件对话框

JFileChooser表示文件对话框,常用来弹出一个文件选择对话框来为用户提供打开文件、保存文件等操作。JFileChooser类提供了6个构造方法用于创建JFileChooser类对象,常用的有3个:

构造方法 说明

JFileChooser()  构造一个指向用户默认目录的 JFileChooser。

JFileChooser(String currentDirectoryPath) 构造一个使用给定路径的 JFileChooser。

JFileChooser(File currentDirectory)  使用给定的 File 作为路径来构造一个 JFileChooser

JFileChooser类中其它常用方法如下表。

成员方法 说明

int showOpenDialog(Component parent)  弹出一个 "Open File" 文件选择器对话框

int showSaveDialog(Component parent)  弹出一个 "Save File" 文件选择器对话框

showDialog(Component parent,  String approveButtonText) 弹出具有自定义approve 按钮的自定义文件选择器对话框

File getSelectedFile() 返回选中的文件

对于showOpenDialog等显示对话框的方法将返回一个整数,可能取值情况包括:

JFileChooser.CANCEL_OPTION 按取消键退出对话框,无文件选取

JFileChooser.APPROVE_OPTION  正常选取文件

JFileChooser.ERROR_OPTION 发生错误或者该对话框已被解除而退出对话框

所以在文件选取对话框交互结束后,应进行判断,是否从对话框中选取了文件,然后根据返回值情况进行处理。

例3:JFileChooser类及其在文件选择中的应用

import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

class JFileChooserTest extends JFrame{

private JLabel label = new JLabel("所选文件路径:");

private JTextField tfFileName = new JTextField(25);

private JButton btnOpen = new JButton("浏览");

public JFileChooserTest(String title){

  super(title);

  Container contentPane = this.getContentPane();

  contentPane.setLayout(new FlowLayout(5));

  contentPane.add(label);

  contentPane.add(tfFileName);

  contentPane.add(btnOpen);

  pack();

  setVisible(true);

  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  //监听btnOpen按钮

  btnOpen.addActionListener(new MyActionListener());

}

//Action事件处理

private class MyActionListener implements ActionListener{

  public void actionPerformed(ActionEvent arg0) {

JFileChooser fc = new JFileChooser("D:\\");

int val = fc.showOpenDialog(null);//文件打开对话框

if(val==fc.APPROVE_OPTION){//正常选择文件

  tfFileName.setText(fc.getSelectedFile().toString());//取得文件名及路径

}

else{//未正常选择文件,如选择取消按钮

  tfFileName.setText("未选取文件");

}

  } 

}

}

public class test {

public static void main(String[] args) {

  new JFileChooserTest("JFileChooser测试");

}

}

程序运行结果如图:

 

注意:这里我们只是演示了如何将读取的文件名显示出来,对于进一步的文件读取、编辑及保存工作,同学们可结合第10章Java I/O流继续完善本实例。