目录

1 Swing概述

2 Swing基本组件的用法

2.1 Swing组件层次

2.2 AWT组件的Swing实现

2.3 为组件设置边框

2.4 使用JToolBar创建工具条

2.5 JColorChooser和JFileChooser

JColorChooser

JFileChooser

2.6 JOptionPane

基本概述

消息对话框:

确认对话框:

输入对话框:

选项对话框:

1 Swing概述

        Swing是完完全全由Java实现的,不再依赖本地平台的GUI,因此可以在所有平台上都保持相同的界面外观,独立于本地平台的Swing组件被称为轻量级组件;而依赖于本地平台的AWT组件被称为重量级组件

        由于Swing的所有组件完全采用Java实现,不再调用本地平台的GUI,所有导致Swing图形界面的显示速度要比AWT图形界面的显示速度慢一些,但相对于快速发展的硬件设施而言,这种微小的速度差距并无大碍。

使用Swing的优势:

        1.Swing组件不再依赖于本地平台的GUI,无需采用各种平台的GUI交集,因此Swing提供了大量图形界面组件,远超出了AWT提供的图形界面组件集;

        2.Swing组件不再依赖于本地平台GUI,因此不会产生与平台相关的bug;

        3.Swing组件在各个平台上运行时可以保证相同的图形界面外观。

Swing的特征:

        1.Swing组件采用MVC(Model-View-Controller,即模型-视图-控制器)设计模式:

        模型(Model):用于维护组建的各种状态;

        视图(View):是组件的可视化表现;

        控制器(Controller):用于控制对于各种事务、组件做出响应。

        当模型发生改变时,他会通知所有依赖它的视图,视图会根据模型数据来更新自己。Swing使用UI代理来包装视图和控制器,还有一个模型对象来维护该组件的状态。

        例如,按钮JButton有一个维护其状态信息的模型ButtonModel对象。Swing组件的模型是自动设置的,因此一般都使用JButton,而无需关心ButtonModel对象。

        2.Swing在不同平台上表现一致,并且有能力提供本地平台不支持的显示外观。由于Swing采用MVC模式来维护各组件,所以当组件的外观被改变时,对组件的状态信息没有影响。音系,Swing可以使用插拔式外观感觉(Pluggable Look And Feel  :  PLAF) 来控制组件外观,使得Swing图形界面在同一个平台上运行时能拥有不同的外观,用户可以选择自己喜欢的外观。相比之下,AWT图形界面中,由于控制组件外观的对等类与具体平台相关,因此AWT组件总是具有与本地平台相关的外观。

2 Swing基本组件的用法

2.1 Swing组件层次

        大部分Swing组件都是JComponent抽象类的直接或间接子类(并不是全部的Swing组件),JComponent类定义了所有子类组建的通用方式,JComponent类是AWT里java.awt.Container类的子类,这也是AWT和Swing的联系之一。绝大部分Swing组件类继承了Container类,所以Swing组件都可作为容器使用(JFrame继承了Frame类)。

Swing组件和AWT组件的对应关系:

        大部分情况下,只需要在AWT组件的名字前面加一个J,就可以得到其对应的Swing组件名称,但有几个例外:

        1.JcomboBox:对应AWT里的Choice组件,但比Choice组件丰富;

        2.JFileChooser:对应AWT里的FileDialog组件;

        3.JScrollBar:对应于AWT里的Scrollbar组件,注意两个组件类名中b字母的大小写;

        4.JCheckBox:对应于AWT里的Checkbox组件,大小写区别;

        5.JCheckBoxMenuItem:对应AWT里的CheckboxMenuItem组件,大小写。

Swing组件按照功能分类:

        1.顶层容器:JFrame,JApplet,JDialog和JWindow。

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

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

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

        5.不可编辑信息的显示组件:向用户显示能够编辑的格式化信息的组件,如JTable,JTextArea和JTextField等。

        6.特殊对话框组件:可以直接产生特殊对话框的组件,如JColorChooser和JFileChooser等。

