Java 中 JOptionPane类的使用

Java中JOptionPane类的静态方法

public static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType)

可以得到一个确认对话框。

其中参数parentComponent指定确认对话框所在的位置,确认对话框在参数parentComponent的正前方显示出来,message指定对话框上显示的信息,title指定对话框的标题,optionType可取的有效值是JOptionPane中的类常量:

  • YES_NOOPTION
  • YES_NO_CANCEL_OPTION
  • OK_CANCEL_OPTION
  • WARNING_MESSAGE
  • NO_OPTION 等等

这些值可以给出确认对话框的外观,例如,取值JOptionPane.YES_NO_OPTION时,确认对话框的外观上会有YesNo两个按钮。

如以下程序就是在frame窗口的正前方显示确认对话框

package src;
import javax.swing.*;

class JOPTIONPANE{
    public static void main(String[] args){
        JFrame frame;
        
        frame = new JFrame();
        frame.setBounds(400, 100, 500, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        
        JOptionPane.showConfirmDialog(frame, "Hello World!", "hello", JOptionPane.CLOSED_OPTION);
    }
}

在这里插入图片描述如果将代码中的frame改为null,那么就是在屏幕的正中央显示对话框

JOptionPane.showMessageDialog(null, "Hello World!", "hello", JOptionPane.CLOSED_OPTION);

showMessageDialog方法

如果仅仅输出一串信息可以使用方法中的showMessageDialog方法,以下就可以在屏幕上显示出一个输出信息的对话框

JOptionPane.showMessageDialog(null, "账号或密码错误", "账号或密码错误", JOptionPane.WARNING_MESSAGE);

在这里插入图片描述

showInputDialog方法

showInputDialog方法可以显示出一个输入框,可以用一个字符串来接收输入框中的内容。
如以下代码可以使用showInputDialog方法来创建一个带输入框的确认对话框。

public static void main(String[] args){
		//showInputDialog方法
        String Massage = JOptionPane.showInputDialog(null, "输入: ");
        JOptionPane.showMessageDialog(null, "Massage");
    }

在这里插入图片描述

下面给出一些常用的确认对话框的外观:

JOptionPane.showConfirmDialog(null, "Hello World!", "hello", JOptionPane.CANCEL_OPTION);

在这里插入图片描述

JOptionPane.showConfirmDialog(null, "Hello World!", "hello", JOptionPane.CLOSED_OPTION);

在这里插入图片描述

JOptionPane.showMessageDialog(null, "Hello World!", "hello", JOptionPane.DEFAULT_OPTION);

在这里插入图片描述

JOptionPane.showMessageDialog(null, "Hello World!", "hello", JOptionPane.ERROR_MESSAGE);

在这里插入图片描述

JOptionPane.showMessageDialog(null, "Hello World!", "hello", JOptionPane.INFORMATION_MESSAGE);

在这里插入图片描述

JOptionPane.showConfirmDialog(null, "Hello World!", "hello", JOptionPane.YES_NO_CANCEL_OPTION);

在这里插入图片描述

JOptionPane.showConfirmDialog(null, "Hello World!", "hello", JOptionPane.YES_NO_OPTION);

在这里插入图片描述

发布了463 篇原创文章 · 获赞 122 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq_41505957/article/details/103428836