[Java]Swing基础编程【1】基本组件的使用

来源:互联网 发布:站长吧源码论坛 编辑:程序博客网 时间:2024/05/17 23:59

 Swing是Java的用户界面包,里面包含许多与图形用户界面相关的组件。

编写此类代码的步骤一般如下:

1、先定义好所需要的低层次组件;

2、创建一个init()方法,用于初始化,并在初始化的时候进行组件的组装,并定义组件需要监听的内容和相应行为;

3、在main()方法中调用初始化方法,使界面呈现。

下面以《疯狂Java讲义》一书中代码进行说明。该代码编写了一个基本的界面,一些基本的监听调用,主要功能为通过右键菜单改变界面风格。

/** *  */package swingcomponent;import java.awt.BorderLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.InputEvent;import javax.swing.*;/** * @author wangyubin * */public class SwingComponent {/** * @param args *///定义一个框架,名称为测试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 bg =new ButtonGroup();//定义一个复选框,初始为未选中状态JCheckBox married=new JCheckBox("是否已婚",false);// 定义一个字符串数组,储存颜色信息String[] colors=new String[]{"红色","绿色","蓝色"};//定义一个下拉选择框JComboBox<String> colorChooser=new JComboBox<>(colors);//定义一个列表选择框JList<String> colorList=new JList<>(colors);//定义一个8行,20列的多行文本域JTextArea ta =new JTextArea(8,20);//定义一个40列的单行文本域JTextField name=new JTextField(40);//创建一个菜单栏存放菜单JMenuBar mb=new JMenuBar();//定义文件菜单与编辑菜单,将存放于菜单栏JMenu file=new JMenu("文件");JMenu edit=new JMenu("编辑");//创建新建菜单,并为之指定图标Icon newIcon=new ImageIcon("ico/new.png");JMenuItem newItem=new JMenuItem("新建",newIcon);//创建保存菜单,并为之指定图标Icon saveIcon=new ImageIcon("ico/save.png");JMenuItem saveItem=new JMenuItem("保存",saveIcon);//创建退出菜单,并为之指定图标Icon exitIcon=new ImageIcon("ico/exit.png");JMenuItem exitItem=new JMenuItem("退出",exitIcon);//创建一个具有选择按钮的菜单JCheckBoxMenuItem autoWrap=new JCheckBoxMenuItem("自动换行");//创建复制菜单,并为之指定图标JMenuItem copyItem=new JMenuItem("复制",new ImageIcon("ico/copy.png"));//创建粘贴菜单,并为之指定图标JMenuItem pasteItem=new JMenuItem("粘贴",new ImageIcon("ico/paste.png"));//创建格式菜单JMenu format=new JMenu("格式");JMenuItem commentItem=new JMenuItem("注释");JMenuItem cancelItem=new JMenuItem("取消注释");//定义一个右键菜单用于设置程序风格JPopupMenu pop=new JPopupMenu();//创建一个用于组合5个风格菜单项的按钮组ButtonGroup flavorGroup=new ButtonGroup();//创建5个单选按钮,用于设定程序的外观风格JRadioButtonMenuItem metalItem=new JRadioButtonMenuItem("Metal风格",true);JRadioButtonMenuItem nimbusItem=new JRadioButtonMenuItem("Nimbus风格");JRadioButtonMenuItem windowsItem=new JRadioButtonMenuItem("Windows风格");JRadioButtonMenuItem classicItem=new JRadioButtonMenuItem("Windows经典风格");JRadioButtonMenuItem motifItem=new JRadioButtonMenuItem("Motif风格");//-----------------------------------用于执行界面初始化的init方法-----------------------------public void init(){//创建一个装载了文本框、按钮的JPanelJPanel bottom =new JPanel();bottom.add(name);bottom.add(ok);f.add(bottom,BorderLayout.SOUTH);//创建一个装载了下拉选择框、三个JCheckBox的JPanelJPanel checkPanel=new JPanel();checkPanel.add(colorChooser);bg.add(male);bg.add(female);checkPanel.add(male);checkPanel.add(female);checkPanel.add(married);//创建一个垂直排列组件的Box,盛装多行文本域JPanelBox topLeft=Box.createVerticalBox();//使用JScrollPane作为普通组件的ViewPortJScrollPane taJsp=new JScrollPane(ta);topLeft.add(taJsp);topLeft.add(checkPanel);//创建一个水平排列组件的Box,盛装topLeft,colorListBox top=Box.createHorizontalBox();top.add(topLeft);top.add(colorList);//将top Box容器添加到窗口的中间f.add(top);//不加第二个参数则默认为中间//--------------------下面开始组合菜单,并为菜单添加监听器----------------------//为newItem设置快捷键,设置快捷键时要使用大写字母newItem.setAccelerator(KeyStroke.getKeyStroke('N',InputEvent.CTRL_MASK)); //newItem.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){   //监听到后进行操作ta.append("用户单击了“新建”菜单\n");}});//为file菜单添加菜单项file.add(newItem);file.add(saveItem);file.add(exitItem);//为edit菜单添加菜单项edit.add(autoWrap);//添加菜单分割线edit.addSeparator();edit.add(copyItem);edit.add(pasteItem);//为组件添加提示信息commentItem.setToolTipText("将程序代码注释起来!");cancelItem.setToolTipText("取消注释");//为format菜单添加添加菜单项format.add(commentItem);format.add(cancelItem);edit.addSeparator();//edit.add(new JMenuItem("-"));//把format菜单添加到eidt菜单中,从而形成二级菜单edit.add(format);mb.add(file);mb.add(edit);//为f窗口设置菜单条f.setJMenuBar(mb);//----------下面开始组合右键菜单,并安装右键菜单----------flavorGroup.add(metalItem);flavorGroup.add(nimbusItem);flavorGroup.add(windowsItem);flavorGroup.add(classicItem);flavorGroup.add(motifItem);pop.add(metalItem);pop.add(nimbusItem);pop.add(windowsItem);pop.add(classicItem);pop.add(motifItem);//为5个风格菜单创建事件监听器ActionListener flavorListener=new ActionListener(){public void actionPerformed(ActionEvent e){try{switch(e.getActionCommand()){case "Metal风格":changeFlavor(1);break;case "Nimbus风格":changeFlavor(2);break;case "Windows风格":changeFlavor(3);break;case "Windows经典风格":changeFlavor(4);break;case "Motif风格":changeFlavor(5);break;    }}catch(Exception ee){ee.printStackTrace();}}};// 为5个风格菜单项添加事件监听器metalItem.addActionListener(flavorListener);nimbusItem.addActionListener(flavorListener);windowsItem.addActionListener(flavorListener);classicItem.addActionListener(flavorListener);motifItem.addActionListener(flavorListener);//调用该方法即可设置右键菜单,无需使用事件机制ta.setComponentPopupMenu(pop);//设置关闭窗口时,退出程序f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.pack();f.setVisible(true);}private void changeFlavor(int flavor) throws Exception{switch(flavor){//设置风格case 1:UIManager.setLookAndFeel("javax.swing.plaf,metal.MetalLookAndFeel");break;case 2:UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");break;case 3:UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");break;case 4:UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsclassicLookAndFeel");break;case 5:UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");break;}//更新f窗口内顶级容器以及内部所有组件的UISwingUtilities.updateComponentTreeUI(f.getContentPane());//更新mbc菜单条以及内部所有组件的UISwingUtilities.updateComponentTreeUI(mb);//更新pop右键菜单以及内部所有组件的UISwingUtilities.updateComponentTreeUI(pop);}public static void main(String[] args) {// TODO 自动生成的方法存根//设置Swing窗口使用Java风格//JFrame.setDefaultLookAndFeelDecorated(true);new SwingComponent().init();}}

编写Swing组件的时候需要注意各组件之间的层级关系。

将Swing组件按功能来分,又可以分为如下几类:

1、顶层容器:JFrame,JApplet,JDialog,JWindow

2、中间容器:JPanel,JScrollPane,JSplitPane,JToolBar等。

3、特殊容器:在用户界面上具有特殊作用的中间容器,如JInternalFrame,JRootPane,JLayeredPane和JDestopPane等。

4、基本组件:实现人机交互的组件,如JButton,JComboBox.JList,JMenu,JSlider等。

5、不可编辑信息的显示组件:如JLabel,JProgressBar和JToolTIp等。

6、可编辑信息的显示组件:如JTable,JTextArea和JTextField等

7、特殊对话框组件:可以直接产生特殊对话框的组件,如JColorChooser和JFielChooser等。


附:(一遍编程一遍学英文!)

pane 窗格
panel 镶板,面
vertical 垂直的
horizontal 水平的
accelerator 加速器,指快捷键
stroke 击打键盘
flavor 风格

0 0