2.2 AWT组件的Swing实现

        Swing为除Canvas之外的所有AWT组件提供了相应的实现,Swing组件比AWT组件的功能更加强大。相对于AWT组件,Swing组件具有如下4个额外的功能:

        1.可以为Swing组件设置提示信息。使用setToolTipText()方法,为组件设置对用户有帮助的提示信息。

        2.很多Swing组件如按钮、标签、菜单项等,除使用文字外,还可以使用图标修饰自己。为了允许在Swing组件中使用图标,Swing为Icon接口提供了一个实现类:ImageIcon,该实现类代表一个图像图标。

        3.支持插拔式的外观风格。每个JComponent对象都有一个相应的ComponentUI对象,为它完成所有的绘画、事件处理、决定尺寸大小等工作。ComponentUI对象依赖当前使用的PLAF,使用UIManager.setLookAndFeel()方法可以改变图形界面的外观风格。

        4.支持设置边框。Swing组件可以设置一个或多个边框。Swing中提供了各式各样的边框供用户使用,也能建立组合边框或自己设计边框。一种空白边框可以用于增大组件,同时协调布局管理器中的组件进行合理的布局。

        每个Swing组件都有一个对应的UI类,例如JButton组件就有一个对应的ButtonUI类来作为UI代理。每个Swing组建的UI代理的类名总是将该Swing组件类名的J去掉,然后在后面添加UI后缀。UI代理类通常是一个抽象基类,不同的PLAF会有不同的UI代理实现类。Swing类库中包含了几套UI代理,分别放在不同的包下,每套UI代理都几乎包含了所有Swing组件的ComponentUI实现,每套这样的实现都被称为一种PLAF实现。

        如果需要改变程序的外观风格,可以使用如下代码:

//容器
JFrame jf=new JFrame();
try{
    //设置外观风格
    UIManager.setLookAndFeel("com.sun.java.swing.plaf.windowsLookAndFeel");
    //刷新jf容器及其内部组件的外观
    SwingUtilities.updateComponentTreeUI(jf);
}catch(Exception e){
    e.printStackTrace();
}

案例:

        下面使用Swing组件完成下图效果:

public class SwingComponentDemo {
    JFrame f = new JFrame("测试Swing基本组件");

    //声明菜单相关的组件
    JMenuBar menuBar = new JMenuBar();

    JMenu fileMenue = new JMenu("文件");
    JMenu editMenue = new JMenu("编辑");

    JMenuItem auto = new JMenuItem("自动换行");
    JMenuItem copy = new JMenuItem("复制",new ImageIcon("swing\\img\\component\\copy.png"));
    JMenuItem paste = new JMenuItem("粘贴",new ImageIcon("swing\\img\\component\\paste.png"));

    JMenu formatMenu = new JMenu("格式");
    JMenuItem comment = new JMenuItem("注释");
    JMenuItem cancelComment = new JMenuItem("取消注释");

    //声明文本域
    JTextArea ta = new JTextArea(8, 20);

    String[] colors= {"红色","绿色","蓝色"};
    //声明列表框
    JList<String> colorList = new JList<String>(colors);

    //声明选择相关组件
    JComboBox<String> colorSelect = new JComboBox<String>();

    ButtonGroup bg = new ButtonGroup();//按钮组,实现单选效果
    JRadioButton male = new JRadioButton("男", false);
    JRadioButton female = new JRadioButton("女", true);

    JCheckBox isMarried = new JCheckBox("是否已婚?", true);

    //声明底部
    JTextField tf = new JTextField(40);
    JButton ok = new JButton("确定",new ImageIcon("swing\\img\\component\\ok.png"));

    //声明右键菜单
    JPopupMenu jPopupMenu = new JPopupMenu();

    ButtonGroup poupButtonBg = new ButtonGroup();

    JRadioButtonMenuItem metalItem = new JRadioButtonMenuItem("Metal 风格");
    JRadioButtonMenuItem nimbusItem = new JRadioButtonMenuItem("Nimbus 风格");
    JRadioButtonMenuItem windowsItem = new JRadioButtonMenuItem("Windows 风格",true);
    JRadioButtonMenuItem windowsClassicItem = new JRadioButtonMenuItem("Windows 经典风格");
    JRadioButtonMenuItem motifItem = new JRadioButtonMenuItem("Motif 风格");


