Java Swing – JOptionPane showOptionDialog示例

JOptionPaneshowOptionDialog方法是showConfirmDialog,showInputDialog和showMessageDialog的统一。

showOptionDialog返回一个integer ,该integer表示用户选择的Object[]Object[]

注意
如果您想了解更多有关不同showXxxDialog方法的信息,请参阅

  1. Java Swing – JOptionPane showConfirmDialog示例
  2. Java Swing – JOptionPane showInputDialog示例
  3. Java Swing – JOptionPane showMessageDialog示例

1. showConfirmDialog具有不同的数组类型

options array可以设置为您选择的任何类型。

ConfirmDialog1a.java
package com.mkyong.optiondialog;

import javax.swing.*;

public class ConfirmDialog1a {

    public static void main(String[] args) {

        String[] options = {"abc", "def", "ghi", "jkl"};
        //Integer[] options = {1, 3, 5, 7, 9, 11};
        //Double[] options = {3.141, 1.618};
        //Character[] options = {'a', 'b', 'c', 'd'};
        int x = JOptionPane.showOptionDialog(null, "Returns the position of your choice on the array",
                "Click a button",
                JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
        System.out.println(x);

    }
}

输出:

swing-showoptiondialog-2a

单击“ abc”时:

0

单击“ def”时:

1

单击“ ghi”时:

2

单击“ jkl”时:

3

您也可以将数组设置为Object[]

ConfirmDialog1b.java
package com.mkyong.optiondialog;

import javax.swing.JCheckBox;
import javax.swing.JOptionPane;

public class ConfirmDialog1b {

