zoukankan      html  css  js  c++  java
  • 201871010134-周英杰《面向对象程序设计(java)》第十五周学习总结

    项目

    内容

    这个作业属于哪个课程

    <任课教师博客主页链接>https://www.cnblogs.com/nwnu-daizh/

    这个作业的要求在哪里

    <作业链接地址>https://www.cnblogs.com/nwnu-daizh/p/11995615.htmll

    作业学习目标

    (1)掌握GUI布局管理器用法;

    (2)掌握Java Swing文本输入组件用途及常用API;

    (3)掌握Java Swing选择输入组件用途及常用API。

    第一部分:总结菜单、对话框两类组件用途及常用API

    一、菜单

    创建一个菜单栏:

    JMenuBar menuBar=new JMenuBar();

    将菜单栏放置在frame的顶部:

    frame.setMenuBar(menuBar);

    为每个菜单建立一个菜单对象:

    JMenu editMenu=new jMenu("Edit");

    将顶层菜单添加到菜单栏中:

    menuBar.add(editMenu);

    往菜单对象中添加菜单项、分隔符和子菜单:

    -JMenultem pasteltem=new JMenultem("Paste");  -editMenu.add(pasteltem)

    用户点击菜单项的动作监听器为实现ActionListener接口(actionPerformed方法)的类对象或关联一个动作事件:-ActionListenerlistener=pasteltem.addActionListener(listener),或将一个动作直接与菜单项关联

    菜单中的图标

    JMenuItem类扩展自AbstructButton类,故菜单项与按钮很相似。

    有3种方法为菜单项指定一个图标:

    构造器方法:

    -JMenultem cutltem=newJMenultem("Cut",newImagelcon("cut.gif")  //默认图形在名称的左侧

    seticon方法:

    -cutltem.seticon(new Imageicon("cut.gif");

    把一个图标添加到一个动作上,再用该动作构造菜单项;cutAction.putValue(Action.SMALL_ICON,new Imageicon("cut.gif"));  JMenultem cutltem =new JMenultem(cutAction);

    使用动作构造菜单项时,Action.NAME将会成为菜单项的文本,而Action.SMALL_ICON成为图标。

    弹出菜单

    弹出菜单(pop-up menu)即单击鼠标右键可弹出的快捷菜单。

    建立弹出菜单的方法与一般菜单相似:

    创建一个弹出式菜单:

    JPopupMenu popup=new JPopupMenu()

    在菜单中添加菜单项:

    JMenultem item=new JMenultem("Cut")

    item.addActionListener(listener);

    popup.add(item);

    弹出式触发器

    弹出式触发器(pop-up tigger):

    用户点击鼠标某个键时,弹出菜单。

    在Windows或者Linux中,弹出式触发器是右键。

    要想在用户点击某一个组件的时候弹出菜单,就要使用弹出式触发器:component.setComponentPopupMenu(pop up);

    快捷键

    可以为菜单项设置快捷键。在当前菜单打开的情况下,可以按下某菜单项的快捷键,相当于鼠标单击了该菜单项。

    JMenultem Cutltem=new JMenultem("lndex");

    Cutltem.setMnemonic("p")

    快捷键就会自动显示在菜单项中,快捷键下面有一条下划线。

    加速器

    加速器可以在不打开菜单的情况下选中菜单项的快捷键

    例如,很多程序把CTRL+O和CTRL+S关联到菜单中的Open和Save项。

    使用方法可以将加速器关联到一个菜单项。该方法使用类型的对象作为参数。

    当用户按下加速器组合键时,就自动选择了相应的菜单项,同时激活一个动作事件。

    注意:加速器实际上并不打开菜单,而是直接激活菜单关联的动作事件。


    启用和禁用菜单项

    在程序运行过程中,经常需要屏蔽某些暂时不适用的命令,待到条件允许时再使之重新可用。

    屏蔽/启用菜单项的方法:

    aMenultem.setEnabled(boolean)

    当参数值为ale时,屏蔽该菜单项,当参数值为tue时,启用该菜单项。

    如果需要动态启用/屏蔽某菜单项,则需要为“menu selected”事件注册监听器。javax.swing.event包定义了MenuListener接口,它有三个方法:

    void menuSelected(MenuEvent event)

    voidmenuDeselected(MenuEventevent)

    void menuCanceled(MenuEvent event)

    二、工具栏

    工具栏是在程序中提供快速访问常用命令的按钮栏。

    工具栏的特别之处在于可以移动,脱离工具栏或拖拽到框架其他地方。

    工具栏的创建

    创建工具栏时,直接将组件添加到工具栏中,再将工具栏放入框架

    JToolBar bar=new JToolBar();

    -bar. add(blue Button);

    -frame.add(bar,BorderLayout.NORTH);

    也可以使用添加Action对象的方法来填充工具栏:-bar.add(blueAction)

    可以设置工具提示:-setToolTipText(String);

    如果使用Action对象,则可使用PutValue方法

    注意;按钮是工具栏中最賞见的组件类型。但其它组件也可以放置在工具栏中,例如复选框等。

    工具栏相关的常用方法

    Java.swing.JToolBar

    JToolBar()

    JToolBar(String titleString)

    JToolBar(intorientation)

    JButton add(Action a) //在工具栏添加与动作a关联的按钮

    void addSeparator() //在工具栏末尾添加一个分隔符

    Java.swing. JToolBar

    void setToolTipText(String text) //设置当鼠标停留在组件上时显示的工具提示的文本

    对话框的种类

    对话框分为模式对话框和无模式对话框。

    模式对话框

    在用户结束对它的操作之前,不允许用户与应用程序其他窗口的交互

    模式对话框的作用:在程序继续运行之前,必须获得用户提供的信息。

    无模式对话框

    无模式对话框运行用户同时在对话框和应用程序的其它窗口中输入信息

    例如:工具栏:工具栏可以停靠在任何地方,并且用户可以在需要时与应用程序窗口和工具栏进行交互。

    一些常用的对话框:

    选项对话框

    Swing提供了一组简单的对话框,用于收集用户提供的简单信息。有四个用于显示这些简单对话框的静态方法

    showMessageDialog:显示一条消息,并等待用户点击OK

    showConfirmDialog:显示一条消息,并等待用户点击确认(与按钮类似)

    showOptionDialog:显示一条消息,并等待用户作出某一种选择

    showInputDialog:显示一条消息,并等待用户输入一行信息

    创建对话框

    创建一个对话框的步骤:

    创建一个派生自JDialog类的子类。

    在子类的构造器中,需要进行以下工作

    调用超类的构造器,用于指定对话框的拥有者(owner frame),(也可以设置为null,但这样对话框有可能被隐藏在其它窗口后面),对话框的标题以及是否模式对话框

    添加对话框的用户界面组件

    添加相应的事件处理器

    设置对话框的大小

    使用对话框的一个重要目的是获取用户的输入信息

    文本对话框

    文件对话框甩于帮助用戶打开或煮保存文件。下面是建立文件对话框并且获取用戶选择信息的步骤:

    建立一个对象。与类构造器不同,这种对象不需要指定父组件,因而允许在多个框架中重用一个文件选择器

    JFileChooser chooser=new JFileChooser0);

    调用方法设置当前目录

    chooser.setCurrentDirectory(new File("… "))

    如果要指定一个默认的文件名,可以使用setSelected方法

    chooser.setSelectedFile(newFile(filename))

    如果要允许用户能同时选中多个文件,可以使用setMultiSelectionEnabled方法

    chooser.setMultiSelectionEnabled(true);

    如果希望在对话框中只显示某一类型的文件(如所有.gif文件),则需要文件过滤器。

    默认情况下只能选中文件,如果希望允许用户选择目录,则需要使用setFileSelectionMode方法。

    调用showOpenDialog或者showSaveDialog方法显示对话框。必须为这些调用指定父组件:

    int result=chooser.showOpenDialog(parent)

    int result=chooser. showSaveDialog(parent);

    使用getSelectedFile或者getSelectedFiles获得选中的一个或多个文件。这些方法返回一个File对象或者组File对象。如果需要文件对象名字时,可以调用getPath方法

    String filename=chooser.getSelectedfile().getPath();

    第二部分:实验部分

    实验1:测试程序1(7分)

    程序代码如下:

    package menu;
     
    import java.awt.event.*;
    import javax.swing.*;
     
    /**
     * 一个带有示例菜单栏的框架。
     */
    public class MenuFrame extends JFrame
    {
       private static final int DEFAULT_WIDTH = 300;
       private static final int DEFAULT_HEIGHT = 200;
       private Action saveAction;
       private Action saveAsAction;
       private JCheckBoxMenuItem readonlyItem;
       private JPopupMenu popup;
     
       /**
        * 将动作名称打印到Studio.OUT的示例动作。
        */
       class TestAction extends AbstractAction
       {
          public TestAction(String name)
          {
             super(name);
          }
     
          public void actionPerformed(ActionEvent event)
          {
             System.out.println(getValue(Action.NAME) + " selected.");
          }
       }
     
       public MenuFrame()
       {
          setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
     
          JMenu fileMenu = new JMenu("File");
          fileMenu.add(new TestAction("New"));
     
          // 演示加速器
          JMenuItem openItem = fileMenu.add(new TestAction("Open"));
          openItem.setAccelerator(KeyStroke.getKeyStroke("ctrl O"));
     
          fileMenu.addSeparator();
     
          saveAction = new TestAction("Save");
          JMenuItem saveItem = fileMenu.add(saveAction);
          saveItem.setAccelerator(KeyStroke.getKeyStroke("ctrl S"));
     
          saveAsAction = new TestAction("Save As");
          fileMenu.add(saveAsAction);
          fileMenu.addSeparator();
     
          fileMenu.add(new AbstractAction("Exit")
             {
                public void actionPerformed(ActionEvent event)
                {
                   System.exit(0);
                }
             });
     
          // 演示复选框和单选按钮菜单
     
          readonlyItem = new JCheckBoxMenuItem("Read-only");
          readonlyItem.addActionListener(new ActionListener()
             {
                public void actionPerformed(ActionEvent event)
                {
                   boolean saveOk = !readonlyItem.isSelected();
                   saveAction.setEnabled(saveOk);
                   saveAsAction.setEnabled(saveOk);
                }
             });
     
          ButtonGroup group = new ButtonGroup();
     
          JRadioButtonMenuItem insertItem = new JRadioButtonMenuItem("Insert");
          insertItem.setSelected(true);
          JRadioButtonMenuItem overtypeItem = new JRadioButtonMenuItem("Overtype");
     
          group.add(insertItem);
          group.add(overtypeItem);
     
          // 演示图标
     
          Action cutAction = new TestAction("Cut");
          cutAction.putValue(Action.SMALL_ICON, new ImageIcon("cut.gif"));
          Action copyAction = new TestAction("Copy");
          copyAction.putValue(Action.SMALL_ICON, new ImageIcon("copy.gif"));
          Action pasteAction = new TestAction("Paste");
          pasteAction.putValue(Action.SMALL_ICON, new ImageIcon("paste.gif"));
     
          JMenu editMenu = new JMenu("Edit");
          editMenu.add(cutAction);
          editMenu.add(copyAction);
          editMenu.add(pasteAction);
     
          // 演示嵌套菜单
     
          JMenu optionMenu = new JMenu("Options");
     
          optionMenu.add(readonlyItem);
          optionMenu.addSeparator();
          optionMenu.add(insertItem);
          optionMenu.add(overtypeItem);
     
          editMenu.addSeparator();
          editMenu.add(optionMenu);
     
          // 助记符演示
     
          JMenu helpMenu = new JMenu("Help");
          helpMenu.setMnemonic('H');
     
          JMenuItem indexItem = new JMenuItem("Index");
          indexItem.setMnemonic('I');
          helpMenu.add(indexItem);
     
          // 还可以将助记键添加到动作中。
          Action aboutAction = new TestAction("About");
          aboutAction.putValue(Action.MNEMONIC_KEY, new Integer('A'));
          helpMenu.add(aboutAction);
           
          // 将所有顶级菜单添加到菜单栏
     
          JMenuBar menuBar = new JMenuBar();
          setJMenuBar(menuBar);
     
          menuBar.add(fileMenu);
          menuBar.add(editMenu);
          menuBar.add(helpMenu);
     
          // 演示弹出窗口
     
          popup = new JPopupMenu();
          popup.add(cutAction);
          popup.add(copyAction);
          popup.add(pasteAction);
     
          JPanel panel = new JPanel();
          panel.setComponentPopupMenu(popup);
          add(panel);
       }
    }
     
    package menu;
     
    import java.awt.*;
    import javax.swing.*;
     
    /**
     * @version 1.25 2018-04-10
     * @author Cay Horstmann
     */
    public class MenuTest
    {
       public static void main(String[] args)
       {
          EventQueue.invokeLater(() -> {
             var frame = new MenuFrame();
             frame.setTitle("MenuTest");
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.setVisible(true);
          });
       }
    }
     
      运行结果如下:

    (1)快捷键:

    可以为菜单项设置快捷键。在当前菜单打开的情况下,可以按下某菜单项的快捷键,相当于鼠标单击了该菜单项。

    JMenultem Cutltem=new JMenultem("lndex");

    Cutltem.setMnemonic("p")

    快捷键就会自动显示在菜单项中,快捷键下面有一条下划线。

    (2)加速器:

    加速器可以在不打开菜单的情况下选中菜单项的快捷键

    例如,很多程序把CTRL+O和CTRL+S关联到菜单中的Open和Save项。

    使用方法可以将加速器关联到一个菜单项。该方法使用类型的对象作为参数。

    当用户按下加速器组合键时,就自动选择了相应的菜单项,同时激活一个动作事件。

    注意:加速器实际上并不打开菜单,而是直接激活菜单关联的动作事件。

    实验1:测试程序2(7分)

    程序代码如下:

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
     
    /**
     * 带有工具栏和菜单的框架,用于颜色变化。
     */
    public class ToolBarFrame extends JFrame
    {
       private static final int DEFAULT_WIDTH = 300;
       private static final int DEFAULT_HEIGHT = 200;
       private JPanel panel;
     
       public ToolBarFrame()
       {
          setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
     
          // 添加颜色变化面板
     
          panel = new JPanel();
          add(panel, BorderLayout.CENTER);
     
          // 设置动作
          Action blueAction = new ColorAction("Blue", new ImageIcon("blue-ball.gif"), Color.BLUE);
          Action yellowAction = new ColorAction("Yellow", new ImageIcon("yellow-ball.gif"),
                Color.YELLOW);
          Action redAction = new ColorAction("Red", new ImageIcon("red-ball.gif"), Color.RED);
     
          Action exitAction = new AbstractAction("Exit", new ImageIcon("exit.gif"))
             {
                public void actionPerformed(ActionEvent event)
                {
                   System.exit(0);
                }
             };
          exitAction.putValue(Action.SHORT_DESCRIPTION, "Exit");
     
          // 填充工具栏
     
          JToolBar bar = new JToolBar();
          bar.add(blueAction);
          bar.add(yellowAction);
          bar.add(redAction);
          bar.addSeparator();
          bar.add(exitAction);
          add(bar, BorderLayout.NORTH);
     
          // 填充菜单
     
          JMenu menu = new JMenu("Color");
          menu.add(yellowAction);
          menu.add(blueAction);
          menu.add(redAction);
          menu.add(exitAction);
          JMenuBar menuBar = new JMenuBar();
          menuBar.add(menu);
          setJMenuBar(menuBar);
       }
     
       /**
        * 颜色动作将帧的背景设置为给定的颜色。
        */
       class ColorAction extends AbstractAction
       {
          public ColorAction(String name, Icon icon, Color c)
          {
             putValue(Action.NAME, name);
             putValue(Action.SMALL_ICON, icon);
             putValue(Action.SHORT_DESCRIPTION, name + " background");
             putValue("Color", c);
          }
     
          public void actionPerformed(ActionEvent event)
          {
             Color c = (Color) getValue("Color");
             panel.setBackground(c);
          }
       }
    }
     
    import java.awt.*;
    import javax.swing.*;
     
    /**
     * @version 1.15 2018-04-10
     * @author Cay Horstmann
     */
    public class ToolBarTest
    {
       public static void main(String[] args)
       {
          EventQueue.invokeLater(() -> {
             var frame = new ToolBarFrame();
             frame.setTitle("ToolBarTest");
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.setVisible(true);
          });
       }
    }
     
     

    运行结果如下:

    工具栏相关的常用方法:

    Java.swing.JToolBar

    JToolBar()

    JToolBar(String titleString)

    JToolBar(intorientation)

    JButton add(Action a) //在工具栏添加与动作a关联的按钮

    void addSeparator() //在工具栏末尾添加一个分隔符

    Java.swing. JToolBar

    void setToolTipText(String text) //设置当鼠标停留在组件上时显示的工具提示的文本

    实验1:测试程序3(7分)

    程序代码如下:

     
    import javax.swing.*;
      
    /**
     * A panel with radio buttons inside a titled border.
     */
    public class ButtonPanel extends JPanel
    {
       private ButtonGroup group;
      
       /**
        * Constructs a button panel.
        * @param title the title shown in the border
        * @param options an array of radio button labels
        */
       public ButtonPanel(String title, String... options)
       {
          setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), title));
          setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
          group = new ButtonGroup();
      
          //为每个选项做一个单选按钮
          for (String option : options)
          {
             JRadioButton b = new JRadioButton(option);
             b.setActionCommand(option);
             add(b);
             group.add(b);
             b.setSelected(option == options[0]);
          }
       }
      
       /**
        * Gets the currently selected option.
        * @return the label of the currently selected radio button.
        */
       public String getSelection()
       {
          return group.getSelection().getActionCommand();
       }
    }

     

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    import javax.swing.*;
     
    /**
     * A frame that contains settings for selecting various option dialogs.
     */
    public class OptionDialogFrame extends JFrame
    {
       private ButtonPanel typePanel;
       private ButtonPanel messagePanel;
       private ButtonPanel messageTypePanel;
       private ButtonPanel optionTypePanel;
       private ButtonPanel optionsPanel;
       private ButtonPanel inputPanel;
       private String messageString = "Message";
       private Icon messageIcon = new ImageIcon("blue-ball.gif");
       private Object messageObject = new Date();
       private Component messageComponent = new SampleComponent();
     
       public OptionDialogFrame()
       {
          var gridPanel = new JPanel();
          gridPanel.setLayout(new GridLayout(2, 3));
     
          typePanel = new ButtonPanel("Type", "Message", "Confirm", "Option", "Input");
          messageTypePanel = new ButtonPanel("Message Type", "ERROR_MESSAGE", "INFORMATION_MESSAGE",
                "WARNING_MESSAGE", "QUESTION_MESSAGE", "PLAIN_MESSAGE");
          messagePanel = new ButtonPanel("Message", "String", "Icon", "Component", "Other",
                "Object[]");
          optionTypePanel = new ButtonPanel("Confirm", "DEFAULT_OPTION", "YES_NO_OPTION",
                "YES_NO_CANCEL_OPTION", "OK_CANCEL_OPTION");
          optionsPanel = new ButtonPanel("Option", "String[]", "Icon[]", "Object[]");
          inputPanel = new ButtonPanel("Input", "Text field", "Combo box");
     
          gridPanel.add(typePanel);
          gridPanel.add(messageTypePanel);
          gridPanel.add(messagePanel);
          gridPanel.add(optionTypePanel);
          gridPanel.add(optionsPanel);
          gridPanel.add(inputPanel);
     
          // 添加带有显示按钮的面板
     
          var showPanel = new JPanel();
          var showButton = new JButton("Show");
          showButton.addActionListener(new ShowAction());
          showPanel.add(showButton);
     
          add(gridPanel, BorderLayout.CENTER);
          add(showPanel, BorderLayout.SOUTH);
          pack();
       }
     
       /**
        * Gets the currently selected message.
        * @return a string, icon, component, or object array, depending on the Message panel selection
        */
       public Object getMessage()
       {
          String s = messagePanel.getSelection();
          if (s.equals("String")) return messageString;
          else if (s.equals("Icon")) return messageIcon;
          else if (s.equals("Component")) return messageComponent;
          else if (s.equals("Object[]")) return new Object[] { messageString, messageIcon,
                messageComponent, messageObject };
          else if (s.equals("Other")) return messageObject;
          else return null;
       }
     
       /**
        * Gets the currently selected options.
        * @return an array of strings, icons, or objects, depending on the Option panel selection
        */
       public Object[] getOptions()
       {
          String s = optionsPanel.getSelection();
          if (s.equals("String[]")) return new String[] { "Yellow", "Blue", "Red" };
          else if (s.equals("Icon[]")) return new Icon[] { new ImageIcon("yellow-ball.gif"),
                new ImageIcon("blue-ball.gif"), new ImageIcon("red-ball.gif") };
          else if (s.equals("Object[]")) return new Object[] { messageString, messageIcon,
                messageComponent, messageObject };
          else return null;
       }
     
       /**
        * Gets the selected message or option type
        * @param panel the Message Type or Confirm panel
        * @return the selected XXX_MESSAGE or XXX_OPTION constant from the JOptionPane class
        */
       public int getType(ButtonPanel panel)
       {
          String s = panel.getSelection();
          try
          {
             return JOptionPane.class.getField(s).getInt(null);
          }
          catch (Exception e)
          {
             return -1;
          }
       }
     
       /**
        * The action listener for the Show button shows a Confirm, Input, Message, or Option dialog
        * depending on the Type panel selection.
        */
       private class ShowAction implements ActionListener
       {
          public void actionPerformed(ActionEvent event)
          {
             if (typePanel.getSelection().equals("Confirm")) JOptionPane.showConfirmDialog(
                   OptionDialogFrame.this, getMessage(), "Title", getType(optionTypePanel),
                   getType(messageTypePanel));
             else if (typePanel.getSelection().equals("Input"))
             {
                if (inputPanel.getSelection().equals("Text field")) JOptionPane.showInputDialog(
                      OptionDialogFrame.this, getMessage(), "Title", getType(messageTypePanel));
                else JOptionPane.showInputDialog(OptionDialogFrame.this, getMessage(), "Title",
                      getType(messageTypePanel), null, new String[] { "Yellow", "Blue", "Red" },
                      "Blue");
             }
             else if (typePanel.getSelection().equals("Message")) JOptionPane.showMessageDialog(
                   OptionDialogFrame.this, getMessage(), "Title", getType(messageTypePanel));
             else if (typePanel.getSelection().equals("Option")) JOptionPane.showOptionDialog(
                   OptionDialogFrame.this, getMessage(), "Title", getType(optionTypePanel),
                   getType(messageTypePanel), null, getOptions(), getOptions()[0]);
          }
       }
    }
     
    /**
     * A component with a painted surface
     */
     
    class SampleComponent extends JComponent
    {
       public void paintComponent(Graphics g)
       {
          var g2 = (Graphics2D) g;
          var rect = new Rectangle2D.Double(0, 0, getWidth() - 1, getHeight() - 1);
          g2.setPaint(Color.YELLOW);
          g2.fill(rect);
          g2.setPaint(Color.BLUE);
          g2.draw(rect);
       }
     
       public Dimension getPreferredSize()
       {
          return new Dimension(10, 10);
       }
    }
    import java.awt.*;
    import javax.swing.*;
     
    /**
     * @version 1.35 2018-04-10
     * @author Cay Horstmann
     */
    public class OptionDialogTest
    {
       public static void main(String[] args)
       {
          EventQueue.invokeLater(() -> {
             var frame = new OptionDialogFrame();
             frame.setTitle("OptionDialogTest");
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.setVisible(true);
          });
       }
    }

     

      
     

    运行结果如下:

    选项对话框:

    Swing提供了一组简单的对话框,用于收集用户提供的简单信息。有四个用于显示这些简单对话框的静态方法

    showMessageDialog:显示一条消息,并等待用户点击OK

    showConfirmDialog:显示一条消息,并等待用户点击确认(与按钮类似)

    showOptionDialog:显示一条消息,并等待用户作出某一种选择

    showInputDialog:显示一条消息,并等待用户输入一行信息 

    实验1:测试程序4(7分)

    程序代码如下:

     
    import java.awt.BorderLayout;
      
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
      
    /**
     * A sample modal dialog that displays a message and waits for the user to click the OK button.
     */
    public class AboutDialog extends JDialog
    {
       public AboutDialog(JFrame owner)
       {
          super(owner, "About DialogTest", true);
      
          // 添加HTML标签到中心
          add(
                new JLabel(
                      "<html><h1><i>Core Java</i></h1><hr>By Cay Horstmann</html>"),
                BorderLayout.CENTER);
      
          // OK按钮关闭对话框
      
          JButton ok = new JButton("OK");
          ok.addActionListener(event -> setVisible(false));
      
          // 添加OK按钮到南部边框
          JPanel panel = new JPanel();
          panel.add(ok);
          add(panel, BorderLayout.SOUTH);
      
          pack();
       }
    }

      

     
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
      
    /**
     * A frame with a menu whose File->About action shows a dialog.
     */
    public class DialogFrame extends JFrame
    {
       private static final int DEFAULT_WIDTH = 300;
       private static final int DEFAULT_HEIGHT = 200;
       private AboutDialog dialog;
      
       public DialogFrame()
       {
          setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
      
          // 构造一个文件菜单。
      
          JMenuBar menuBar = new JMenuBar();
          setJMenuBar(menuBar);
          JMenu fileMenu = new JMenu("File");
          menuBar.add(fileMenu);
      
          // 添加和退出菜单项
      
          //有关项目显示有关对话框.
      
          JMenuItem aboutItem = new JMenuItem("About");
          aboutItem.addActionListener(event -> {
             if (dialog == null) // first time
                dialog = new AboutDialog(DialogFrame.this);
             dialog.setVisible(true); // pop up dialog
          });
          fileMenu.add(aboutItem);
      
          // 退出项退出程序。
      
          JMenuItem exitItem = new JMenuItem("Exit");
          exitItem.addActionListener(event -> System.exit(0));
          fileMenu.add(exitItem);
       }
    }
    import java.awt.*;
    import javax.swing.*;
     
    /**
     * @version 1.35 2018-04-10
     * @author Cay Horstmann
     */
    public class DialogTest
    {
       public static void main(String[] args)
       {
          EventQueue.invokeLater(() -> {
             var frame = new DialogFrame();
             frame.setTitle("DialogTest");
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.setVisible(true);
          });
       }
    }

      

     

     运行结果如下:

    创建对话框:

    创建一个对话框的步骤:

    1.创建一个派生自JDialog类的子类。

    2.在子类的构造器中,需要进行以下工作

    (1)调用超类的构造器,用于指定对话框的拥有者(owner frame),(也可以设置为null,但这样对话框有可能被隐藏在其它窗口后面),对话框的标题以及是否模式对话框

    (2)添加对话框的用户界面组件

    (3)添加相应的事件处理器

    (4)设置对话框的大小

    使用对话框的一个重要目的是获取用户的输入信息

    实验1:测试程序5(7分)

    程序代码如下:

     
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
      
    /**
     * A frame with a menu whose File->Connect action shows a password dialog.
     */
    public class DataExchangeFrame extends JFrame
    {
       public static final int TEXT_ROWS = 20;
       public static final int TEXT_COLUMNS = 40;
       private PasswordChooser dialog = null;
       private JTextArea textArea;
      
       public DataExchangeFrame()
       {
          // 建构档案选单
      
          JMenuBar mbar = new JMenuBar();
          setJMenuBar(mbar);
          JMenu fileMenu = new JMenu("File");
          mbar.add(fileMenu);
      
          //添加连接和退出菜单项
          JMenuItem connectItem = new JMenuItem("Connect");
          connectItem.addActionListener(new ConnectAction());
          fileMenu.add(connectItem);
      
          // 退出项退出程序
      
          JMenuItem exitItem = new JMenuItem("Exit");
          exitItem.addActionListener(event -> System.exit(0));
          fileMenu.add(exitItem);
      
          textArea = new JTextArea(TEXT_ROWS, TEXT_COLUMNS);
          add(new JScrollPane(textArea), BorderLayout.CENTER);
          pack();
       }
      
       /**
        * The Connect action pops up the password dialog.
        */
       private class ConnectAction implements ActionListener
       {
          public void actionPerformed(ActionEvent event)
          {
             // 如果第一次,构造对话框
      
             if (dialog == null) dialog = new PasswordChooser();
      
             //设定预设值
             dialog.setUser(new User("yourname", null));
      
             //弹出对话框
             if (dialog.showDialog(DataExchangeFrame.this, "Connect"))
             {
                // 如果接受,则检索用户输入
                User u = dialog.getUser();
                textArea.append("user name = " + u.getName() + ", password = "
                      + (new String(u.getPassword())) + "
    ");
             }
          }
       }
    }

      

     
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
      
    /**
     * A frame with a menu whose File->Connect action shows a password dialog.
     */
    public class DataExchangeFrame extends JFrame
    {
       public static final int TEXT_ROWS = 20;
       public static final int TEXT_COLUMNS = 40;
       private PasswordChooser dialog = null;
       private JTextArea textArea;
      
       public DataExchangeFrame()
       {
          // 建构档案选单
      
          JMenuBar mbar = new JMenuBar();
          setJMenuBar(mbar);
          JMenu fileMenu = new JMenu("File");
          mbar.add(fileMenu);
      
          //添加连接和退出菜单项
          JMenuItem connectItem = new JMenuItem("Connect");
          connectItem.addActionListener(new ConnectAction());
          fileMenu.add(connectItem);
      
          // 退出项退出程序
      
          JMenuItem exitItem = new JMenuItem("Exit");
          exitItem.addActionListener(event -> System.exit(0));
          fileMenu.add(exitItem);
      
          textArea = new JTextArea(TEXT_ROWS, TEXT_COLUMNS);
          add(new JScrollPane(textArea), BorderLayout.CENTER);
          pack();
       }
      
       /**
        * The Connect action pops up the password dialog.
        */
       private class ConnectAction implements ActionListener
       {
          public void actionPerformed(ActionEvent event)
          {
             // 如果第一次,构造对话框
      
             if (dialog == null) dialog = new PasswordChooser();
      
             //设定预设值
             dialog.setUser(new User("yourname", null));
      
             //弹出对话框
             if (dialog.showDialog(DataExchangeFrame.this, "Connect"))
             {
                // 如果接受,则检索用户输入
                User u = dialog.getUser();
                textArea.append("user name = " + u.getName() + ", password = "
                      + (new String(u.getPassword())) + "
    ");
             }
          }
       }
    }

      

     
    import java.awt.*;
    import javax.swing.*;
     
    /**
     * @version 1.35 2018-04-10
     * @author Cay Horstmann
     */
    public class DataExchangeTest
    {
       public static void main(String[] args)
       {
          EventQueue.invokeLater(() -> {
             var frame = new DataExchangeFrame();
             frame.setTitle("DataExchangeTest");
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.setVisible(true);
          });
       }
    }

      

    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Frame;
    import java.awt.GridLayout;
      
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JPasswordField;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
      
    /**
     * A password chooser that is shown inside a dialog
     */
    public class PasswordChooser extends JPanel
    {
       private JTextField username;
       private JPasswordField password;
       private JButton okButton;
       private boolean ok;
       private JDialog dialog;
      
       public PasswordChooser()
       {
          setLayout(new BorderLayout());
      
          // 构造带有用户名和密码字段的面板
      
          JPanel panel = new JPanel();
          panel.setLayout(new GridLayout(2, 2));
          panel.add(new JLabel("User name:"));
          panel.add(username = new JTextField(""));
          panel.add(new JLabel("Password:"));
          panel.add(password = new JPasswordField(""));
          add(panel, BorderLayout.CENTER);
      
          //创建“确定”并取消终止对话框的按钮
      
          okButton = new JButton("Ok");
          okButton.addActionListener(event -> {
             ok = true;
             dialog.setVisible(false);
          });
      
          JButton cancelButton = new JButton("Cancel");
          cancelButton.addActionListener(event -> dialog.setVisible(false));
      
          // 添加按钮到南部边界
      
          JPanel buttonPanel = new JPanel();
          buttonPanel.add(okButton);
          buttonPanel.add(cancelButton);
          add(buttonPanel, BorderLayout.SOUTH);
       }
      
       /**
        * Sets the dialog defaults.
        * @param u the default user information
        */
       public void setUser(User u)
       {
          username.setText(u.getName());
       }
      
       /**
        * Gets the dialog entries.
        * @return a User object whose state represents the dialog entries
        */
       public User getUser()
       {
          return new User(username.getText(), password.getPassword());
       }
      
       /**
        * Show the chooser panel in a dialog
        * @param parent a component in the owner frame or null
        * @param title the dialog window title
        */
       public boolean showDialog(Component parent, String title)
       {
          ok = false;
      
          // 找到所有者框架
          Frame owner = null;
          if (parent instanceof Frame)
             owner = (Frame) parent;
          else
             owner = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, parent);
      
          // 如果第一次,或者所有者已经改变,请创建新的对话框
      
          if (dialog == null || dialog.getOwner() != owner)
          {
             dialog = new JDialog(owner, true);
             dialog.add(this);
             dialog.getRootPane().setDefaultButton(okButton);
             dialog.pack();
          }
      
          // 设定标题及显示对话框
      
          dialog.setTitle(title);
          dialog.setVisible(true);
          return ok;
       }
    }
     

     

    package dataExchange;
     
    /**
     * A user has a name and password. For security reasons, the password is stored as a char[], not a
     * String.
     */
    public class User
    {
       private String name;
       private char[] password;
     
       public User(String aName, char[] aPassword)
       {
          name = aName;
          password = aPassword;
       }
     
       public String getName()
       {
          return name;
       }
     
       public char[] getPassword()
       {
          return password;
       }
     
       public void setName(String aName)
       {
          name = aName;
       }
     
       public void setPassword(char[] aPassword)
       {
          password = aPassword;
       }
    }

     

      运行结果如下:

    实验1:测试程序6(7分)

    import java.awt.*;
    import javax.swing.*;
     
    /**
     * @version 1.26 2018-04-10
     * @author Cay Horstmann
     */
    public class FileChooserTest
    {
       public static void main(String[] args)
       {
          EventQueue.invokeLater(() -> {
             var frame = new ImageViewerFrame();
             frame.setTitle("FileChooserTest");
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.setVisible(true);
          });
       }
    }

      

     
    import java.io.*;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    import javax.swing.filechooser.FileFilter;
     
    /**
     * A file view that displays an icon for all files that match a file filter.
     */
    public class FileIconView extends FileView
    {
       private FileFilter filter;
       private Icon icon;
     
       /**
        * Constructs a FileIconView.
        * @param aFilter a file filter--all files that this filter accepts will be shown
        * with the icon.
        * @param anIcon--the icon shown with all accepted files.
        */
       public FileIconView(FileFilter aFilter, Icon anIcon)
       {
          filter = aFilter;
          icon = anIcon;
       }
     
       public Icon getIcon(File f)
       {
          if (!f.isDirectory() && filter.accept(f)) return icon;
          else return null;
       }
    }

     

    import java.awt.*;
    import java.io.*;
      
    import javax.swing.*;
      
    /**
     * A file chooser accessory that previews images.
     */
    public class ImagePreviewer extends JLabel
    {
       /**
        * Constructs an ImagePreviewer.
        * @param chooser the file chooser whose property changes trigger an image
        *        change in this previewer
        */
       public ImagePreviewer(JFileChooser chooser)
       {
          setPreferredSize(new Dimension(100, 100));
          setBorder(BorderFactory.createEtchedBorder());
      
          chooser.addPropertyChangeListener(event -> {
             if (event.getPropertyName() == JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)
             {
                //用户选择了一个新文件
                File f = (File) event.getNewValue();
                if (f == null)
                {
                   setIcon(null);
                   return;
                }
      
                //将影像读取成图示
                ImageIcon icon = new ImageIcon(f.getPath());
      
                // 如果图标太大,无法安装,请缩放
                if (icon.getIconWidth() > getWidth())
                   icon = new ImageIcon(icon.getImage().getScaledInstance(
                         getWidth(), -1, Image.SCALE_DEFAULT));
      
                setIcon(icon);
             }
          });
       }
    }

      

    import java.io.*;
      
    import javax.swing.*;
    import javax.swing.filechooser.*;
    import javax.swing.filechooser.FileFilter;
      
    /**
     * A frame that has a menu for loading an image and a display area for the
     * loaded image.
     */
    public class ImageViewerFrame extends JFrame
    {
       private static final int DEFAULT_WIDTH = 300;
       private static final int DEFAULT_HEIGHT = 400;
       private JLabel label;
       private JFileChooser chooser;
      
       public ImageViewerFrame()
       {
          setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
      
          // 设置菜单栏
          JMenuBar menuBar = new JMenuBar();
          setJMenuBar(menuBar);
      
          JMenu menu = new JMenu("File");
          menuBar.add(menu);
      
          JMenuItem openItem = new JMenuItem("Open");
          menu.add(openItem);
          openItem.addActionListener(event -> {
             chooser.setCurrentDirectory(new File("."));
      
             // 显示文件选择器对话框
                int result = chooser.showOpenDialog(ImageViewerFrame.this);
      
                // 如果图像文件被接受,将其设置为标签的图标
                if (result == JFileChooser.APPROVE_OPTION)
                {
                   String name = chooser.getSelectedFile().getPath();
                   label.setIcon(new ImageIcon(name));
                   pack();
                }
             });
      
          JMenuItem exitItem = new JMenuItem("Exit");
          menu.add(exitItem);
          exitItem.addActionListener(event -> System.exit(0));
      
          //使用标签显示影像
          label = new JLabel();
          add(label);
      
          // 设置文件选择器
          chooser = new JFileChooser();
      
          //接受所有以之结尾的影像档案。JPG。杰伯图形交换格式
          FileFilter filter = new FileNameExtensionFilter(
                "Image files", "jpg", "jpeg", "gif");
          chooser.setFileFilter(filter);
      
          chooser.setAccessory(new ImagePreviewer(chooser));
      
          chooser.setFileView(new FileIconView(filter, new ImageIcon("palette.gif")));
       }
    }

      运行结果如下:

    文本对话框:

    文件对话框甩于帮助用户打开或者保存文件。下面是建立文件对话框并且获取用户选择信息的步骤:

    1.建立一个对象。与类构造器不同,这种对象不需要指定父组件,因而允许在多个框架中重用一个文件选择器

    JFileChooser chooser=new JFileChooser0);

    2.调用方法设置当前目录

    chooser.setCurrentDirectory(new File("… "))

    3.如果要指定一个默认的文件名,可以使用setSelected方法

    chooser.setSelectedFile(newFile(filename))

    4.如果要允许用户能同时选中多个文件,可以使用setMultiSelectionEnabled方法

    chooser.setMultiSelectionEnabled(true);

    5.如果希望在对话框中只显示某一类型的文件(如所有.gif文件),则需要文件过滤器。

    6.默认情况下只能选中文件,如果希望允许用户选择目录,则需要使用setFileSelectionMode方法。

    7.调用showOpenDialog或者showSaveDialog方法显示对话框。必须为这些调用指定父组件:

    int result=chooser.showOpenDialog(parent)

    int result=chooser. showSaveDialog(parent);

    8.使用getSelectedFile或者getSelectedFiles获得选中的一个或多个文件。这些方法返回一个File对象或者组File对象。如果需要文件对象名字时,可以调用getPath方法

    String filename=chooser.getSelectedfile().getPath();

    实验1:测试程序7(7分)

    程序代码如下:

    import javax.swing.*;
      
    /**
     * A frame with a color chooser panel
     */
    public class ColorChooserFrame extends JFrame
    {
       private static final int DEFAULT_WIDTH = 300;
       private static final int DEFAULT_HEIGHT = 200;
      
       public ColorChooserFrame()
       {    
          setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
      
          // 添加颜色选择器面板到框架
      
          ColorChooserPanel panel = new ColorChooserPanel();
          add(panel);
       }
    }

      

    import java.awt.Color;
    import java.awt.Frame;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
      
    import javax.swing.JButton;
    import javax.swing.JColorChooser;
    import javax.swing.JDialog;
    import javax.swing.JPanel;
      
    /**
     * A panel with buttons to pop up three types of color choosers
     */
    public class ColorChooserPanel extends JPanel
    {
       public ColorChooserPanel()
       {
          JButton modalButton = new JButton("Modal");
          modalButton.addActionListener(new ModalListener());
          add(modalButton);
      
          JButton modelessButton = new JButton("Modeless");
          modelessButton.addActionListener(new ModelessListener());
          add(modelessButton);
      
          JButton immediateButton = new JButton("Immediate");
          immediateButton.addActionListener(new ImmediateListener());
          add(immediateButton);
       }
      
       /**
        * This listener pops up a modal color chooser
        */
       private class ModalListener implements ActionListener
       {
          public void actionPerformed(ActionEvent event)
          {
             Color defaultColor = getBackground();
             Color selected = JColorChooser.showDialog(ColorChooserPanel.this, "Set background",
                   defaultColor);
             if (selected != null) setBackground(selected);
          }
       }
      
       /**
        * This listener pops up a modeless color chooser. The panel color is changed when the user
        * clicks the OK button.
        */
       private class ModelessListener implements ActionListener
       {
          private JDialog dialog;
          private JColorChooser chooser;
      
          public ModelessListener()
          {
             chooser = new JColorChooser();
             dialog = JColorChooser.createDialog(ColorChooserPanel.this, "Background Color",
                   false /* not modal */, chooser,
                   event -> setBackground(chooser.getColor()),
                   null /* no Cancel button listener */);
          }
      
          public void actionPerformed(ActionEvent event)
          {
             chooser.setColor(getBackground());
             dialog.setVisible(true);
          }
       }
      
       /**
        * This listener pops up a modeless color chooser. The panel color is changed immediately when
        * the user picks a new color.
        */
       private class ImmediateListener implements ActionListener
       {
          private JDialog dialog;
          private JColorChooser chooser;
      
          public ImmediateListener()
          {
             chooser = new JColorChooser();
             chooser.getSelectionModel().addChangeListener(
                   event -> setBackground(chooser.getColor()));
      
             dialog = new JDialog((Frame) null, false /* not modal */);
             dialog.add(chooser);
             dialog.pack();
          }
      
          public void actionPerformed(ActionEvent event)
          {
             chooser.setColor(getBackground());
             dialog.setVisible(true);
          }
       }
    }

      

    import java.awt.*;
    import javax.swing.*;
      
    /**
     * @version 1.04 2015-06-12
     * @author Cay Horstmann
     */
    public class ColorChooserTest
    {
       public static void main(String[] args)
       {
          EventQueue.invokeLater(() -> {
             JFrame frame = new ColorChooserFrame();
             frame.setTitle("ColorChooserTest");
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.setVisible(true);
          });
       }
    }

      运行结果如下:

    颜色选择器:

    颜色选择器JColorChooser是用于挑选某种颜色的组件。

    1.用颜色选择器显示模式颜色选择对话框

    color selectedColor=new JColorChooser. showDialog(parent, title,initialColor)

    2.用颜色选择器显示无模式颜色选择对话框

    chooser=new JColorChooser()

    实验2:结对编程练习包含以下4部分:(该项作业16周实验课现场检查,并单独评分)

    1)   程序设计思路简述;

    2)   符合编程规范的程序代码;

    3)   程序运行功能界面截图;

    实验总结:(16分)

    这一周继续学习了Swing用户界面组件以及GUI相关组件。

    掌握了GUI布局管理器用法;掌握了Java Swing文本输入组件用途及常用API;掌握了Java Swing选择输入组件用途及常用API。

  • 相关阅读:
    数据库——表操作(5)
    数据库——存储引擎(4)
    数据库——库操作(3)
    数据库——初始mysql语句(2)
    数据库——初识数据库(1)
    并发编程——协程(5)
    并发编程——IO模型(6)
    并发编程——多线程(4)
    并发编程——多进程——multiprocessing开启进程的方式及其属性(3)
    并发编程——多进程——理论(2)
  • 原文地址:https://www.cnblogs.com/dlzyj/p/12013559.html
Copyright © 2011-2022 走看看