    //初始化界面
    public void init() {
        //组装视图

        //组装底部
        JPanel bottomPanel = new JPanel();
        bottomPanel.add(tf);
        bottomPanel.add(ok);

        f.add(bottomPanel, BorderLayout.SOUTH);

        //组装选择相关的组件
        JPanel selectPanel = new JPanel();

        colorSelect.addItem("红色");
        colorSelect.addItem("绿色");
        colorSelect.addItem("蓝色");

        selectPanel.add(colorSelect);
        bg.add(male);
        bg.add(female);
        selectPanel.add(male);
        selectPanel.add(female);

        selectPanel.add(isMarried);

        //组装文本域和选择相关组件
        Box topLeft = Box.createVerticalBox();
        topLeft.add(ta);
        topLeft.add(selectPanel);

        //组装顶部
        Box top = Box.createHorizontalBox();
        top.add(topLeft);
        top.add(colorList);

        f.add(top);

        //组装顶部菜单
        formatMenu.add(comment);
        formatMenu.add(cancelComment);

        editMenue.add(auto);
        editMenue.addSeparator();
        editMenue.add(copy);
        editMenue.add(paste);
        editMenue.addSeparator();
        editMenue.add(formatMenu);

        menuBar.add(fileMenue);
        menuBar.add(editMenue);

        f.setJMenuBar(menuBar);

        //组装右键菜单
        poupButtonBg.add(metalItem);
        poupButtonBg.add(nimbusItem);
        poupButtonBg.add(windowsItem);
        poupButtonBg.add(windowsClassicItem);
        poupButtonBg.add(motifItem);

        ActionListener listener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //当前选择的是哪一个风格
                String actionCommand = e.getActionCommand();
                try {
                    changeFlavor(actionCommand);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        };

        metalItem.addActionListener(listener);
        nimbusItem.addActionListener(listener);
        windowsItem.addActionListener(listener);
        windowsClassicItem.addActionListener(listener);
        motifItem.addActionListener(listener);

        jPopupMenu.add(metalItem);
        jPopupMenu.add(nimbusItem);
        jPopupMenu.add(windowsItem);
        jPopupMenu.add(windowsClassicItem);
        jPopupMenu.add(motifItem);

        //不需要再监听鼠标事件了
        ta.setComponentPopupMenu(jPopupMenu);


        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭程序
        f.pack();
        f.setVisible(true);

    }

    public static void main(String[] args) {
        new SwingComponentDemo().init();
    }


    //定义一个方法,用于改变界面风格
    private void changeFlavor(String command) throws Exception {
        switch (command) {
            case "Metal 风格":
                UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
                break;
            case "Nimbus 风格":
                UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
                break;
            case "Windows 风格":
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                break;
            case "Windows 经典风格":
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel");
                break;
            case "Motif 风格":
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
                break;
        }

        //刷新组件的外观
        SwingUtilities.updateComponentTreeUI(f.getContentPane());
        SwingUtilities.updateComponentTreeUI(menuBar);
        SwingUtilities.updateComponentTreeUI(jPopupMenu);
    }

}


 2.3 为组件设置边框

        很多情况下,我们常常喜欢给不同的组件设置边框,从而让界面的层次感更明显,Swing中提供了Border对象代表一个边框,下图是Border的一个继承体系图:

 特殊的Border:

        1.TitledBorder:它的作用并不是直接为其他组件添加边框,而是为其他边框设置标题,创建该类的对象时,需要传入一个其他的Border对象;

        2.CompoundBorder:用来组合其他两个边框,创建该类的对象时,需要传入其他两个Border对象,一个作为内边框,一个作为外边框。

给组件设置边框步骤:

        1.使用BorderFactory或者XxxBorder创建Border的实例对象;

        2.调用Swing组件的setBorder(Border b)方法为组件设置边框;

案例:

        使用Border实现下图效果:

 演示代码:

public class BorderTest {

    JFrame jf  = new JFrame("测试边框");