    public static void main(String[] args) {

        JCheckBox check = new JCheckBox("Tick me");
        Object[] options = {'e', 2, 3.14, 4, 5, "TURTLES!", check};
        int x = JOptionPane.showOptionDialog(null, "So many options using Object[]",
                "Don't forget to Tick it!",
                JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[0]);

        if (check.isSelected() && x != -1) {
            System.out.println("Your choice was " + options[x]);
        } else {
            System.out.println(":( no choice");
        }

    }

}

输出:

swing-showoptiondialog-2b

勾选复选框并显示“ TURTLES!”时 点击:

Your choice was TURTLES!

当窗口关闭或用户单击按钮而不勾选复选框时:

:( no choice

2. showConfirmDialog

showConfirmDialog放置在框架中并将图标设置为本地图片文件的示例。

ConfirmDialog2.java
package com.mkyong.optiondialog;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

@SuppressWarnings("serial")
public class ConfirmDialog2 extends JFrame {

    public ConfirmDialog2() {

        getContentPane().setBackground(new Color(238, 232, 170));
        getContentPane().setLayout(null);
        setTitle("Confirm Dialog in Frame");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        setResizable(false);
        setSize(450, 300);

        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        setLocation(dim.width / 2 - this.getWidth() / 2, dim.height / 2 - this.getHeight() / 2);

    }

    public JPanel panel() {

        JPanel panel = new JPanel();
        panel.setBounds(0, 0, 444, 271);
        panel.setBackground(new Color(176, 224, 230));
        getContentPane().add(panel);
        panel.setLayout(null);

        JLabel lblIcon = new JLabel("");
        lblIcon.setBounds(30, 30, 200, 200);
        lblIcon.setIcon(new ImageIcon("src/images/girl200.png"));
        panel.add(lblIcon);

        JLabel lblText2 = new JLabel("Lauren is the 4th daughter!");
        lblText2.setVerticalAlignment(SwingConstants.TOP);
        lblText2.setFont(new Font("Tahoma", Font.ITALIC, 14));
        lblText2.setHorizontalAlignment(SwingConstants.CENTER);
        lblText2.setBounds(240, 130, 175, 100);
        panel.add(lblText2);

        JLabel lblText1 = new JLabel("Yaaaay!");
        lblText1.setHorizontalAlignment(SwingConstants.CENTER);
        lblText1.setFont(new Font("Tahoma", Font.ITALIC, 14));
        lblText1.setBounds(240, 30, 175, 100);
        panel.add(lblText1);

        return panel;

    }

    public static void main(String[] args) {

        ConfirmDialog2 cdframe = new ConfirmDialog2();
        ImageIcon icon = new ImageIcon("src/images/girl64.png");
        String[] options = {"Mary", "Nora", "Anna", "Lauren"};
        int x = JOptionPane.showOptionDialog(cdframe, "Lauren's mom had four kids: Maria, Martha, Margaret...",
                "The missing kid", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, icon, options, options[0]);

        if (x == 3) {
            cdframe.getContentPane().add(cdframe.panel());
            cdframe.repaint();
            cdframe.revalidate();
        } else {
            cdframe.dispose();
            JOptionPane.showMessageDialog(null, "Nooope!");
        }

    }
}

输出:

swing-showoptiondialog-2c

单击Mary,Nora,Anna或X(关闭窗口)时:

swing-showoptiondialog-2d

单击Lauren时:

swing-showoptiondialog-2e

图片来源:https://en.wikipedia.org/wiki/File:Creative-Tail-People-girl.svg

参考文献

  1. 如何制作对话框
  2. JOption窗格类– Java 8 API

翻译自: https://mkyong.com/swing/java-swing-joptionpane-showoptiondialog-example/

  • 6
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
import java.awt.BorderLayout; import java.awt.Container; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import javax.swing.BorderFactory; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.KeyStroke; import javax.swing.ScrollPaneConstants; import javax.swing.SwingConstants; public class JNotePadUI extends JFrame { private JMenuItem menuOpen; private JMenuItem menuSave; private JMenuItem menuSaveAs; private JMenuItem menuClose; private JMenu editMenu; private JMenuItem menuCut; private JMenuItem menuCopy; private JMenuItem menuPaste; private JMenuItem menuAbout; private JTextArea textArea; private JLabel stateBar; private JFileChooser fileChooser; private JPopupMenu popUpMenu; public JNotePadUI() { super("新建文本文件"); setUpUIComponent(); setUpEventListener(); setVisible(true); } private void setUpUIComponent() { setSize(640, 480); // 菜单栏 JMenuBar menuBar = new JMenuBar(); // 设置「文件」菜单 JMenu fileMenu = new JMenu("文件"); menuOpen = new JMenuItem("打开"); // 快捷键设置 menuOpen.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_O, InputEvent.CTRL_MASK)); menuSave = new JMenuItem("保存"); menuSave.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_S, InputEvent.CTRL_MASK)); menuSaveAs = new JMenuItem("另存为"); menuClose = new JMenuItem("关闭"); menuClose.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_Q, InputEvent.CTRL_MASK)); fileMenu.add(menuOpen); fileMenu.addSeparator(); // 分隔线 fileMenu.add(menuSave); fileMenu.add(menuSaveAs); fileMenu.addSeparator(); // 分隔线 fileMenu.add(menuClose); // 设置「编辑」菜单 JMenu editMenu = new JMenu("编辑"); menuCut = new JMenuItem("剪切"); menuCut.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_MASK)); menuCopy = new JMenuItem("复制"); menuCopy.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK)); menuPaste = new JMenuItem("粘贴"); menuPaste.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK)); editMenu.add(menuCut); editMenu.add(menuCopy); editMenu.add(menuPaste); // 设置「关于」菜单 JMenu aboutMenu = new JMenu("关于"); menuAbout = new JMenuItem("关于JNotePad"); aboutMenu.add(menuAbout); menuBar.add(fileMenu); menuBar.add(editMenu); menuBar.add(aboutMenu); setJMenuBar(menuBar); // 文字编辑区域 textArea = new JTextArea(); textArea.setFont(new Font("宋体", Font.PLAIN, 16)); textArea.setLineWrap(true); JScrollPane panel = new JScrollPane(textArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); Container contentPane = getContentPane(); contentPane.add(panel, BorderLayout.CENTER); // 状态栏 stateBar = new JLabel("未修改"); stateBar.setHorizontalAlignment(SwingConstants.LEFT); stateBar.setBorder( BorderFactory.createEtchedBorder()); contentPane.add(stateBar, BorderLayout.SOUTH); popUpMenu = editMenu.getPopupMenu(); fileChooser = new JFileChooser(); } private void setUpEventListener() { // 按下窗口关闭钮事件处理 addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { closeFile(); } } ); // 菜单 - 打开 menuOpen.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { openFile(); } } ); // 菜单 - 保存 menuSave.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { saveFile(); } } ); // 菜单 - 另存为 menuSaveAs.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { saveFileAs(); } } ); // 菜单 - 关闭文件 menuClose.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { closeFile(); } } ); // 菜单 - 剪切 menuCut.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { cut(); } } ); // 菜单 - 复制 menuCopy.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { copy(); } } ); // 菜单 - 粘贴 menuPaste.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { paste(); } } ); // 菜单 - 关于 menuAbout.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { // 显示对话框 JOptionPane.showOptionDialog(null, "程序名称:\n JNotePad \n" + "程序设计:\n \n" + "简介:\n 一个简单的文字编辑器\n" + " 可作为验收Java的实现对象\n" + " 欢迎网友下载研究交流\n\n" + " /", "关于JNotePad", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null); } } ); // 编辑区键盘事件 textArea.addKeyListener( new KeyAdapter() { public void keyTyped(KeyEvent e) { processTextArea(); } } ); // 编辑区鼠标事件 textArea.addMouseListener( new MouseAdapter() { public void mouseReleased(MouseEvent e) { if(e.getButton() == MouseEvent.BUTTON3) popUpMenu.show(editMenu, e.getX(), e.getY()); } public void mouseClicked(MouseEvent e) { if(e.getButton() == MouseEvent.BUTTON1) popUpMenu.setVisible(false); } } ); } private void openFile() { if(isCurrentFileSaved()) { // 文件是否为保存状态 open(); // 打开 } else { // 显示对话框 int option = JOptionPane.showConfirmDialog( null, "文件已修改,是否保存?", "保存文件?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null); switch(option) { // 确认文件保存 case JOptionPane.YES_OPTION: saveFile(); // 保存文件 break; // 放弃文件保存 case JOptionPane.NO_OPTION: open(); break; } } } private boolean isCurrentFileSaved() { if(stateBar.getText().equals("未修改")) { return false; } else { return true; } } private void open() { // fileChooser 是 JFileChooser 的实例 // 显示文件选取的对话框 int option = fileChooser.showDialog(null, null); // 使用者按下确认键 if(option == JFileChooser.APPROVE_OPTION) { try { // 开启选取的文件 BufferedReader buf = new BufferedReader( new FileReader( fileChooser.getSelectedFile())); // 设定文件标题 setTitle(fileChooser.getSelectedFile().toString()); // 清除前一次文件 textArea.setText(""); // 设定状态栏 stateBar.setText("未修改"); // 取得系统相依的换行字符 String lineSeparator = System.getProperty("line.separator"); // 读取文件并附加至文字编辑区 String text; while((text = buf.readLine()) != null) { textArea.append(text); textArea.append(lineSeparator); } buf.close(); } catch(IOException e) { JOptionPane.showMessageDialog(null, e.toString(), "开启文件失败", JOptionPane.ERROR_MESSAGE); } } } private void saveFile() { // 从标题栏取得文件名称 File file = new File(getTitle()); // 若指定的文件不存在 if(!file.exists()) { // 执行另存为 saveFileAs(); } else { try { // 开启指定的文件 BufferedWriter buf = new BufferedWriter( new FileWriter(file)); // 将文字编辑区的文字写入文件 buf.write(textArea.getText()); buf.close(); // 设定状态栏为未修改 stateBar.setText("未修改"); } catch(IOException e) { JOptionPane.showMessageDialog(null, e.toString(), "写入文件失败", JOptionPane.ERROR_MESSAGE); } } } private void saveFileAs() { // 显示文件对话框 int option = fileChooser.showSaveDialog(null); // 如果确认选取文件 if(option == JFileChooser.APPROVE_OPTION) { // 取得选择的文件 File file = fileChooser.getSelectedFile(); // 在标题栏上设定文件名称 setTitle(file.toString()); try { // 建立文件 file.createNewFile(); // 进行文件保存 saveFile(); } catch(IOException e) { JOptionPane.showMessageDialog(null, e.toString(), "无法建立新文件", JOptionPane.ERROR_MESSAGE); } } } private void closeFile() { // 是否已保存文件 if(isCurrentFileSaved()) { // 释放窗口资源,而后关闭程序 dispose(); } else { int option = JOptionPane.showConfirmDialog( null, "文件已修改,是否保存?", "保存文件?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null); switch(option) { case JOptionPane.YES_OPTION: saveFile(); break; case JOptionPane.NO_OPTION: dispose(); } } } private void cut() { textArea.cut(); stateBar.setText("已修改"); popUpMenu.setVisible(false); } private void copy() { textArea.copy(); popUpMenu.setVisible(false); } private void paste() { textArea.paste(); stateBar.setText("已修改"); popUpMenu.setVisible(false); } private void processTextArea() { stateBar.setText("已修改"); } public static void main(String[] args) { new JNotePadUI(); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值