使用showOptionDialog显示多项选择框

-----------------siwuxie095

   

   

   

   

   

   

   

工程名:TestJOptionPane

包名:com.siwuxie095.showdialog

类名:TestOptionDialog.java

   

   

工程结构目录如下:

   

   

   

   

   

代码:

   

package com.siwuxie095.showdialog;

   

import java.awt.BorderLayout;

import java.awt.EventQueue;

   

import javax.swing.JFrame;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.UIManager;

import javax.swing.UnsupportedLookAndFeelException;

import javax.swing.border.EmptyBorder;

   

import com.sun.java.swing.plaf.windows.WindowsLookAndFeel;

import com.sun.org.apache.xerces.internal.impl.xs.SchemaSymbols;

   

import javax.swing.JButton;

import java.awt.event.MouseAdapter;

import java.awt.event.MouseEvent;

   

public class TestOptionDialog extends JFrame {

   

private JPanel contentPane;

   

/**

* Launch the application.

*/

public static void main(String[] args) {

EventQueue.invokeLater(new Runnable() {

public void run() {

try {

TestOptionDialog frame = new TestOptionDialog();

frame.setVisible(true);

} catch (Exception e) {

e.printStackTrace();

}

}

});

}

   

/**

* Create the frame.

*/

public TestOptionDialog() {

 

try {

UIManager.setLookAndFeel(new WindowsLookAndFeel());

} catch (UnsupportedLookAndFeelException e) {

e.printStackTrace();

}

 

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setBounds(100, 100, 450, 300);

contentPane = new JPanel();

contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));

contentPane.setLayout(new BorderLayout(0, 0));

setContentPane(contentPane);

 

JButton btnshowoptiondialog = new JButton("显示多项选择框(showOptionDialog)");

 

// 按钮 添加鼠标点击事件

btnshowoptiondialog.addMouseListener(new MouseAdapter() {

@Override

public void mouseClicked(MouseEvent e) {

 

/**

* 直接通过静态方法调用

* 需要指定父级窗体,信息,标题,选项类型,

* 信息类型,图标,可选值(数组),初始值(默认输入值)

* 返回值是 int 类型,创建以接收返回值

* 如果返回 0,对应 "方案1" ...

* 如果返回 CLOSED_OPTION,则该窗口关闭,没有选择

* 没有关闭多项选择框时,后面的主窗体是完全无法操作的(即 阻塞)

*/

String options[]={"方案1","方案2","方案3"};

int value=JOptionPane.showOptionDialog(TestOptionDialog.this, "选择一个方案:",

"方案", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null,

options, "方案1");

 

if (value!=JOptionPane.CLOSED_OPTION) {

switch (value) {

case 0:System.out.println("你选择了 方案1");break;

case 1:System.out.println("你选择了 方案2");break;

case 2:System.out.println("你选择了 方案3");break;

default:

break;

}

}

 

 

}

});

btnshowoptiondialog.setFocusable(false);

contentPane.add(btnshowoptiondialog, BorderLayout.NORTH);

}

   

}

   

   

   

将窗体 JFrame 的 LookAndFeel 设定为 Windows

   

   

在根面板 contentPane 的上方添加一个 JButton,

将其 focusable 属性设为 false

   

   

为 JButton 添加 mouseClicked 事件,点击 按钮 弹出多项选择框

   

   

   

运行程序:

   

   

   

   

   

   

   

   

【made by siwuxie095】

原文地址:https://www.cnblogs.com/siwuxie095/p/6675500.html