    public void init(){
        //组装视图
        //1.JFrame的布局修改为GridLayout
        jf.setLayout(new GridLayout(2,4));

        //2.往网格中填充不同的JPanel组件,并且设置边框和内容

        //创建BevelBorder
        Border bevelBorder = BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.RED, Color.GREEN, Color.BLUE, Color.GRAY);
        jf.add(getJPanelWithBorder(bevelBorder,"BevelBorder"));

        //创建LineBorder
        Border lineBorder = BorderFactory.createLineBorder(Color.ORANGE, 10);
        jf.add(getJPanelWithBorder(lineBorder,"LineBorder"));

        //创建EmptyBorder
        Border emptyBorder = BorderFactory.createEmptyBorder(10, 5, 20, 10);
        jf.add(getJPanelWithBorder(emptyBorder,"EmptyBorder"));

        //创建EchtedBorder
        Border etchedBorder = BorderFactory.createEtchedBorder(EtchedBorder.RAISED, Color.RED, Color.GREEN);
        jf.add(getJPanelWithBorder(etchedBorder,"EtchedBorder"));

        //创建TitledBorder
        TitledBorder titledBorder = new TitledBorder(new LineBorder(Color.ORANGE,10),"测试标题",TitledBorder.LEFT,TitledBorder.BOTTOM,new Font("StSong",Font.BOLD,18),Color.BLUE);
        jf.add(getJPanelWithBorder(titledBorder,"TitledBorder"));

        //创建MatteBorder
        MatteBorder matteBorder = new MatteBorder(10, 5, 20, 10, Color.GREEN);
        jf.add(getJPanelWithBorder(matteBorder,"MatteBorder"));

        //创建CompoundBorder
        CompoundBorder compoundBorder = new CompoundBorder( new LineBorder(Color.RED, 10),titledBorder);
        jf.add(getJPanelWithBorder(compoundBorder,"CompoundBorder"));

        //3.设置窗口最佳大小、设置窗口可见,处理关闭操作
        jf.pack();
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    public JPanel getJPanelWithBorder(Border border,String content){
        JPanel jPanel = new JPanel();
        jPanel.add(new JLabel(content));

        //设置边框
        jPanel.setBorder(border);

        return jPanel;
    }

    public static void main(String[] args) {
        new BorderTest().init();
    }
}

2.4 使用JToolBar创建工具条

        Swing提供了JToolBar类来创建工具条,并且可以往JToolBar中添加多个工具按钮。

JToolBar API:

JToolBar(String name,

int orientation)

创建一个名字为name,方向为orientation的工具条对象
JButton add(Action a)通过Action对象为ToolBar工具条添加对应的工具按钮
addSeparator(Dimension size)向工具条中添加指定大小的分隔符
setFloatable(boolean b)设定工具条是否可以被拖动
setMargin(Insets m)设置工具条与工具按钮的边距
setOrientation(int o)设置工具条的方向

案例:

        使用JToolBar组件完成下图效果:

代码演示: 

public class JToolBarTest {

    JFrame jf = new JFrame("测试工具条");
    JTextArea jta = new JTextArea(6,35);

    //声明工具条相关内容

    JToolBar jToolBar = new JToolBar("播放工具条",SwingConstants.HORIZONTAL);

    //创建3个Action对象
    //传递的参数,name和icon,最终在添加到工具条中时,会被拿出来作为按钮的名称和图标
    Action pre = new AbstractAction("上一曲",new ImageIcon("E:\\GUISwing\\img\\component\\上一曲16.png")) {
        @Override
        public void actionPerformed(ActionEvent e) {
            jta.append("上一曲.\n");
        }
    };

    Action pause = new AbstractAction("暂停",new ImageIcon("E:\\GUISwing\\img\\component\\暂停16.png")) {
        @Override
        public void actionPerformed(ActionEvent e) {
            jta.append("暂停播放.\n");
        }
    };

    Action next = new AbstractAction("下一曲",new ImageIcon("E:\\GUISwing\\img\\component\\下一曲16.png")) {
        @Override
        public void actionPerformed(ActionEvent e) {
            jta.append("下一曲.\n");
        }
    };


