100个Java经典例证
100个Java经典例子package?test11????import?java.awt.event.ActionEvent??import?java.awt.event.Actio
100个Java经典例子
- package?test11;????
- import?java.awt.event.ActionEvent;??import?java.awt.event.ActionListener;??
- import?java.awt.event.KeyEvent;????
- import?javax.swing.AbstractButton;??import?javax.swing.ImageIcon;??
- import?javax.swing.JButton;??import?javax.swing.JFrame;??
- import?javax.swing.JPanel;????
- /**??*?Title:?按钮演示?
- ?*?Description:?提供一个按钮的演示。如何实现按钮和是一个按钮失效??*?Filename:??
- ?*/??public?class?ButtonDemo?extends?JPanel??
- ????????????????????????implements?ActionListener?{????????
- ????private?static?final?long?serialVersionUID?=?1L;??????protected?JButton?b1,?b2,?b3;??
- /**??*方法说明:构造器,初始图形界面构建?
- ?*/??????public?ButtonDemo()?{??
- ????????ImageIcon?leftButtonIcon?=?createImageIcon("images/right.gif");??????????ImageIcon?middleButtonIcon?=?createImageIcon("images/middle.gif");??
- ????????ImageIcon?rightButtonIcon?=?createImageIcon("images/left.gif");????
- ????????b1?=?new?JButton("失效中间按钮(D)",?leftButtonIcon);??????????b1.setVerticalTextPosition(AbstractButton.CENTER);//水平中间对齐??
- ????????b1.setHorizontalTextPosition(AbstractButton.LEADING);//相当于LEFT??????????b1.setMnemonic(KeyEvent.VK_D);//将b1邦定alt+D键??
- ????????b1.setActionCommand("disable");????
- ????????b2?=?new?JButton("M中间按钮",?middleButtonIcon);??????????b2.setVerticalTextPosition(AbstractButton.BOTTOM);??
- ????????b2.setHorizontalTextPosition(AbstractButton.CENTER);??????????b2.setMnemonic(KeyEvent.VK_M);//将b2邦定alt+M键??
- ??????????b3?=?new?JButton("E激活中间按钮",?rightButtonIcon);??
- ????????b3.setMnemonic(KeyEvent.VK_E);//将b3邦定alt+E键??????????b3.setActionCommand("enable");??
- ????????b3.setEnabled(false);????
- ????????//给1和3添加事件监听??????????b1.addActionListener(this);??
- ????????b3.addActionListener(this);??????????//设置按钮提示文本??
- ????????b1.setToolTipText("点击这个按钮,将使中间的按钮失效!");??????????b2.setToolTipText("点击这个按钮,没有任何的事件发生!");??
- ????????b3.setToolTipText("点击这个按钮,将使中间的按钮有效");????
- ????????//将按钮添加到JPanel中??????????add(b1);??
- ????????add(b2);??????????add(b3);??
- ????}??/**?
- ?*方法说明:事件处理??*/??
- ????public?void?actionPerformed(ActionEvent?e)?{??????????if?("disable".equals(e.getActionCommand()))?{??
- ????????????b2.setEnabled(false);??????????????b1.setEnabled(false);??
- ????????????b3.setEnabled(true);??????????}?else?{??
- ????????????b2.setEnabled(true);??????????????b1.setEnabled(true);??
- ????????????b3.setEnabled(false);??????????}??
- ????}??/**?
- ?*方法说明:创建图标,??*输入参数:String?path?图标所在的路径?
- ?*返回类型:ImageIcon?图标对象??*/??
- ????protected?static?ImageIcon?createImageIcon(String?path)?{??????????java.net.URL?imgURL?=?ButtonDemo.class.getResource(path);??
- ????????if?(imgURL?!=?null)?{??????????????return?new?ImageIcon(imgURL);??
- ????????}?else?{??????????????System.err.println("Couldn't?find?file:?"?+?path);??
- ????????????return?null;??????????}??
- ????}??/**?
- ?*方法说明:主方法??*/??
- ????public?static?void?main(String[]?args)?{??????????//设置使用新的swing界面??
- ????????JFrame.setDefaultLookAndFeelDecorated(true);????
- ????????//创建一个窗体??????????JFrame?frame?=?new?JFrame("ButtonDemo");??
- ????????frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);????
- ????????//创建一个面板??????????ButtonDemo?newContentPane?=?new?ButtonDemo();??
- ????????newContentPane.setOpaque(true);???????????frame.setContentPane(newContentPane);??
- ??????????//显示窗体??
- ????????frame.pack();??????????frame.setVisible(true);??
- ????}??}??
view plain
- package?test12;????
- import?java.awt.*;??import?java.awt.event.*;??
- import?javax.swing.*;??/**?
- ?*?Title:?检查盒演示??*?Description:?选择不同的选择框显示不同的图片?
- ?*?Filename:?CheckBoxDemo.java<??*/??
- public?class?CheckBoxDemo?extends?JPanel????????????????????????????implements?ItemListener?{??
- ?????????private?static?final?long?serialVersionUID?=?1L;??
- ????JCheckBox?chinButton;??????JCheckBox?glassesButton;??
- ????JCheckBox?hairButton;??????JCheckBox?teethButton;??
- ??????/*?
- ?????*?有四个检查盒,分别对应下巴、眼镜、头发和牙齿??????*?图片不是拼出来的,而是根据检查盒选择拼写图片文件名?
- ?????*?图片文件名的定义格式为"geek-XXXX.gif"??????*?其中?XXXX?根据检查盒的不同选择,而不同。它的格式如下:?
- ????????----?????????????//没有选择?
- ????????c---?????????????//一个选择?
- ???????-g--????????--h-?
- ???????---t??
- ???????cg--?????????????//两个选择????????c-h-?
- ???????c--t????????-gh-?
- ???????-g-t????????--ht?
- ????????-ght?????????????//三个选择?
- ???????c-ht????????cg-t?
- ???????cgh-??
- ???????cght?????????????//所有都选??????*/??
- ??????StringBuffer?choices;??
- ????JLabel?pictureLabel;????
- ????public?CheckBoxDemo()?{??????????super(new?BorderLayout());??
- ??????????//创建检查盒??
- ????????chinButton?=?new?JCheckBox("下巴(c)");??????????chinButton.setMnemonic(KeyEvent.VK_C);??
- ????????chinButton.setSelected(true);????
- ????????glassesButton?=?new?JCheckBox("眼镜(g)");??????????glassesButton.setMnemonic(KeyEvent.VK_G);??
- ????????glassesButton.setSelected(true);????
- ????????hairButton?=?new?JCheckBox("头发(h)");??????????hairButton.setMnemonic(KeyEvent.VK_H);??
- ????????hairButton.setSelected(true);????
- ????????teethButton?=?new?JCheckBox("牙齿(t)");??????????teethButton.setMnemonic(KeyEvent.VK_T);??
- ????????teethButton.setSelected(true);????
- ????????//给检查盒添加监听??????????chinButton.addItemListener(this);??
- ????????glassesButton.addItemListener(this);??????????hairButton.addItemListener(this);??
- ????????teethButton.addItemListener(this);????
- ????????choices?=?new?StringBuffer("cght");????
- ????????//放置一个带图片的标签??????????pictureLabel?=?new?JLabel();??
- ????????pictureLabel.setFont(pictureLabel.getFont().deriveFont(Font.ITALIC));??????????updatePicture();??
- ??????????//将检查盒放置到面版中??
- ????????JPanel?checkPanel?=?new?JPanel(new?GridLayout(0,?1));??????????checkPanel.add(chinButton);??
- ????????checkPanel.add(glassesButton);??????????checkPanel.add(hairButton);??
- ????????checkPanel.add(teethButton);????
- ????????add(checkPanel,?BorderLayout.LINE_START);??????????add(pictureLabel,?BorderLayout.CENTER);??
- ????????setBorder(BorderFactory.createEmptyBorder(20,20,20,20));??????}??
- /**??*<br>方法说明:监听检查盒事件,拼凑图片的文件名XXXX部分?
- ?*<br>输入参数:??*<br>返回类型:?
- ?*/??????public?void?itemStateChanged(ItemEvent?e)?{??
- ????????int?index?=?0;??????????char?c?=?'-';??
- ????????Object?source?=?e.getItemSelectable();????
- ????????if?(source?==?chinButton)?{??????????????index?=?0;??
- ????????????c?=?'c';??????????}?else?if?(source?==?glassesButton)?{??
- ????????????index?=?1;??????????????c?=?'g';??
- ????????}?else?if?(source?==?hairButton)?{??????????????index?=?2;??
- ????????????c?=?'h';??????????}?else?if?(source?==?teethButton)?{??
- ????????????index?=?3;??????????????c?=?'t';??
- ????????}????????????
- ????????//取消选择事件??????????if?(e.getStateChange()?==?ItemEvent.DESELECTED)?{??
- ????????????c?=?'-';??????????}??
- ??????????//改变文件名字XXXX??
- ????????choices.setCharAt(index,?c);????
- ????????updatePicture();??????}??
- /**??*<br>方法说明:绘制图片?
- ?*<br>输入参数:??*<br>返回类型:?
- ?*/??????protected?void?updatePicture()?{??
- ????????//将得到的图片制成图标??????????ImageIcon?icon?=?createImageIcon(??
- ????????????????????????????????????"images/geek/geek-"??????????????????????????????????????+?choices.toString()??
- ????????????????????????????????????+?".gif");??????????pictureLabel.setIcon(icon);??
- ????????pictureLabel.setToolTipText(choices.toString());??????????if?(icon?==?null)?{??
- ????????????pictureLabel.setText("没有发现图片");??????????}?else?{??
- ????????????pictureLabel.setText(null);??????????}??
- ????}??/**?
- ?*<br>方法说明:获取图标??*<br>输入参数:String?path?图片路径?
- ?*<br>返回类型:ImageIcon对象??*/??
- ????protected?static?ImageIcon?createImageIcon(String?path)?{??????????java.net.URL?imgURL?=?CheckBoxDemo.class.getResource(path);??
- ????????if?(imgURL?!=?null)?{??????????????return?new?ImageIcon(imgURL);??
- ????????}?else?{??????????????System.err.println("Couldn't?find?file:?"?+?path);??
- ????????????return?null;??????????}??
- ????}??/**?
- ?*<br>方法说明:主方法??*<br>输入参数:?
- ?*<br>返回类型:??*/??
- ????public?static?void?main(String?s[])?{???????????JFrame.setDefaultLookAndFeelDecorated(true);??
- ??????????//创建一个窗体,??
- ????????JFrame?frame?=?new?JFrame("CheckBoxDemo");??????????frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);??
- ??????????//创建一个面板??
- ????????JComponent?newContentPane?=?new?CheckBoxDemo();??????????newContentPane.setOpaque(true);??
- ????????frame.setContentPane(newContentPane);????
- ????????//显示窗体??????????frame.pack();??
- ????????frame.setVisible(true);??????}??
- }??
?
view plain
- package?test13;????
- import?java.awt.*;??import?java.awt.event.*;??
- import?javax.swing.*;??import?java.util.*;??
- import?java.text.SimpleDateFormat;??/**?
- ?*?Title:?ComboBox下拉域演示</p>??*?Description:?通过选择或这输入一种日期格式来格式化今天的日期?
- ?*?Filename:?ComboBoxDemo.java??*/??
- ??public?class?ComboBoxDemo?extends?JPanel??
- ???????????????????????????implements?ActionListener?{????
- ????private?static?final?long?serialVersionUID?=?1L;??????static?JFrame?frame;??
- ????JLabel?result;??????String?currentPattern;??
- /**??*方法说明:构造器。初始化窗体构件?
- ?*/??????public?ComboBoxDemo()?{??
- ????????setLayout(new?BoxLayout(this,?BoxLayout.PAGE_AXIS));??????????String[]?patternExamples?=?{??
- ?????????????????"dd?MMMMM?yyyy",???????????????????"dd.MM.yy",??
- ?????????????????"MM/dd/yy",???????????????????"yyyy.MM.dd?G?'at'?hh:mm:ss?z",??
- ?????????????????"EEE,?MMM?d,?''yy",???????????????????"h:mm?a",??
- ?????????????????"H:mm:ss:SSS",???????????????????"K:mm?a,z",??
- ?????????????????"yyyy.MMMMM.dd?GGG?hh:mm?aaa"???????????????????};??
- ??????????currentPattern?=?patternExamples[0];??
- ??????????//设置一个规范的用户界面??
- ????????JLabel?patternLabel1?=?new?JLabel("输入一个字符格式或者");??????????JLabel?patternLabel2?=?new?JLabel("从下拉列表中选择一种:");??
- ??????????JComboBox?patternList?=?new?JComboBox(patternExamples);??
- ????????patternList.setEditable(true);//标注这里ComboBox可进行编辑??????????patternList.addActionListener(this);??
- ??????????//创建一个显示结果用户界面??
- ????????JLabel?resultLabel?=?new?JLabel("当前?日期/时间",??????????????????????????????????????????JLabel.LEADING);//相当于LEFT??
- ????????result?=?new?JLabel("?");??????????result.setForeground(Color.black);??
- ????????result.setBorder(BorderFactory.createCompoundBorder(???????????????BorderFactory.createLineBorder(Color.black),??
- ?????????????BorderFactory.createEmptyBorder(5,5,5,5)??????????));??
- ??????????//布置构件??
- ????????JPanel?patternPanel?=?new?JPanel();??????????patternPanel.setLayout(new?BoxLayout(patternPanel,??
- ???????????????????????????????BoxLayout.PAGE_AXIS));??????????patternPanel.add(patternLabel1);??
- ????????patternPanel.add(patternLabel2);??????????patternList.setAlignmentX(Component.LEFT_ALIGNMENT);??
- ????????patternPanel.add(patternList);????
- ????????JPanel?resultPanel?=?new?JPanel(new?GridLayout(0,?1));??????????resultPanel.add(resultLabel);??
- ????????resultPanel.add(result);????
- ????????patternPanel.setAlignmentX(Component.LEFT_ALIGNMENT);??????????resultPanel.setAlignmentX(Component.LEFT_ALIGNMENT);??
- ??????????add(patternPanel);??
- ????????add(Box.createRigidArea(new?Dimension(0,?10)));??????????add(resultPanel);??
- ??????????setBorder(BorderFactory.createEmptyBorder(10,10,10,10));??
- ??????????reformat();??
- ????}???/**?
- ?*方法说明:事件处理??*/??
- ????public?void?actionPerformed(ActionEvent?e)?{??????????JComboBox?cb?=?(JComboBox)e.getSource();??
- ????????String?newSelection?=?(String)cb.getSelectedItem();??????????currentPattern?=?newSelection;??
- ????????reformat();??????}??
- /**??*方法说明:格式和显示今天的日期?
- ?*/??????public?void?reformat()?{??
- ????????Date?today?=?new?Date();??????????SimpleDateFormat?formatter?=??
- ???????????new?SimpleDateFormat(currentPattern);??????????try?{??
- ????????????String?dateString?=?formatter.format(today);??????????????result.setForeground(Color.black);??
- ????????????result.setText(dateString);??????????}?catch?(IllegalArgumentException?iae)?{??
- ????????????result.setForeground(Color.red);??????????????result.setText("Error:?"?+?iae.getMessage());??
- ????????}??????}??
- /**??*方法说明:主方法?
- ?*/??????public?static?void?main(String[]?args)?{??
- ????????JFrame.setDefaultLookAndFeelDecorated(true);????
- ????????//创建一个窗体??????????frame?=?new?JFrame("ComboBoxDemo");??
- ????????frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);????
- ????????//创建一个面版容器??????????JComponent?newContentPane?=?new?ComboBoxDemo();??
- ????????newContentPane.setOpaque(true);??????????frame.setContentPane(newContentPane);??
- ??????????//显示窗体??
- ????????frame.pack();??????????frame.setVisible(true);??
- ????}??}??
?
view plain
- package?test14;????
- import?java.awt.*;??import?java.awt.event.*;??
- import?javax.swing.*;??import?javax.swing.event.*;??
- /**??*?Title:?列表框?
- ?*?Description:?通过输入框添加元素和点击“删除”按钮删除列表元素??*?Filename:?ListDemo.java?
- ?*/??public?class?ListDemo?extends?JPanel??
- ??????????????????????implements?ListSelectionListener?{??????private?static?final?long?serialVersionUID?=?1L;??
- ????private?JList?list;??????private?DefaultListModel?listModel;??
- ??????private?static?final?String?hireString?=?"添加";??
- ????private?static?final?String?fireString?=?"删除";??????private?JButton?fireButton;??
- ????private?JTextField?employeeName;????
- ????public?ListDemo()?{??????????super(new?BorderLayout());??
- ????????//构建List的列表元素??????????listModel?=?new?DefaultListModel();??
- ????????listModel.addElement("Alan?Sommerer");??????????listModel.addElement("Alison?Huml");??
- ????????listModel.addElement("Kathy?Walrath");??????????listModel.addElement("Lisa?Friendly");??
- ????????listModel.addElement("Mary?Campione");??????????listModel.addElement("Sharon?Zakhour");??
- ??????????//创建一个List构件,并将列表元素添加到列表中??
- ????????list?=?new?JList(listModel);??????????//设置选择模式为单选??
- ????????list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);??????????//初始化选择索引在0的位置,即第一个元素??
- ????????list.setSelectedIndex(0);??????????list.addListSelectionListener(this);??
- ????????//设置列表可以同时看5个元素??????????list.setVisibleRowCount(5);??
- ????????//给列表添加一个滑动块??????????JScrollPane?listScrollPane?=?new?JScrollPane(list);??
- ??????????JButton?hireButton?=?new?JButton(hireString);??
- ????????HireListener?hireListener?=?new?HireListener(hireButton);??????????hireButton.setActionCommand(hireString);??
- ????????hireButton.addActionListener(hireListener);??????????hireButton.setEnabled(false);??
- ??????????fireButton?=?new?JButton(fireString);??
- ????????fireButton.setActionCommand(fireString);??????????fireButton.addActionListener(new?FireListener());??
- ??????????employeeName?=?new?JTextField(10);??
- ????????employeeName.addActionListener(hireListener);??????????employeeName.getDocument().addDocumentListener(hireListener);??
- ????????@SuppressWarnings("unused")??????????String?name?=?listModel.getElementAt(??
- ??????????????????????????????list.getSelectedIndex()).toString();????
- ????????//创建一个面板??????????JPanel?buttonPane?=?new?JPanel();??
- ????????buttonPane.setLayout(new?BoxLayout(buttonPane,?????????????????????????????????????????????BoxLayout.LINE_AXIS));??
- ????????buttonPane.add(fireButton);??????????buttonPane.add(Box.createHorizontalStrut(5));??
- ????????buttonPane.add(new?JSeparator(SwingConstants.VERTICAL));??????????buttonPane.add(Box.createHorizontalStrut(5));??
- ????????buttonPane.add(employeeName);??????????buttonPane.add(hireButton);??
- ????????buttonPane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));????
- ????????add(listScrollPane,?BorderLayout.CENTER);??????????add(buttonPane,?BorderLayout.PAGE_END);??
- ????}??/**?
- ?*类说明:“添加”按钮监听??*类描述:当点击“添加”按钮后,实现将元素添加到列表框中?
- ?*/??????class?FireListener?implements?ActionListener?{??
- ????????public?void?actionPerformed(ActionEvent?e)?{???????????????
- ????????????int?index?=?list.getSelectedIndex();??????????????listModel.remove(index);??
- ??????????????int?size?=?listModel.getSize();??
- ??????????????if?(size?==?0)?{?//如果没有了选择项,则是“删除”按钮实效??
- ????????????????fireButton.setEnabled(false);????
- ????????????}?else?{?//选择了一个??????????????????if?(index?==?listModel.getSize())?{??
- ????????????????????//移除选项??????????????????????index--;??
- ????????????????}????
- ????????????????list.setSelectedIndex(index);??????????????????list.ensureIndexIsVisible(index);??
- ????????????}??????????}??
- ????}????
- /**??*类说明:“删除”按钮监听事件?
- ?*类描述:实现删除列表元素??*/??
- ????class?HireListener?implements?ActionListener,?DocumentListener?{??????????private?boolean?alreadyEnabled?=?false;??
- ????????private?JButton?button;????
- ????????public?HireListener(JButton?button)?{??????????????this.button?=?button;??
- ????????}????
- ????????//必须实现?ActionListener.??????????public?void?actionPerformed(ActionEvent?e)?{??
- ????????????String?name?=?employeeName.getText();????
- ????????????//如果输入空或有同名??????????????if?(name.equals("")?||?alreadyInList(name))?{??
- ????????????????Toolkit.getDefaultToolkit().beep();??????????????????employeeName.requestFocusInWindow();??
- ????????????????employeeName.selectAll();??????????????????return;??
- ????????????}????
- ????????????int?index?=?list.getSelectedIndex();?//获取选择项??????????????if?(index?==?-1)?{?//如果没有选择,就插入到第一个??
- ????????????????index?=?0;??????????????}?else?{???????????//如果有选择,那么插入到选择项的后面??
- ????????????????index++;??????????????}??
- ??????????????listModel.insertElementAt(employeeName.getText(),?index);??
- ???????????????//重新设置文本??
- ????????????employeeName.requestFocusInWindow();??????????????employeeName.setText("");??
- ??????????????//选择新的元素,并显示出来??
- ????????????list.setSelectedIndex(index);??????????????list.ensureIndexIsVisible(index);??
- ????????}??/**?
- ?*方法说明:检测是否在LIST中有重名元素??*输入参数:String?name?检测的名字?
- ?*返回类型:boolean?布尔值,如果存在返回true??*/??
- ??????????protected?boolean?alreadyInList(String?name)?{??
- ????????????return?listModel.contains(name);??????????}??
- ??/**?
- ?*方法说明:实现DocumentListener接口,必需实现的方法:??*/??
- ????????public?void?insertUpdate(DocumentEvent?e)?{??????????????enableButton();??
- ????????}????
- /**??*方法说明:实现DocumentListener接口,必需实现的方法?
- ?*/??????????public?void?removeUpdate(DocumentEvent?e)?{??
- ????????????handleEmptyTextField(e);??????????}??
- ??/**?
- ?*方法说明:实现DocumentListener接口,必需实现的方法??*/??
- ????????public?void?changedUpdate(DocumentEvent?e)?{??????????????if?(!handleEmptyTextField(e))?{??
- ????????????????enableButton();??????????????}??
- ????????}??/**?
- ?*方法说明:按钮使能??*/??
- ????????private?void?enableButton()?{??????????????if?(!alreadyEnabled)?{??
- ????????????????button.setEnabled(true);??????????????}??
- ????????}??/**?
- ?*方法说明:实现DocumentListener接口,必需实现的方法,修改按钮的状态??*/??
- ????????private?boolean?handleEmptyTextField(DocumentEvent?e)?{??????????????if?(e.getDocument().getLength()?<=?0)?{??
- ????????????????button.setEnabled(false);??????????????????alreadyEnabled?=?false;??
- ????????????????return?true;??????????????}??
- ????????????return?false;??????????}??
- ????}??/**?
- ?*方法说明:实现ListSelectionListener接口,必需实现的方法:??*/??
- ????public?void?valueChanged(ListSelectionEvent?e)?{??????????if?(e.getValueIsAdjusting()?==?false)?{??
- ??????????????if?(list.getSelectedIndex()?==?-1)?{??
- ????????????????fireButton.setEnabled(false);????
- ????????????}?else?{??????????????????fireButton.setEnabled(true);??
- ????????????}??????????}??
- ????}??/**?
- ?*方法说明:主方法??*/??
- ????public?static?void?main(String[]?args)?{????
- ????????JFrame.setDefaultLookAndFeelDecorated(true);????
- ????????//创建一个窗体??????????JFrame?frame?=?new?JFrame("ListDemo");??
- ????????frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);????
- ????????//创建一个面版??????????JComponent?newContentPane?=?new?ListDemo();??
- ????????newContentPane.setOpaque(true);??????????frame.setContentPane(newContentPane);??
- ??????????//显示窗体??
- ????????frame.pack();??????????frame.setVisible(true);??
- ????}??}??
?
view plain
- package?test15;????
- import?javax.swing.JTabbedPane;??import?javax.swing.ImageIcon;??
- import?javax.swing.JLabel;??import?javax.swing.JPanel;??
- import?javax.swing.JFrame;??/**?
- ?*?Title:?选项卡演示??*?Description:?这里是一个选项卡演示,点击不同的卡片,显示的内容不同?
- ?*?Filename:?TabbedPaneDemo.java??*/??
- import?java.awt.*;????
- public?class?TabbedPaneDemo?extends?JPanel?{??????/**?
- ?????*???????*/??
- ????private?static?final?long?serialVersionUID?=?1L;????
- ????public?TabbedPaneDemo()?{??????????super(new?GridLayout(1,?1));??
- ??????????ImageIcon?icon?=?createImageIcon("images/middle.gif");??
- ????????JTabbedPane?tabbedPane?=?new?JTabbedPane();????
- ????????Component?panel1?=?makeTextPanel("#第一个卡片#");??????????tabbedPane.addTab("One",?icon,?panel1,??
- ??????????????????????????"第一个卡片提示信息!");??????????tabbedPane.setSelectedIndex(0);??
- ??????????Component?panel2?=?makeTextPanel("##第二个卡片##");??
- ????????tabbedPane.addTab("Two",?icon,?panel2,????????????????????????????"第二个卡片提示信息!");??
- ??????????Component?panel3?=?makeTextPanel("###第三个卡片###");??
- ????????tabbedPane.addTab("Three",?icon,?panel3,????????????????????????????"第三个卡片提示信息!");??
- ??????????Component?panel4?=?makeTextPanel("####第四个卡片####");??
- ????????tabbedPane.addTab("Four",?icon,?panel4,????????????????????????????"第四个卡片提示信息!");??
- ??????????//将选项卡添加到panl中??
- ????????add(tabbedPane);??????}??
- /**??*方法说明:添加信息到选项卡中?
- ?*输入参数:String?text?显示的信息内容??*返回类型:Component?成员对象?
- ?*/??????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;??
- ????}??/**?
- ?*方法说明:获得图片??*输入参数:String?path?图片的路径?
- ?*返回类型:ImageIcon?图片对象??*/??
- ????protected?static?ImageIcon?createImageIcon(String?path)?{??????????java.net.URL?imgURL?=?TabbedPaneDemo.class.getResource(path);??
- ????????if?(imgURL?!=?null)?{??????????????return?new?ImageIcon(imgURL);??
- ????????}?else?{??????????????System.err.println("Couldn't?find?file:?"?+?path);??
- ????????????return?null;??????????}??
- ????}????
- ????public?static?void?main(String[]?args)?{??????????//使用Swing窗体描述??
- ????????JFrame.setDefaultLookAndFeelDecorated(true);????
- ????????//创建窗体??????????JFrame?frame?=?new?JFrame("TabbedPaneDemo");??
- ????????frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);??????????frame.getContentPane().add(new?TabbedPaneDemo(),??
- ?????????????????????????????????BorderLayout.CENTER);????
- ????????//显示窗体??????????frame.setSize(400,?200);??
- ????????frame.setVisible(true);??????}??
- }??
?
view plain
- package?test16;????
- import?javax.swing.JOptionPane;??import?javax.swing.JDialog;??
- import?javax.swing.JTextField;??import?java.beans.*;?//property?change?stuff??
- import?java.awt.*;??import?java.awt.event.*;??
- /**??*?Title:?用户自定义对话框?
- ?*?Description:?自己定义对话框的风格。这使得对话框的样式更加多样化??*?Filename:?CustomDialog.java?
- ?*/??class?CustomDialog?extends?JDialog??
- ???????????????????implements?ActionListener,????????????????????????????????PropertyChangeListener?{??
- ??????private?static?final?long?serialVersionUID?=?1L;??
- ????private?String?typedText?=?null;??????private?JTextField?textField;??
- ????private?DialogDemo?dd;????
- ????private?String?magicWord;??????private?JOptionPane?optionPane;??
- ??????private?String?btnString1?=?"确定";??
- ????private?String?btnString2?=?"取消";??/**?
- ?*方法说明:返回文本输入字符??*/??
- ????public?String?getValidatedText()?{??????????return?typedText;??
- ????}??/**?
- ?*方法说明:创建一个结果对话框??*/??
- ????public?CustomDialog(Frame?aFrame,?String?aWord,?DialogDemo?parent)?{??????????super(aFrame,?true);??
- ????????dd?=?parent;????????????
- ????????magicWord?=?aWord.toUpperCase();??????????setTitle("测试");??
- ??????????textField?=?new?JTextField(10);??
- ??????????//定义显示信息??
- ????????String?msgString1?=?"李先生:?jeck是你的英文名字吗?";??????????String?msgString2?=?"(这个答案是:?""?+?magicWord??
- ??????????????????????????????+?""。)";??????????Object[]?array?=?{msgString1,?msgString2,?textField};??
- ????
- ????????Object[]?options?=?{btnString1,?btnString2};????
- ????????//创建对话框??????????optionPane?=?new?JOptionPane(array,??
- ????????????????????????????????????JOptionPane.QUESTION_MESSAGE,??????????????????????????????????????JOptionPane.YES_NO_OPTION,??
- ????????????????????????????????????null,??????????????????????????????????????options,??
- ????????????????????????????????????options[0]);????
- ????????//显示对话框??????????setContentPane(optionPane);??
- ??????????//设置当关闭窗体动作模式??
- ????????setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);??????????addWindowListener(new?WindowAdapter()?{??
- ????????????????public?void?windowClosing(WindowEvent?we)?{????????????????????
- ????????????????????optionPane.setValue(new?Integer(??????????????????????????????????????????JOptionPane.CLOSED_OPTION));??
- ????????????}??????????});??
- ??????????//使的文本输入域得到焦点??
- ????????addComponentListener(new?ComponentAdapter()?{??????????????public?void?componentShown(ComponentEvent?ce)?{??
- ????????????????textField.requestFocusInWindow();??????????????}??
- ????????});????
- ????????//给文本域添加监听事件??????????textField.addActionListener(this);??
- ??????????//监听输入改变??
- ????????optionPane.addPropertyChangeListener(this);??????}??
- ??????/**?文本域监听处理?*/??
- ????public?void?actionPerformed(ActionEvent?e)?{??????????optionPane.setValue(btnString1);??
- ????}????
- ????/**?监听输入的改变?*/??????public?void?propertyChange(PropertyChangeEvent?e)?{??
- ????????String?prop?=?e.getPropertyName();????
- ????????if?(isVisible()???????????&&?(e.getSource()?==?optionPane)??
- ?????????&&?(JOptionPane.VALUE_PROPERTY.equals(prop)?||???????????????JOptionPane.INPUT_VALUE_PROPERTY.equals(prop)))?{??
- ????????????Object?value?=?optionPane.getValue();????
- ????????????if?(value?==?JOptionPane.UNINITIALIZED_VALUE)?{???????????????????return;??
- ????????????}????
- ????????????optionPane.setValue(??????????????????????JOptionPane.UNINITIALIZED_VALUE);??
- ??????????????if?(btnString1.equals(value))?{??
- ????????????????????typedText?=?textField.getText();??????????????????String?ucText?=?typedText.toUpperCase();??
- ????????????????if?(magicWord.equals(ucText))?{??????????????????????//如果输入有效,则清楚文本域并隐藏对话框??
- ????????????????????clearAndHide();??????????????????}?else?{??
- ????????????????????//文本输入无效??????????????????????textField.selectAll();??
- ????????????????????JOptionPane.showMessageDialog(??????????????????????????????????????CustomDialog.this,??
- ????????????????????????????????????"对不起,?""?+?typedText?+?""?"??????????????????????????????????????+?"是无效的输入。\n"??
- ????????????????????????????????????+?"请重新输入"??????????????????????????????????????+?magicWord?+?".",??
- ????????????????????????????????????"再试一次",??????????????????????????????????????JOptionPane.ERROR_MESSAGE);??
- ????????????????????typedText?=?null;??????????????????????textField.requestFocusInWindow();??
- ????????????????}??????????????}?else?{?//用户关闭了对话框或点击了“cancel”??
- ????????????????dd.setLabel("好吧!?"???????????????????????????+?"我们不能影响你的决定输入"??
- ?????????????????????????+?magicWord?+?"。");??????????????????typedText?=?null;??
- ????????????????clearAndHide();??????????????}??
- ????????}??????}??
- /**??*方法说明:清楚文本域并隐藏痘翱蝌?
- ??*/??
- ????public?void?clearAndHide()?{??????????textField.setText(null);??
- ????????setVisible(false);??????}??
- }??
?
view plain
- package?test16;????
- import?javax.swing.JOptionPane;??import?javax.swing.JDialog;??
- import?javax.swing.JButton;??import?javax.swing.JRadioButton;??
- import?javax.swing.ButtonGroup;??import?javax.swing.JLabel;??
- import?javax.swing.ImageIcon;??import?javax.swing.BoxLayout;??
- import?javax.swing.Box;??import?javax.swing.BorderFactory;??
- import?javax.swing.border.Border;??import?javax.swing.JTabbedPane;??
- import?javax.swing.JPanel;??import?javax.swing.JFrame;??
- import?java.beans.*;???import?java.awt.*;??
- import?java.awt.event.*;????
- /**??*Title:?对话框演示?
- ?*Description:?全面的演示各种类型的对话框的使用??*Filename:?DialogDemo.java?
- ?*/??public?class?DialogDemo?extends?JPanel?{??
- ??????private?static?final?long?serialVersionUID?=?1L;??
- ????JLabel?label;??????ImageIcon?icon?=?createImageIcon("images/middle.gif");??
- ????JFrame?frame;??????String?simpleDialogDesc?=?"简单的信息提示对话窗";??
- ????String?iconDesc?=?"带有图标的对话窗";??????String?moreDialogDesc?=?"复杂信息对话窗";??
- ????CustomDialog?customDialog;??/**?
- ?*方法说明:构造器,生成一个面板添加到JFrame中??*输入参数:?
- ?*返回类型:??*/??
- ????public?DialogDemo(JFrame?frame)?{??????????super(new?BorderLayout());??
- ????????this.frame?=?frame;??????????customDialog?=?new?CustomDialog(frame,?"tom",?this);??
- ????????customDialog.pack();????
- ????????//创建成员??????????JPanel?frequentPanel?=?createSimpleDialogBox();??
- ????????JPanel?featurePanel?=?createFeatureDialogBox();??????????JPanel?iconPanel?=?createIconDialogBox();??
- ????????label?=?new?JLabel("点击"显示"?按钮"?????????????????????????????+?"?显示一个选择的对话框",??
- ???????????????????????????JLabel.CENTER);????
- ????????//放置对象??????????Border?padding?=?BorderFactory.createEmptyBorder(20,20,5,20);??
- ????????frequentPanel.setBorder(padding);??????????featurePanel.setBorder(padding);??
- ????????iconPanel.setBorder(padding);??????????//创建选项卡??
- ????????JTabbedPane?tabbedPane?=?new?JTabbedPane();??????????tabbedPane.addTab("简单对话窗",?null,??
- ??????????????????????????frequentPanel,????????????????????????????simpleDialogDesc);???
- ????????tabbedPane.addTab("复杂对话窗",?null,????????????????????????????featurePanel,??
- ??????????????????????????moreDialogDesc);??????????tabbedPane.addTab("图标对话窗",?null,??
- ??????????????????????????iconPanel,????????????????????????????iconDesc);??
- ??????????add(tabbedPane,?BorderLayout.CENTER);??
- ????????add(label,?BorderLayout.PAGE_END);??????????label.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));??
- ????}??/**?
- ?*方法说明:设置按钮上的文字??*输入参数:String?newText?添加的文字?
- ?*返回类型:??*/??
- ????void?setLabel(String?newText)?{??????????label.setText(newText);??
- ????}??/**?
- ?*方法说明:获取图片??*输入参数:String?path?图片完整路径和名字?
- ?*返回类型:ImageIcon?图片对象??*/??
- ????protected?static?ImageIcon?createImageIcon(String?path)?{??????????java.net.URL?imgURL?=?DialogDemo.class.getResource(path);??
- ????????if?(imgURL?!=?null)?{??????????????return?new?ImageIcon(imgURL);??
- ????????}?else?{??????????????System.err.println("Couldn't?find?file:?"?+?path);??
- ????????????return?null;??????????}??
- ????}??/**?
- ?*方法说明:创建一个JPanel,给第一个选项卡??*输入参数:?
- ?*返回类型:??*/??
- ????private?JPanel?createSimpleDialogBox()?{??????????final?int?numButtons?=?4;??
- ????????JRadioButton[]?radioButtons?=?new?JRadioButton[numButtons];??????????final?ButtonGroup?group?=?new?ButtonGroup();??
- ??????????JButton?showItButton?=?null;??
- ??????????final?String?defaultMessageCommand?=?"default";??
- ????????final?String?yesNoCommand?=?"yesno";??????????final?String?yeahNahCommand?=?"yeahnah";??
- ????????final?String?yncCommand?=?"ync";??????????//添加单选到数字??
- ????????radioButtons[0]?=?new?JRadioButton("只有“OK”按钮");??????????radioButtons[0].setActionCommand(defaultMessageCommand);??
- ??????????radioButtons[1]?=?new?JRadioButton("有“Yes/No”二个按钮");??
- ????????radioButtons[1].setActionCommand(yesNoCommand);????
- ????????radioButtons[2]?=?new?JRadioButton("有“Yes/No”两个按钮?"????????????????????????+?"(程序添加文字)");??
- ????????radioButtons[2].setActionCommand(yeahNahCommand);????
- ????????radioButtons[3]?=?new?JRadioButton("有“Yes/No/Cancel”三个按钮?"?????????????????????????????+?"(程序添加文字)");??
- ????????radioButtons[3].setActionCommand(yncCommand);??????????//将四个单选组成一个群??
- ????????for?(int?i?=?0;?i?<?numButtons;?i++)?{??????????????group.add(radioButtons[i]);??
- ????????}??????????//设置第一个为默认选择??
- ????????radioButtons[0].setSelected(true);??????????//定义“显示”按钮??
- ????????showItButton?=?new?JButton("显示");??????????//给“显示”按钮添加监听??
- ????????showItButton.addActionListener(new?ActionListener()?{??????????????public?void?actionPerformed(ActionEvent?e)?{??
- ????????????????String?command?=?group.getSelection().getActionCommand();????
- ????????????????//ok对话窗??????????????????if?(command?==?defaultMessageCommand)?{??
- ????????????????????JOptionPane.showMessageDialog(frame,??????????????????????????????????"鸡蛋不可能是绿色的!");??
- ??????????????????//yes/no?对话窗??
- ????????????????}?else?if?(command?==?yesNoCommand)?{??????????????????????int?n?=?JOptionPane.showConfirmDialog(??
- ????????????????????????????frame,?"你喜欢吃酸菜鱼吗?",??????????????????????????????"一个很无聊的问题!!",??
- ????????????????????????????JOptionPane.YES_NO_OPTION);??????????????????????if?(n?==?JOptionPane.YES_OPTION)?{//选择yes??
- ????????????????????????setLabel("哇!我也是!");??????????????????????}?else?if?(n?==?JOptionPane.NO_OPTION)?{//选择no??
- ????????????????????????setLabel("唉!我喜欢吃!");??????????????????????}?else?{??
- ????????????????????????setLabel("快告诉我吧!");??????????????????????}??
- ??????????????????//yes/no?(自己输入选项)??
- ????????????????}?else?if?(command?==?yeahNahCommand)?{??????????????????????Object[]?options?=?{"是的",?"不喜欢"};??
- ????????????????????int?n?=?JOptionPane.showOptionDialog(frame,??????????????????????????????????????"你喜欢酸菜鱼吗?",??
- ????????????????????????????????????"又一个无聊的问题!",??????????????????????????????????????JOptionPane.YES_NO_OPTION,??
- ????????????????????????????????????JOptionPane.QUESTION_MESSAGE,??????????????????????????????????????null,??
- ????????????????????????????????????options,??????????????????????????????????????options[0]);??
- ????????????????????if?(n?==?JOptionPane.YES_OPTION)?{??????????????????????????setLabel("你哄人的吧,我也喜欢。");??
- ????????????????????}?else?if?(n?==?JOptionPane.NO_OPTION)?{??????????????????????????setLabel("其实我也不喜欢!");??
- ????????????????????}?else?{??????????????????????????setLabel("这都不肯告诉我,小气鬼!");??
- ????????????????????}????
- ????????????????//yes/no/cancel?对话框??????????????????}?else?if?(command?==?yncCommand)?{??
- ????????????????????Object[]?options?=?{"是的,给我来一份。",??????????????????????????????????????????"不,谢谢!",??
- ????????????????????????????????????????"不,我要水煮鱼!"};??????????????????????//构造对话框??
- ????????????????????int?n?=?JOptionPane.showOptionDialog(frame,??????????????????????????????????????"先生!我们这里有鲜美的酸菜鱼,您需要吗?",??
- ????????????????????????????????????"服务生的问题。",??????????????????????????????????????JOptionPane.YES_NO_CANCEL_OPTION,??
- ????????????????????????????????????JOptionPane.QUESTION_MESSAGE,??????????????????????????????????????null,??
- ????????????????????????????????????options,??????????????????????????????????????options[2]);??
- ????????????????????if?(n?==?JOptionPane.YES_OPTION)?{??????????????????????????setLabel("你要的酸菜鱼来了!");??
- ????????????????????}?else?if?(n?==?JOptionPane.NO_OPTION)?{??????????????????????????setLabel("好的,你需要其它的。");??
- ????????????????????}?else?if?(n?==?JOptionPane.CANCEL_OPTION)?{??????????????????????????setLabel("好的,我们给你做水煮鱼!");??
- ????????????????????}?else?{??????????????????????????setLabel("对不起!你还没有点菜呢!");??
- ????????????????????}??????????????????}??
- ????????????????return;??????????????}??
- ????????});????
- ????????return?createPane(simpleDialogDesc?+?":",????????????????????????????radioButtons,??
- ??????????????????????????showItButton);??????}??
- /**??*方法说明:提供给createSimpleDialogBox和createFeatureDialogBox方法?
- ?*方法说明:创建带提示信息、一列单选框和“显示”按钮??*输入参数:String?description?提示帮助信息?
- ?*输入参数:JRadioButton[]?radioButtons?单选框组??*输入参数:JButton?showButton?“显示”按钮?
- ?*返回类型:JPanel?添加好的面板??*/??
- ????private?JPanel?createPane(String?description,????????????????????????????????JRadioButton[]?radioButtons,??
- ??????????????????????????????JButton?showButton)?{????
- ????????int?numChoices?=?radioButtons.length;??????????JPanel?box?=?new?JPanel();??
- ????????JLabel?label?=?new?JLabel(description);????
- ????????box.setLayout(new?BoxLayout(box,?BoxLayout.PAGE_AXIS));??????????box.add(label);??
- ????????//添加radio??????????for?(int?i?=?0;?i?<?numChoices;?i++)?{??
- ????????????box.add(radioButtons[i]);??????????}??
- ??????????JPanel?pane?=?new?JPanel(new?BorderLayout());??
- ????????pane.add(box,?BorderLayout.PAGE_START);??????????pane.add(showButton,?BorderLayout.PAGE_END);??
- ????????return?pane;??????}??
- /**??*方法说明:提供给createSimpleDialogBox和createFeatureDialogBox方法?
- ?*方法说明:创建带提示信息、二列单选框和“显示”按钮??*输入参数:String?description?提示帮助信息?
- ?*输入参数:JRadioButton[]?radioButtons?单选框组??*输入参数:JButton?showButton?“显示”按钮?
- ?*返回类型:JPanel?添加好的面板??*/??
- ?????private?JPanel?create2ColPane(String?description,????????????????????????????????????JRadioButton[]?radioButtons,??
- ??????????????????????????????????JButton?showButton)?{??????????JLabel?label?=?new?JLabel(description);??
- ????????int?numPerColumn?=?radioButtons.length/2;????
- ????????JPanel?grid?=?new?JPanel(new?GridLayout(0,?2));??????????for?(int?i?=?0;?i?<?numPerColumn;?i++)?{??
- ????????????grid.add(radioButtons[i]);??????????????grid.add(radioButtons[i?+?numPerColumn]);??
- ????????}????
- ????????JPanel?box?=?new?JPanel();??????????box.setLayout(new?BoxLayout(box,?BoxLayout.PAGE_AXIS));??
- ????????box.add(label);??????????grid.setAlignmentX(0.0f);??
- ????????box.add(grid);????
- ????????JPanel?pane?=?new?JPanel(new?BorderLayout());??????????pane.add(box,?BorderLayout.PAGE_START);??
- ????????pane.add(showButton,?BorderLayout.PAGE_END);????
- ????????return?pane;??????}??
- /**??*方法说明:创建第三个选项卡的面板?
- ?*方法说明:这里都是实现showMessageDialog类,但是也可以指定图标??*输入参数:?
- ?*返回类型:JPanel?构造好的面板??*/??
- ??????private?JPanel?createIconDialogBox()?{??
- ????????JButton?showItButton?=?null;????
- ????????final?int?numButtons?=?6;??????????JRadioButton[]?radioButtons?=?new?JRadioButton[numButtons];??
- ????????final?ButtonGroup?group?=?new?ButtonGroup();????
- ????????final?String?plainCommand?=?"plain";??????????final?String?infoCommand?=?"info";??
- ????????final?String?questionCommand?=?"question";??????????final?String?errorCommand?=?"error";??
- ????????final?String?warningCommand?=?"warning";??????????final?String?customCommand?=?"custom";??
- ??????????radioButtons[0]?=?new?JRadioButton("普通(没有图标)");??
- ????????radioButtons[0].setActionCommand(plainCommand);????
- ????????radioButtons[1]?=?new?JRadioButton("信息图标");??????????radioButtons[1].setActionCommand(infoCommand);??
- ??????????radioButtons[2]?=?new?JRadioButton("问题图标");??
- ????????radioButtons[2].setActionCommand(questionCommand);????
- ????????radioButtons[3]?=?new?JRadioButton("错误图标");??????????radioButtons[3].setActionCommand(errorCommand);??
- ??????????radioButtons[4]?=?new?JRadioButton("警告图标");??
- ????????radioButtons[4].setActionCommand(warningCommand);????
- ????????radioButtons[5]?=?new?JRadioButton("自定义图标");??????????radioButtons[5].setActionCommand(customCommand);??
- ??????????for?(int?i?=?0;?i?<?numButtons;?i++)?{??
- ????????????group.add(radioButtons[i]);??????????}??
- ????????radioButtons[0].setSelected(true);????
- ????????showItButton?=?new?JButton("显示");??????????showItButton.addActionListener(new?ActionListener()?{??
- ????????????public?void?actionPerformed(ActionEvent?e)?{??????????????????String?command?=?group.getSelection().getActionCommand();??
- ??????????????????//没有图标??
- ????????????????if?(command?==?plainCommand)?{??????????????????????JOptionPane.showMessageDialog(frame,??
- ????????????????????????????????????"水煮鱼里不要放酸菜!",??????????????????????????????????????"无图标",??
- ????????????????????????????????????JOptionPane.PLAIN_MESSAGE);??????????????????//信息图标??
- ????????????????}?else?if?(command?==?infoCommand)?{??????????????????????JOptionPane.showMessageDialog(frame,??
- ????????????????????????????????????"水煮鱼里不要放酸菜!",??????????????????????????????????????"信息图标",??
- ????????????????????????????????????JOptionPane.INFORMATION_MESSAGE);????
- ????????????????//问题图标??????????????????}?else?if?(command?==?questionCommand)?{??
- ????????????????????JOptionPane.showMessageDialog(frame,??????????????????????????????????????"请你吃饭前洗手,好吗?",??
- ????????????????????????????????????"问题",??????????????????????????????????????JOptionPane.QUESTION_MESSAGE);??
- ????????????????//错误图标??????????????????}?else?if?(command?==?errorCommand)?{??
- ????????????????????JOptionPane.showMessageDialog(frame,??????????????????????????????????????"对不起,你的信用卡没有资金了!",??
- ????????????????????????????????????"错误信息",??????????????????????????????????????JOptionPane.ERROR_MESSAGE);??
- ????????????????//警告图标??????????????????}?else?if?(command?==?warningCommand)?{??
- ????????????????????JOptionPane.showMessageDialog(frame,??????????????????????????????????????"警告!你严重透支信用卡,请尽快补齐金额!",??
- ????????????????????????????????????"警告信息",??????????????????????????????????????JOptionPane.WARNING_MESSAGE);??
- ????????????????//自定义图标??????????????????}?else?if?(command?==?customCommand)?{??
- ????????????????????JOptionPane.showMessageDialog(frame,??????????????????????????????????????"哈哈。我想用什么图标都可以!",??
- ????????????????????????????????????"自定义对话窗",??????????????????????????????????????JOptionPane.INFORMATION_MESSAGE,??
- ????????????????????????????????????icon);??????????????????}??
- ????????????}??????????});??
- ??????????return?create2ColPane(iconDesc?+?":",??
- ??????????????????????????????radioButtons,????????????????????????????????showItButton);??
- ????}??/**?
- ?*方法说明:创建一个JPanel,放在第二个选项卡上??*输入参数:?
- ?*返回类型:??*/??
- ????private?JPanel?createFeatureDialogBox()?{??????????final?int?numButtons?=?5;??
- ????????JRadioButton[]?radioButtons?=?new?JRadioButton[numButtons];??????????final?ButtonGroup?group?=?new?ButtonGroup();??
- ??????????JButton?showItButton?=?null;??
- ????????//定义操作命令??????????final?String?pickOneCommand?=?"pickone";??
- ????????final?String?textEnteredCommand?=?"textfield";??????????final?String?nonAutoCommand?=?"nonautooption";??
- ????????final?String?customOptionCommand?=?"customoption";??????????final?String?nonModalCommand?=?"nonmodal";??
- ????????//定义radio数组??????????radioButtons[0]?=?new?JRadioButton("选择一个");??
- ????????radioButtons[0].setActionCommand(pickOneCommand);????
- ????????radioButtons[1]?=?new?JRadioButton("输入信息");??????????radioButtons[1].setActionCommand(textEnteredCommand);??
- ??????????radioButtons[2]?=?new?JRadioButton("关闭按钮无效");??
- ????????radioButtons[2].setActionCommand(nonAutoCommand);????
- ????????radioButtons[3]?=?new?JRadioButton("输入校验"?????????????????????????????????????????????+?"(用户输入信息)");??
- ????????radioButtons[3].setActionCommand(customOptionCommand);????
- ????????radioButtons[4]?=?new?JRadioButton("没有模式");??????????radioButtons[4].setActionCommand(nonModalCommand);??
- ????????//合成一个组群??????????for?(int?i?=?0;?i?<?numButtons;?i++)?{??
- ????????????group.add(radioButtons[i]);??????????}??
- ????????//设置第一个为默认选择??????????radioButtons[0].setSelected(true);??
- ??????????showItButton?=?new?JButton("显示");??
- ????????showItButton.addActionListener(new?ActionListener()?{??????????????@SuppressWarnings("static-access")??
- ????????????public?void?actionPerformed(ActionEvent?e)?{??????????????????String?command?=?group.getSelection().getActionCommand();??
- ??????????????????//选择一个??
- ????????????????if?(command?==?pickOneCommand)?{??????????????????????Object[]?possibilities?=?{"辣椒",?"西红柿",?"洋葱"};??
- ????????????????????//设置对话框??????????????????????String?s?=?(String)JOptionPane.showInputDialog(??
- ????????????????????????????????????????frame,????//所属窗体??????????????????????????????????????????"请选择项目:\n"??
- ????????????????????????????????????????+?""鸡蛋炒"",??//输出信息??????????????????????????????????????????"客户选择",??
- ????????????????????????????????????????JOptionPane.PLAIN_MESSAGE,??//对话框模式??????????????????????????????????????????icon,???????????//显示图标??
- ????????????????????????????????????????possibilities,???//选项内容??????????????????????????????????????????"辣椒");????//默认选项??
- ??????????????????????//如果有选择??
- ????????????????????if?((s?!=?null)?&&?(s.length()?>?0))?{??????????????????????????setLabel("鸡蛋炒"?+?s?+?"!");??
- ????????????????????????return;??????????????????????}??
- ??????????????????????//如果客户没有选择??
- ????????????????????setLabel("快点!");????
- ????????????????//文本输入??????????????????}?else?if?(command?==?textEnteredCommand)?{??
- ????????????????????String?s?=?(String)JOptionPane.showInputDialog(??????????????????????????????????????????frame,??
- ????????????????????????????????????????"选择一个配料\n"??????????????????????????????????????????+?""鸡蛋炒"",??
- ????????????????????????????????????????"客户输入",??????????????????????????????????????????JOptionPane.PLAIN_MESSAGE,??
- ????????????????????????????????????????icon,??????????????????????????????????????????null,??
- ????????????????????????????????????????"辣椒");????
- ????????????????????//如果用户有输入??????????????????????if?((s?!=?null)?&&?(s.length()?>?0))?{??
- ????????????????????????setLabel("你要的是鸡蛋炒"?+?s?+?"!");??????????????????????????return;??
- ????????????????????}????
- ????????????????????//如果返回的是空或者是null。??????????????????????setLabel("快些选择!");??
- ??????????????????//关闭按钮无效??
- ????????????????}?else?if?(command?==?nonAutoCommand)?{??????????????????????//构造一个对话框面板??
- ????????????????????final?JOptionPane?optionPane?=?new?JOptionPane(??????????????????????????????????????"关闭这个对话框\n"??
- ????????????????????????????????????+?"请点击下面的按钮\n"??????????????????????????????????????+?"明白吗?",??
- ????????????????????????????????????JOptionPane.QUESTION_MESSAGE,??????????????????????????????????????JOptionPane.YES_NO_OPTION);??
- ??????????????????????JDialog.setDefaultLookAndFeelDecorated(false);??
- ????????????????????//构造一个对话框??????????????????????final?JDialog?dialog?=?new?JDialog(frame,??
- ?????????????????????????????????????????????????"点击一个按钮",???????????????????????????????????????????????????true);??
- ????????????????????//将对话框面板添加到对话框中??????????????????????dialog.setContentPane(optionPane);??
- ????????????????????//设置对话框关闭时的操作模式??????????????????????dialog.setDefaultCloseOperation(??
- ????????????????????????JDialog.DO_NOTHING_ON_CLOSE);??????????????????????dialog.addWindowListener(new?WindowAdapter()?{??
- ????????????????????????public?void?windowClosing(WindowEvent?we)?{?//当点击关闭按钮??????????????????????????????setLabel("阻碍用户视图关闭窗体!");??
- ????????????????????????}??????????????????????});??
- ??????????????????????????????????????????JDialog.setDefaultLookAndFeelDecorated(true);??
- ??????????????????????????????????????????optionPane.addPropertyChangeListener(??
- ????????????????????????new?PropertyChangeListener()?{??????????????????????????????public?void?propertyChange(PropertyChangeEvent?e)?{??
- ????????????????????????????????String?prop?=?e.getPropertyName();????
- ????????????????????????????????if?(dialog.isVisible()???????????????????????????????????&&?(e.getSource()?==?optionPane)??
- ?????????????????????????????????&&?(JOptionPane.VALUE_PROPERTY.equals(prop)))?{??????????????????????????????????????//如果你要阻止关闭按钮,可以在这里进行处理。??
- ??????????????????????????????????????????????????????????????????????????dialog.setVisible(false);??
- ????????????????????????????????}??????????????????????????????}??
- ????????????????????????});??????????????????????dialog.pack();??
- ????????????????????dialog.setLocationRelativeTo(frame);??????????????????????dialog.setVisible(true);??
- ??????????????????????????????????????????int?value?=?((Integer)optionPane.getValue()).intValue();??
- ????????????????????if?(value?==?JOptionPane.YES_OPTION)?{??????????????????????????setLabel("好的");??
- ????????????????????}?else?if?(value?==?JOptionPane.NO_OPTION)?{??????????????????????????setLabel("试图点击关闭按钮来关闭一个不能关闭的对话框!"??
- ?????????????????????????????????+?"你不能!");??????????????????????}?else?{??
- ????????????????????????setLabel("窗体可以使用ESC键关闭。");??????????????????????}??
- ???????????????????//自己定义版面??
- ????????????????}?else?if?(command?==?customOptionCommand)?{??????????????????????customDialog.setLocationRelativeTo(frame);??
- ????????????????????customDialog.setVisible(true);????
- ????????????????????String?s?=?customDialog.getValidatedText();??????????????????????if?(s?!=?null)?{??
- ????????????????????????//The?text?is?valid.??????????????????????????setLabel("欢迎你!"??
- ?????????????????????????????????+?"你已经进入了""???????????????????????????????????+?s??
- ?????????????????????????????????+?""。");??????????????????????}??
- ??????????????????//没有模式??
- ????????????????}?else?if?(command?==?nonModalCommand)?{??????????????????????//创建一个对话框??
- ????????????????????final?JDialog?dialog?=?new?JDialog(frame,?????????????????????????????????????????????????????????"一个没有模式的对话框");??
- ????????????????????//使用html语言来显示信息??????????????????????JLabel?label?=?new?JLabel("<html><p?align=center>"??
- ????????????????????????+?"这是一个没有模式的对话框"??????????????????????????+?"你可以使用更多的格式"??
- ????????????????????????+?"甚至可以使用主窗体!");??????????????????????label.setHorizontalAlignment(JLabel.CENTER);??
- ????????????????????Font?font?=?label.getFont();????????????????????????
- ????????????????????label.setFont(label.getFont().deriveFont(font.PLAIN,???????????????????????????????????????????????????????????????14.0f));??
- ??????????????????????JButton?closeButton?=?new?JButton("关闭");??
- ????????????????????closeButton.addActionListener(new?ActionListener()?{??????????????????????????public?void?actionPerformed(ActionEvent?e)?{??
- ????????????????????????????dialog.setVisible(false);??????????????????????????????dialog.dispose();??
- ????????????????????????}??????????????????????});??
- ????????????????????JPanel?closePanel?=?new?JPanel();??????????????????????closePanel.setLayout(new?BoxLayout(closePanel,??
- ???????????????????????????????????????????????????????BoxLayout.LINE_AXIS));??????????????????????closePanel.add(Box.createHorizontalGlue());??
- ????????????????????closePanel.add(closeButton);??????????????????????closePanel.setBorder(BorderFactory.??
- ????????????????????????createEmptyBorder(0,0,5,5));????
- ????????????????????JPanel?contentPane?=?new?JPanel(new?BorderLayout());??????????????????????contentPane.add(label,?BorderLayout.CENTER);??
- ????????????????????contentPane.add(closePanel,?BorderLayout.PAGE_END);??????????????????????contentPane.setOpaque(true);??
- ????????????????????dialog.setContentPane(contentPane);????
- ????????????????????//显示窗体??????????????????????dialog.setSize(new?Dimension(300,?150));??
- ????????????????????dialog.setLocationRelativeTo(frame);??????????????????????dialog.setVisible(true);??
- ????????????????}??????????????}??
- ????????});????
- ????????return?createPane(moreDialogDesc?+?":",????????????????????????????radioButtons,??
- ??????????????????????????showItButton);??????}??
- ??????public?static?void?main(String[]?args)?{??
- ??????????JFrame.setDefaultLookAndFeelDecorated(true);??
- ????????JDialog.setDefaultLookAndFeelDecorated(true);????
- ????????//创建和设置一个窗体??????????JFrame?frame?=?new?JFrame("DialogDemo");??
- ????????frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);????
- ????????//设置一个面板??????????Container?contentPane?=?frame.getContentPane();??
- ????????contentPane.setLayout(new?GridLayout(1,1));??????????contentPane.add(new?DialogDemo(frame));??
- ??????????//显示窗体??
- ????????frame.pack();??????????frame.setVisible(true);??
- ????}??}??
?
view plain
- package?test17;????
- import?java.io.*;??import?java.awt.*;??
- import?java.awt.event.*;??import?javax.swing.*;??
- /**??*?Title:?文件对话框演示?
- ?*?Description:?演示打开文件对话框和保存文件对话框,使用了文件过滤。??*?Filename:?FileChooserDemo.java?
- ?*/????
- public?class?FileChooserDemo?extends?JPanel???????????????????????????????implements?ActionListener?{??
- ??????private?static?final?long?serialVersionUID?=?1L;??
- ????static?private?final?String?newline?=?"\n";??????JButton?openButton,?saveButton;??
- ????JTextArea?log;??????JFileChooser?fc;??
- ??????public?FileChooserDemo()?{??
- ????????super(new?BorderLayout());????
- ????????log?=?new?JTextArea(15,40);??????????log.setMargin(new?Insets(10,10,10,10));??
- ????????log.setEditable(false);??????????JScrollPane?logScrollPane?=?new?JScrollPane(log);??
- ??????????//创建一个文件过滤,使用当前目录??
- ????????fc?=?new?JFileChooser(".");??????????//过滤条件在MyFilter类中定义??
- ????????fc.addChoosableFileFilter(new?MyFilter());????
- ????????openButton?=?new?JButton("打开文件",???????????????????????????????????createImageIcon("images/Open16.gif"));??
- ????????openButton.addActionListener(this);????
- ????????saveButton?=?new?JButton("保存文件",???????????????????????????????????createImageIcon("images/Save16.gif"));??
- ????????saveButton.addActionListener(this);????
- ????????//构建一个面板,添加“打开文件”和“保存文件”??????????JPanel?buttonPanel?=?new?JPanel();???
- ????????buttonPanel.add(openButton);??????????buttonPanel.add(saveButton);??
- ??????????add(buttonPanel,?BorderLayout.PAGE_START);??
- ????????add(logScrollPane,?BorderLayout.CENTER);??????}??
- /**??*方法说明:事件处理?
- ?*输入参数:??*返回类型:?
- ?*/??????public?void?actionPerformed(ActionEvent?e)?{??
- ??????????//当点击“打开文件”按钮??
- ????????if?(e.getSource()?==?openButton)?{??????????????int?returnVal?=?fc.showOpenDialog(FileChooserDemo.this);??
- ??????????????if?(returnVal?==?JFileChooser.APPROVE_OPTION)?{??
- ????????????????File?file?=?fc.getSelectedFile();??????????????????//在这里添加一些对文件的处理??
- ????????????????log.append("打开文件:?"?+?file.getName()?+?newline);??????????????}?else?{??
- ????????????????log.append("打开文件被用户取消!"?+?newline);??????????????}??
- ??????????//点击“保存文件”按钮??
- ????????}?else?if?(e.getSource()?==?saveButton)?{??????????????int?returnVal?=?fc.showSaveDialog(FileChooserDemo.this);??
- ????????????if?(returnVal?==?JFileChooser.APPROVE_OPTION)?{??????????????????File?file?=?fc.getSelectedFile();??
- ????????????????//在这里添加一些对文件的处理??????????????????log.append("保存文件:?"?+?file.getName()??+?newline);??
- ????????????}?else?{??????????????????log.append("保存文件被用户取消!"?+?newline);??
- ????????????}??????????}??
- ????}??/**?
- ?*方法说明:获取图像对象??*输入参数:String?path?图片路径?
- ?*返回类型:ImageIcon?图片对象??*/??
- ????protected?static?ImageIcon?createImageIcon(String?path)?{??????????java.net.URL?imgURL?=?FileChooserDemo.class.getResource(path);??
- ????????if?(imgURL?!=?null)?{??????????????return?new?ImageIcon(imgURL);??
- ????????}?else?{??????????????System.err.println("Couldn't?find?file:?"?+?path);??
- ????????????return?null;??????????}??
- ????}????
- ????public?static?void?main(String[]?args)?{??????????JFrame.setDefaultLookAndFeelDecorated(true);??
- ????????JDialog.setDefaultLookAndFeelDecorated(true);????
- ????????//创建窗体??????????JFrame?frame?=?new?JFrame("FileChooserDemo");??
- ????????frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);????
- ????????//创建一个面板??????????JComponent?newContentPane?=?new?FileChooserDemo();??
- ????????newContentPane.setOpaque(true);??????????frame.setContentPane(newContentPane);??
- ??????????//显示窗体??
- ????????frame.pack();??????????frame.setVisible(true);??
- ????}??}??
?
view plain
- package?test17;????
- import?java.io.File;??import?javax.swing.filechooser.*;??
- /**??*?Title:?文件过滤器演示?
- ?*?Description:?FileChooserDemo文件使用的文件过滤器??*?Filename:?MyFilter.java?
- ?*/????
- public?class?MyFilter?extends?FileFilter?{?????@SuppressWarnings("unused")??
- private?String?files;?????public?boolean?accept(File?f)?{??
- ????????if?(f.isDirectory())?{??????????????return?true;??
- ????????}????
- ????????String?extension?=?getExtension(f);??????????if?(extension?!=?null)?{??
- ??????????????????????????if?(extension.equals("java"))?{//定义过滤Java文件??
- ????????????????????return?true;??????????????}?else?{??
- ????????????????return?false;??????????????}??
- ??????????}??
- ??????????return?false;??
- ????}????
- ????//过滤器描述??????public?String?getDescription()?{??
- ????????return?"Java";??????}??
- /**??*方法说明:获取文件扩展名?
- ?*/??????public?static?String?getExtension(File?f)?{??
- ????????String?ext?=?null;??????????String?s?=?f.getName();??
- ????????int?i?=?s.lastIndexOf('.');????
- ????????if?(i?>?0?&&??i?<?s.length()?-?1)?{??????????????ext?=?s.substring(i+1).toLowerCase();??
- ????????}??????????return?ext;??
- ????}??}??
?
view plain
- package?test18;????
- import?javax.swing.*;??import?java.awt.*;??
- import?java.awt.event.*;??/**?
- ?*?Description:?这里演示使用html语言在swing面板上构造显示信息??*?Filename:?HtmlDemo.java?
- ?*/????
- public?class?HtmlDemo?extends?JPanel????????????????????????implements?ActionListener?{??
- ??????private?static?final?long?serialVersionUID?=?1L;??
- ????JLabel?theLabel;??????JTextArea?htmlTextArea;??
- /**??*方法说明:构造器,描述窗体中的成员?
- ?*输入参数:??*返回类型:?
- ?*/??????public?HtmlDemo()?{??
- ????????setLayout(new?BoxLayout(this,?BoxLayout.LINE_AXIS));????
- ????????String?initialText?=?"<html>\n"?+??????????????????"颜色和字体测试:\n"?+??
- ????????????????"<ul>\n"?+??????????????????"<li><font?color=red>red</font>\n"?+??
- ????????????????"<li><font?color=blue>blue</font>\n"?+??????????????????"<li><font?color=green>green</font>\n"?+??
- ????????????????"<li><font?size=-2>small</font>\n"?+??????????????????"<li><font?size=+2>large</font>\n"?+??
- ????????????????"<li><i>italic</i>\n"?+??????????????????"<li><b>bold</b>\n"?+??
- ????????????????"</ul>\n";??????????//定义一个文本框??
- ????????htmlTextArea?=?new?JTextArea(10,?20);??????????htmlTextArea.setText(initialText);??
- ????????JScrollPane?scrollPane?=?new?JScrollPane(htmlTextArea);??????????//定义按钮??
- ????????JButton?changeTheLabel?=?new?JButton("改变显示");??????????changeTheLabel.setMnemonic(KeyEvent.VK_C);??
- ????????changeTheLabel.setAlignmentX(Component.CENTER_ALIGNMENT);??????????changeTheLabel.addActionListener(this);??
- ????????//定义标签??????????theLabel?=?new?JLabel(initialText)?{??
- ???????????????????????private?static?final?long?serialVersionUID?=?1L;??
- ????????????public?Dimension?getPreferredSize()?{??????????????????return?new?Dimension(200,?200);??
- ????????????}??????????????public?Dimension?getMinimumSize()?{??
- ????????????????return?new?Dimension(200,?200);??????????????}??
- ????????????public?Dimension?getMaximumSize()?{??????????????????return?new?Dimension(200,?200);??
- ????????????}??????????};??
- ????????//设置标签的对齐方式??????????theLabel.setVerticalAlignment(SwingConstants.CENTER);??
- ????????theLabel.setHorizontalAlignment(SwingConstants.CENTER);??????????//构造一个带边框的左边的编辑面板??
- ????????JPanel?leftPanel?=?new?JPanel();??????????leftPanel.setLayout(new?BoxLayout(leftPanel,?BoxLayout.PAGE_AXIS));??
- ????????leftPanel.setBorder(BorderFactory.createCompoundBorder(??????????????????BorderFactory.createTitledBorder(??
- ????????????????????"编辑HTML,点击按钮显示结果。"),??????????????????BorderFactory.createEmptyBorder(10,10,10,10)));??
- ????????leftPanel.add(scrollPane);??????????leftPanel.add(Box.createRigidArea(new?Dimension(0,10)));??
- ????????leftPanel.add(changeTheLabel);???????????//构造一个带边框的右边显示的面板??
- ????????JPanel?rightPanel?=?new?JPanel();??????????rightPanel.setLayout(new?BoxLayout(rightPanel,?BoxLayout.PAGE_AXIS));??
- ????????rightPanel.setBorder(BorderFactory.createCompoundBorder(??????????????????????????BorderFactory.createTitledBorder("这里使用标签显示HTML结果"),??
- ????????????????????????BorderFactory.createEmptyBorder(10,10,10,10)));??????????rightPanel.add(theLabel);??
- ??????????????????setBorder(BorderFactory.createEmptyBorder(10,10,10,10));??
- ????????add(leftPanel);??????????add(Box.createRigidArea(new?Dimension(10,0)));??
- ????????add(rightPanel);??????}??
- /**??*方法说明:事件监听,当用户点击按钮触发?
- ?*输入参数:??*返回类型:?
- ?*/??????public?void?actionPerformed(ActionEvent?e)?{??
- ????????theLabel.setText(htmlTextArea.getText());??????}??
- /**??*方法说明:主方法?
- ?*输入参数:??*返回类型:?
- ?*/??????public?static?void?main(String[]?args)?{??
- ??????????JFrame.setDefaultLookAndFeelDecorated(true);??
- ??????????//创建窗体??
- ????????JFrame?frame?=?new?JFrame("HtmlDemo");??????????frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);??
- ??????????//创建面板??
- ????????JComponent?newContentPane?=?new?HtmlDemo();??????????newContentPane.setOpaque(true);??
- ????????frame.setContentPane(newContentPane);????
- ????????//显示窗体??????????frame.pack();??
- ????????frame.setVisible(true);??????}??
- }??
?
view plain
- package?test19;????
- import?java.awt.*;??import?java.awt.event.*;??
- import?javax.swing.JPopupMenu;??import?javax.swing.JMenu;??
- import?javax.swing.JMenuItem;??import?javax.swing.JCheckBoxMenuItem;??
- import?javax.swing.JRadioButtonMenuItem;??import?javax.swing.ButtonGroup;??
- import?javax.swing.JMenuBar;??import?javax.swing.KeyStroke;??
- import?javax.swing.ImageIcon;????
- import?javax.swing.JPanel;??import?javax.swing.JTextArea;??
- import?javax.swing.JScrollPane;??import?javax.swing.JFrame;??
- /**??*?Title:?菜单演示?
- ?*?Description:?演示菜单的建立和快捷键的使用。??*?Filename:?MenuDemo.java?
- ?*/????
- public?class?MenuDemo?implements?ActionListener,?ItemListener?{??????JTextArea?output;??
- ????JScrollPane?scrollPane;??????String?newline?=?"\n";??
- /**??*方法说明:组建菜单栏?
- ?*输入参数:??*返回类型:?
- ?*/??????public?JMenuBar?createMenuBar()?{??
- ????????JMenuBar?menuBar;??????????JMenu?menu,?submenu;??
- ????????JMenuItem?menuItem;??????????JRadioButtonMenuItem?rbMenuItem;??
- ????????JCheckBoxMenuItem?cbMenuItem;????
- ????????//定义菜单条??????????menuBar?=?new?JMenuBar();??
- ??????????//定义第一个菜单??
- ????????menu?=?new?JMenu("(A)菜单");??????????menu.setMnemonic(KeyEvent.VK_A);??
- ????????menuBar.add(menu);????
- ????????//下面开始定义菜单项????????????
- ????????//只有文字??????????menuItem?=?new?JMenuItem("(O)只有文本的菜单",??
- ?????????????????????????????????KeyEvent.VK_O);??????????//设置快捷键??
- ????????menuItem.setAccelerator(KeyStroke.getKeyStroke(??????????????????KeyEvent.VK_1,?ActionEvent.ALT_MASK));??
- ????????//添加监听??????????menuItem.addActionListener(this);??
- ????????menu.add(menuItem);??????????//有图标还有文字??
- ????????ImageIcon?icon?=?createImageIcon("images/middle.gif");??????????menuItem?=?new?JMenuItem("(B)有图标和文字的菜单",?icon);??
- ????????menuItem.setMnemonic(KeyEvent.VK_B);??????????menuItem.addActionListener(this);??
- ????????menu.add(menuItem);??????????//只有图标??
- ????????menuItem?=?new?JMenuItem(icon);??????????menuItem.setMnemonic(KeyEvent.VK_D);??
- ????????menuItem.addActionListener(this);??????????menu.add(menuItem);??
- ??????????//定义一组radio?button(单选按钮)菜单??
- ????????menu.addSeparator();??????????ButtonGroup?group?=?new?ButtonGroup();??
- ??????????rbMenuItem?=?new?JRadioButtonMenuItem("(R)使用radio的菜单");??
- ????????rbMenuItem.setSelected(true);??????????rbMenuItem.setMnemonic(KeyEvent.VK_R);??
- ????????group.add(rbMenuItem);??????????rbMenuItem.addActionListener(this);??
- ????????menu.add(rbMenuItem);????
- ????????rbMenuItem?=?new?JRadioButtonMenuItem("(d)另外一个radio菜单");??????????rbMenuItem.setMnemonic(KeyEvent.VK_D);??
- ????????group.add(rbMenuItem);??????????rbMenuItem.addActionListener(this);??
- ????????menu.add(rbMenuItem);????
- ????????//定义一组check?box(检查盒)菜单??????????menu.addSeparator();??
- ????????cbMenuItem?=?new?JCheckBoxMenuItem("(C)使用检查盒的菜单");??????????cbMenuItem.setMnemonic(KeyEvent.VK_C);??
- ????????cbMenuItem.addItemListener(this);??????????menu.add(cbMenuItem);??
- ??????????cbMenuItem?=?new?JCheckBoxMenuItem("(H)另外一个检查盒");??
- ????????cbMenuItem.setMnemonic(KeyEvent.VK_H);??????????cbMenuItem.addItemListener(this);??
- ????????menu.add(cbMenuItem);????
- ????????//定义一个带子菜单??????????menu.addSeparator();??
- ????????submenu?=?new?JMenu("(S)带有子菜单");??????????submenu.setMnemonic(KeyEvent.VK_S);??
- ????????//定义子菜单??????????menuItem?=?new?JMenuItem("这是子菜单");??
- ????????//定义快捷键??????????menuItem.setAccelerator(KeyStroke.getKeyStroke(??
- ????????????????KeyEvent.VK_2,?ActionEvent.ALT_MASK));??????????menuItem.addActionListener(this);??
- ????????submenu.add(menuItem);????
- ????????menuItem?=?new?JMenuItem("子菜单项");??????????menuItem.addActionListener(this);??
- ????????submenu.add(menuItem);??????????menu.add(submenu);??
- ??????????//定义第二个菜单??
- ????????menu?=?new?JMenu("(N)第二个菜单");??????????menu.setMnemonic(KeyEvent.VK_N);??
- ????????menuBar.add(menu);????
- ????????return?menuBar;??????}??
- /**??*方法说明:构建面板?
- ?*输入参数:??*返回类型:?
- ?*/??????public?Container?createContentPane()?{??
- ????????//构造一个面板??????????JPanel?contentPane?=?new?JPanel(new?BorderLayout());??
- ????????contentPane.setOpaque(true);????
- ????????//定义一个文本域??????????output?=?new?JTextArea(5,?30);??
- ????????output.setEditable(false);??????????scrollPane?=?new?JScrollPane(output);??
- ??????????//将文本域添加到面板中??
- ????????contentPane.add(scrollPane,?BorderLayout.CENTER);????
- ????????return?contentPane;??????}??
- /**??*方法说明:构建弹出菜单?
- ?*输入参数:??*返回类型:?
- ?*/??????public?void?createPopupMenu()?{??
- ????????JMenuItem?menuItem;????
- ????????//构件弹出菜单??????????JPopupMenu?popup?=?new?JPopupMenu();??
- ????????ImageIcon?openicon?=?createImageIcon("images/Open16.gif");??????????menuItem?=?new?JMenuItem("打开文件",openicon);??
- ????????menuItem.addActionListener(this);??????????popup.add(menuItem);??
- ????????ImageIcon?saveicon?=?createImageIcon("images/Save16.gif");??????????menuItem?=?new?JMenuItem("保存文件",saveicon);??
- ????????menuItem.addActionListener(this);??????????popup.add(menuItem);??
- ??????????//添加一个监听给文本域,以便点击右键时响应??
- ????????MouseListener?popupListener?=?new?PopupListener(popup);??????????output.addMouseListener(popupListener);??
- ????}??/**?
- ?*方法说明:监听普通的菜单选择??*输入参数:ActionEvent?e?事件?
- ?*返回类型:??*/??
- ????public?void?actionPerformed(ActionEvent?e)?{??????????JMenuItem?source?=?(JMenuItem)(e.getSource());??
- ????????String?s?=?"监测事件。"?????????????????????+?newline??
- ???????????????????+?"????事件源:?"?+?source.getText()?????????????????????+?"?(选择对象"?+?getClassName(source)?+?")";??
- ????????output.append(s?+?newline);??????}??
- /**??*方法说明:监听检查盒菜单选择项?
- ?*输入参数:ItemEvent?e?检查盒触发的事件??*返回类型:?
- ?*/??????public?void?itemStateChanged(ItemEvent?e)?{??
- ????????JMenuItem?source?=?(JMenuItem)(e.getSource());??????????String?s?=?"菜单项监听"??
- ???????????????????+?newline?????????????????????+?"????事件源:?"?+?source.getText()??
- ???????????????????+?"?(选择对象?"?+?getClassName(source)?+?")"?????????????????????+?newline??
- ???????????????????+?"????新的状态:?"?????????????????????+?((e.getStateChange()?==?ItemEvent.SELECTED)????
- ?????????????????????"选择":"不选择");??????????output.append(s?+?newline);??
- ????}??/**?
- ?*方法说明:获得类的名字??*输入参数:?
- ?*返回类型:??*/??
- ????protected?String?getClassName(Object?o)?{??????????String?classString?=?o.getClass().getName();??
- ????????int?dotIndex?=?classString.lastIndexOf(".");??????????return?classString.substring(dotIndex+1);??
- ????}??/**?
- ?*方法说明:根据路径查找图片??*输入参数:String?path?图片的路径?
- ?*返回类型:ImageIcon?图片对象??*/??
- ????protected?static?ImageIcon?createImageIcon(String?path)?{??????????java.net.URL?imgURL?=?MenuDemo.class.getResource(path);??
- ????????if?(imgURL?!=?null)?{??????????????return?new?ImageIcon(imgURL);??
- ????????}?else?{??????????????System.err.println("Couldn't?find?file:?"?+?path);??
- ????????????return?null;??????????}??
- ????}????
- ????public?static?void?main(String[]?args)?{??????????JFrame.setDefaultLookAndFeelDecorated(true);??
- ??????????//创建一个窗体??
- ????????JFrame?frame?=?new?JFrame("MenuDemo");??????????frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);??
- ??????????//创建菜单,并添加到面板中??
- ????????MenuDemo?demo?=?new?MenuDemo();??????????frame.setJMenuBar(demo.createMenuBar());??
- ????????frame.setContentPane(demo.createContentPane());????
- ????????//生成弹出菜单??????????demo.createPopupMenu();??
- ??????????//显示窗体??
- ????????frame.setSize(450,?260);??????????frame.setVisible(true);??
- ????}??//弹出菜单监听类??
- ????class?PopupListener?extends?MouseAdapter?{??????????JPopupMenu?popup;??
- ??????????PopupListener(JPopupMenu?popupMenu)?{??
- ????????????popup?=?popupMenu;??????????}??
- ??????????????????public?void?mousePressed(MouseEvent?e)?{??
- ????????????maybeShowPopup(e);??????????}??
- ??????????public?void?mouseReleased(MouseEvent?e)?{??
- ????????????maybeShowPopup(e);??????????}??
- ??????????private?void?maybeShowPopup(MouseEvent?e)?{??
- ????????????if?(e.isPopupTrigger())?{??????????????????popup.show(e.getComponent(),??
- ???????????????????????????e.getX(),?e.getY());??????????????}??
- ????????}??????}??
- }??
?
view plain
- package?test20;????
- 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.net.URL;??
- ??import?java.awt.*;??
- import?java.awt.event.*;??/**?
- ?*?Title:?工具栏演示??*?Description:?提供一个工具栏,包括“打开”、“保存”、“搜索”工具按钮?
- ?*?Filename:?ToolBarDemo.java??*/??
- public?class?ToolBarDemo?extends?JPanel???????????????????????????implements?ActionListener?{??
- ??????private?static?final?long?serialVersionUID?=?1L;??
- ????protected?JTextArea?textArea;??????protected?String?newline?=?"\n";??
- ????static?final?private?String?OPEN?=?"OPEN";??????static?final?private?String?SAVE?=?"SAVE";??
- ????static?final?private?String?SEARCH?=?"SEARCH";??/**?
- ?*方法说明:构造器??*输入参数:?
- ?*返回类型:??*/??
- ????public?ToolBarDemo()?{??????????super(new?BorderLayout());??
- ??????????//创建工具栏??
- ????????JToolBar?toolBar?=?new?JToolBar();??????????addButtons(toolBar);??
- ??????????//创建一个文本域,用来输出一些信息??
- ????????textArea?=?new?JTextArea(15,?30);??????????textArea.setEditable(false);??
- ????????JScrollPane?scrollPane?=?new?JScrollPane(textArea);????
- ????????//安放成员??????????setPreferredSize(new?Dimension(450,?110));??
- ????????add(toolBar,?BorderLayout.PAGE_START);??????????add(scrollPane,?BorderLayout.CENTER);??
- ????}??/**?
- ?*方法说明:构建工具栏??*输入参数:JToolBar?toolBar?工具条?
- ?*返回类型:??*/??
- ????protected?void?addButtons(JToolBar?toolBar)?{??????????JButton?button?=?null;??
- ??????????//第一个按钮,“打开”??
- ????????button?=?makeNavigationButton("Open16",?OPEN,????????????????????????????????????????"打开一个文件!",??
- ??????????????????????????????????????"打开");??????????toolBar.add(button);??
- ??????????//第二个按钮,“保存”??
- ????????button?=?makeNavigationButton("Save16",?SAVE,????????????????????????????????????????"保存当前文件!",??
- ??????????????????????????????????????"保存");??????????toolBar.add(button);??
- ??????????//第三个按钮,“搜索”??
- ????????button?=?makeNavigationButton("Search16",?SEARCH,????????????????????????????????????????"搜索文件中的字符!",??
- ??????????????????????????????????????"搜索");??????????toolBar.add(button);??
- ????}??/**?
- ?*方法说明:构造工具栏上的按钮??*输入参数:?
- ?*返回类型:??*/??
- ????protected?JButton?makeNavigationButton(String?imageName,?????????????????????????????????????????????String?actionCommand,??
- ???????????????????????????????????????????String?toolTipText,?????????????????????????????????????????????String?altText)?{??
- ????????//搜索图片??????????String?imgLocation?=?"images/"??
- ?????????????????????????????+?imageName???????????????????????????????+?".gif";??
- ????????URL?imageURL?=?ToolBarDemo.class.getResource(imgLocation);????
- ????????//初始化工具按钮??????????JButton?button?=?new?JButton();??
- ????????//设置按钮的命令??????????button.setActionCommand(actionCommand);??
- ????????//设置提示信息??????????button.setToolTipText(toolTipText);??
- ????????button.addActionListener(this);????????????
- ????????if?(imageURL?!=?null)?{??????????????????????//找到图像??????????????button.setIcon(new?ImageIcon(imageURL));??
- ????????}?else?{?????????????????????????????????????//没有图像??????????????button.setText(altText);??
- ????????????System.err.println("Resource?not?found:?"?????????????????????????????????+?imgLocation);??
- ????????}????
- ????????return?button;??????}??
- /**??*方法说明:事件监听?
- ?*输入参数:??*返回类型:?
- ?*/??????public?void?actionPerformed(ActionEvent?e)?{??
- ????????String?cmd?=?e.getActionCommand();??????????String?description?=?null;??
- ??????????if?(OPEN.equals(cmd))?{?//点击第一个按钮??
- ????????????description?=?"打开一个文件操作!";??????????}?else?if?(SAVE.equals(cmd))?{?//点击第二个按钮??
- ????????????description?=?"保存文件操作";??????????}?else?if?(SEARCH.equals(cmd))?{?//点击第三个按钮??
- ????????????description?=?"搜索字符操作";??????????}??
- ??????????displayResult("如果这里是真正的程序,你将进入:?"??
- ????????????????????????+?description);??????}??
- ??????protected?void?displayResult(String?actionDescription)?{??
- ????????textArea.append(actionDescription?+?newline);??????}??
- ??????public?static?void?main(String[]?args)?{??
- ????????JFrame.setDefaultLookAndFeelDecorated(true);????
- ????????//定义窗体??????????JFrame?frame?=?new?JFrame("ToolBarDemo");??
- ????????frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);????
- ????????//定义面板??????????ToolBarDemo?newContentPane?=?new?ToolBarDemo();??
- ????????newContentPane.setOpaque(true);??????????frame.setContentPane(newContentPane);??
- ??????????//显示窗体??
- ????????frame.pack();??????????frame.setVisible(true);??
- ????}??}?