    public void init(){
        //组装视图

        //通过Action对象来创建JButton

        JButton preBtn = new JButton(pre);
        JButton pauseBtn = new JButton(pause);
        JButton nextBtn = new JButton(next);


        /*jToolBar.add(pre);
        jToolBar.addSeparator();
        jToolBar.add(pause);
        jToolBar.addSeparator();
        jToolBar.add(next);*/

        jToolBar.add(preBtn);
        jToolBar.addSeparator();
        jToolBar.add(pauseBtn);
        jToolBar.addSeparator();
        jToolBar.add(nextBtn);

        //让工具条可以拖动
        jToolBar.setFloatable(true);

        jf.add(jToolBar,BorderLayout.NORTH);

        //文本框默认不支持滚动条

        //把一个组件设置到JScrollPane中,那么该组件就支持滚动条了

        JScrollPane jScrollPane = new JScrollPane(jta);


        jf.add(jScrollPane);

        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.pack();
        jf.setVisible(true);
    }

    public static void main(String[] args) {
        new JToolBarTest().init();
    }
}

2.5 JColorChooser和JFileChooser

        Swing提供了JColorChooser和JFileChooser这两种对话框,可以很方便的完成颜色的选择和本地文件的选择。

JColorChooser

        JColorChooser用于创建颜色选择器对话框,该类的用法非常简单,只需要调用它的静态方法就可以快速生成一个颜色选择对话框:

public static Color showDialog(Component component,String title,Color initialColor)

/*       

        参数:

                Component:指定当前对话框的父组件

                title:当前对话框的名称

                initialColor:指定默认选中的颜色

        返回值:

                返回用户选中的颜色

*/

案例: 

        使用颜色选择器,完成下图功能:

                点击按钮,改变文本域的背景色

代码如下: 

public class JColorChooserDemo {

    JFrame jFrame = new JFrame("测试颜色选择器");

    JTextArea jta = new JTextArea("我爱中华",6,30);

    //声明按钮
    JButton btn = new JButton(new AbstractAction("改变文本框背景颜色") {
        @Override
        public void actionPerformed(ActionEvent e) {
            //弹出一个颜色选择器,
            Color result = JColorChooser.showDialog(jFrame, "颜色选择器", Color.white);

            //修改文本框背景
            jta.setBackground(result);
        }
    });



    public void init(){

        //组装视图
        jFrame.add(jta);

        jFrame.add(btn,BorderLayout.SOUTH);


        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.pack();
        jFrame.setVisible(true);
    }

    public static void main(String[] args) {
        new JColorChooserDemo().init();
    }

}

JFileChooser

        JFileChooser的功能与AWT中的FileDialog基本相同,也是用于生成“打开文件”、“保存文件”对话框。与FileDialog不同的是,JFileChooser无需依赖本地平台的GUI,它完全由Java实现,在所有平台上具有完全相同的行为,并可以在所有平台上具有相同的外观。

JFileChooser使用步骤:

        1.创建JfileChooser对象:

JFileChooser chooser=new JFileChooser("D:\\a");

        2. 调用JFileChooser的一系列可选方法,进行初始化:

setSelectedFile(File file)或setSelectedFiles(File[ ] selectedFiles);//设定默认选中的文件

setMultiSelectionEnabled(boolean b);设置是否允许多选,默认是单选

setFileSelectionMode(int mode);设置可选内容。默认只能选择文件 

         3.打开文件对话框

showOpenDialog(Component parent);打开文件加载对话框,并指定父组件

showSaveDialog(Component parent);打开文件保存对话框,并指定父组件

        4.获取用户选择的结果

File getSelectedFile();获取用户选择的一个文件

File[ ] getSelectedFiles();获取用户选择的多个文件 

 案例:

        使用JFileChooser完成打开和保存文件:

代码如下:

public class JFileChooserDemo {

    //创建窗口对象
    JFrame jf = new JFrame("测试JFileChooser");

    //创建菜单条
    JMenuBar jmb = new JMenuBar();
    //创建菜单
    JMenu jMenu = new JMenu("文件");


    JMenuItem open = new JMenuItem(new AbstractAction("打开") {
        @Override
        public void actionPerformed(ActionEvent e) {
            //显示一个文件选择器
            JFileChooser fileChooser = new JFileChooser(".");
            fileChooser.showOpenDialog(jf);

            //获取用户选择的文件
            File file = fileChooser.getSelectedFile();

            //进行显示
            try {
                image = ImageIO.read(file);
                drawArea.repaint();
            } catch (IOException ex) {
                ex.printStackTrace();
            }

        }
    });

    JMenuItem save = new JMenuItem(new AbstractAction("另存为") {
        @Override
        public void actionPerformed(ActionEvent e) {
            //显示一个文件选择器
            JFileChooser fileChooser = new JFileChooser(".");
            fileChooser.showSaveDialog(jf);

            //获取用户选择的保存文件路径
            File file = fileChooser.getSelectedFile();

            try {
                ImageIO.write(image,"jpeg",file);
            } catch (IOException ex) {
                ex.printStackTrace();
            }

        }
    });



    BufferedImage image;

    //swing提供的组件,都使用了图像缓冲区技术
    private class MyCanvas extends JPanel{
        @Override
        public void paint(Graphics g) {
            //把图片绘制到组件上即可
            g.drawImage(image,0,0,null);
        }
    }

    MyCanvas drawArea = new MyCanvas();


    public void init(){
        //组装视图
        jMenu.add(open);
        jMenu.add(save);

        jmb.add(jMenu);

        jf.setJMenuBar(jmb);

        drawArea.setPreferredSize(new Dimension(740,500));
        jf.add(drawArea);

        //显示jf
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.pack();
        jf.setVisible(true);
    }

    public static void main(String[] args) {
        new JFileChooserDemo().init();
    }

}

2.6 JOptionPane

基本概述

        通过JOptionPane可以非常方便地创建一些简单的对话框,Swing已经为这些对话框添加了相应的组件,无需程序员手动添加组件。JOptionPane提供了如下4个方法来创建对话框。

showMessageDialog/showInternalMessageDialog

消息对话框,告知用户某事已发生,用户只能单击“确定”按钮。

showConfirmDialog/showInternalConfirmDialog确认对话框,向用户确定某个问题,用户可选yes,no-cancel等选项,该方法返回用户单击了哪个按钮
showInputDialog/showInternalInputDialog输入对话框,提示输入某些信息。该方法返回用户输入的字符串
showOptionDialog/showInternalOptionDialog自定义选项对话框,允许使用自定义选项

上述方法都有很多重载形式,选择其中一种最全的形式,参数解释如下:

showXxxDialog(Component parentComponent,Object message,String title,int optionType,int messageType,Icon icon,Object[] options,Object initialValue)

参数解释:

parentComponent:当前对话框的父组件

message:对话框上显示的信息,可以是字符串、组件、图片等

title:当前对话框标题

optionType:当前对话框上显示的按钮类型:DEFAULT_OPTION、YES_NO_OPTION、YES_NO_CANCEL_OPTION、OK_CANCEL_OPTION

messageType:当前对话框的类型:ERROR_MESSAGE、INFORMATION_MESSAGE、WARNING_MESSAGE、QUESTION_MESSAGE、PLAIN_MESSAGE

icon:当前对话框左上角图标

options:自定义下拉列表的选项

initialValue:自定义选项中的默认选中项

 下面演示四种对话框:


消息对话框:

public class MessageDialogTest {


    JFrame jf = new JFrame("测试消息对话框");

    JTextArea jta = new JTextArea(6, 30);

    //声明按钮
    JButton btn = new JButton(new AbstractAction("弹出消息对话框") {
        @Override
        public void actionPerformed(ActionEvent e) {
            //弹出一个消息对话框,并且显示  文本域中输入的内容
            String text = jta.getText();

            //参数:int messageType  指定消息对话框的类型: 错误消息,警告消息,问题消息...
            //JOptionPane.showMessageDialog(jf,text,"消息对话框",JOptionPane.ERROR_MESSAGE);
            //JOptionPane.showMessageDialog(jf,text,"消息对话框",JOptionPane.INFORMATION_MESSAGE);
            //JOptionPane.showMessageDialog(jf,text,"消息对话框",JOptionPane.WARNING_MESSAGE);
            //JOptionPane.showMessageDialog(jf,text,"消息对话框",JOptionPane.QUESTION_MESSAGE);
            //JOptionPane.showMessageDialog(jf,text,"消息对话框",JOptionPane.PLAIN_MESSAGE);

            JOptionPane.showMessageDialog(jf,text,"消息对话框",JOptionPane.WARNING_MESSAGE,new ImageIcon("E:\\GUISwing\\img\\component\\female.png"));

        }
    });

    public void init(){
        //组装视图
        jf.add(jta);
        jf.add(btn,BorderLayout.SOUTH);

        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.pack();
        jf.setVisible(true);
    }

    public static void main(String[] args) {
        new MessageDialogTest().init();
    }

}

确认对话框:

public class ConfirmDialogTest {
    JFrame jf = new JFrame("测试确认对话框");

    JTextArea jta = new JTextArea(6, 30);

    JButton btn = new JButton(new AbstractAction("弹出确认对话框") {

        @Override
        public void actionPerformed(ActionEvent e) {
            //TODO 弹出确认对话框
            String text = jta.getText();
            jta.append("\n");
            //int result = JOptionPane.showConfirmDialog(jf, text, "确认对话框", JOptionPane.DEFAULT_OPTION);
            //int result = JOptionPane.showConfirmDialog(jf, text, "确认对话框", JOptionPane.YES_NO_OPTION);
            int result = JOptionPane.showConfirmDialog(jf, text, "确认对话框", JOptionPane.YES_NO_CANCEL_OPTION);
            //int result = JOptionPane.showConfirmDialog(jf, text, "确认对话框", JOptionPane.OK_CANCEL_OPTION);
            if (result == JOptionPane.YES_OPTION){
                jta.append("用户点击了 是 按钮\n");
            }

            if (result == JOptionPane.NO_OPTION){
                jta.append("用户点击了 否 按钮\n");
            }

            /*if (result == JOptionPane.OK_OPTION){
                jta.append("用户点击了 确认 按钮\n");
            }*/

            if (result == JOptionPane.CANCEL_OPTION){
                jta.append("用户点击了 取消 按钮\n");
            }
        }
    });

    public void init(){
        jf.add(jta);
        jf.add(btn, BorderLayout.SOUTH);

        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.pack();
        jf.setVisible(true);
    }

    public static void main(String[] args) {
        new ConfirmDialogTest().init();
    }

}

输入对话框:

public class InputDialogTest {
    JFrame jf = new JFrame("测试输入对话框");

    JTextArea jta = new JTextArea(6, 30);

    JButton btn = new JButton(new AbstractAction("弹出输入对话框") {

        @Override
        public void actionPerformed(ActionEvent e) {
            //弹出输入对话框
            String result = JOptionPane.showInputDialog(jf, "请填写您的银行账号:", "输入对话框", JOptionPane.INFORMATION_MESSAGE);
            jta.append(result);
        }
    });

    public void init(){
        jf.add(jta);
        jf.add(btn, BorderLayout.SOUTH);

        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.pack();
        jf.setVisible(true);
    }

    public static void main(String[] args) {
        new InputDialogTest().init();
    }

}

选项对话框:

public class OptionDialogTest {

    JFrame jf = new JFrame("测试选项对话框");

    JTextArea jta = new JTextArea(6, 30);

    JButton btn = new JButton(new AbstractAction("弹出选项对话框") {

        @Override
        public void actionPerformed(ActionEvent e) {
            //弹出选项对话框
            int result = JOptionPane.showOptionDialog(jf, "请选择你的登录账号", "选项对话框", JOptionPane.DEFAULT_OPTION,
                    JOptionPane.INFORMATION_MESSAGE, null, new String[]{"大号", "中号", "小号"}, "中号");

            switch (result){
                case 0:
                    jta.setText("用户选择了大号");
                    break;
                case 1:
                    jta.setText("用户选择了中号");
                    break;
                case 2:
                    jta.setText("用户选择了小号");
                    break;
            }

        }
    });

    public void init(){
        jf.add(jta);
        jf.add(btn, BorderLayout.SOUTH);

        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.pack();
        jf.setVisible(true);
    }

    public static void main(String[] args) {
        new OptionDialogTest().init();
    }

}

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