Java Swing - Exemple avec JOptionPane showConfirmDialog

Java Swing - Exemple de JOptionPane showConfirmDialog

Ceci est un examen de la méthodeshowConfirmDialog() de la classeJOptionPane. Cette méthode est un moyen rapide et facile d'obtenir des commentaires de l'utilisateur en posant une question de confirmation, comme oui / non / annuler. LesshowConfirmDialog() peuvent être appelés en utilisant les combinaisons de paramètres suivantes:

Component, Object
Component, Object, String, int
Component, Object, String, int, int
Component, Object, String, int, int, Icon
  1. Composant - Le premier paramètre est un composant qui détermine le cadre dans lequel la boîte de dialogue est affichée; si nul, ou si leparentComponent n'a pas de trame, une trame par défaut est utilisée.

  2. Object - Le deuxième paramètre peut être n'importe quel objet. (In some older versions of Java you might get a compiler error when using primitive types directly)

  3. String - Le troisième paramètre est une chaîne placée comme titre de la fenêtre confirmDialog.

  4. int - L'int qui suit la chaîne est leOptionType. Les différentsOptionTypes pourJOptionPane sont:

    • OPTION PAR DÉFAUT

    • YES_NO_OPTION

    • YES_NO_CANCEL_OPTION

    • OK_CANCEL_OPTION

  5. int - Le prochain int est leMessageType. Les différentsMessageTypes pourJOptionPane sont:

    • MESSAGE D'ERREUR

    • INFORMATION_MESSAGE

    • MESSAGE D'ALERTE

    • QUESTION_MESSAGE

    • PLAIN_MESSAGE

  6. Icône - Le dernier paramètre est unIcon qui s'affiche dans la boîte de dialogue et remplace l'icône par défautMessageType.

1. Composant et objet

Le moyen le plus simple d'obtenir l'entrée de l'utilisateur. LesshowConfirmDialog() feront apparaître une boîte de dialogue avec les options Oui, Non et Annuler et le titre «Sélectionnez une option»:

ConfirmDialog1.java

package com.techfou.confirmDialog;

import javax.swing.JOptionPane;

public class ConfirmDialog1 {

    public static void main(String[] args) {

        int input = JOptionPane.showConfirmDialog(null, "Do you like bacon?");
        // 0=yes, 1=no, 2=cancel
        System.out.println(input);

    }
}

Sortie:

swing-comfirm-dialog-2a

2. Composant, objet, chaîne et int

Ajout d'informations supplémentaires dans la boîte de dialogue de confirmation. Dans cet exemple, nous pouvons choisir le titre de la boîte de dialogue ainsi que lesoptionType. LeDEFAULT_OPTION n'a qu'un bouton «OK». Cette forme de dialogue de confirmation équivaut à un simpleshowMessageDialog() tout en nous donnant la possibilité d'obtenir l'entrée de l'utilisateur.

ConfirmDialog2a.java

package com.techfou.confirmDialog;

import javax.swing.JOptionPane;

public class ConfirmDialog2a {

    public static void main(String[] args) {

        int input = JOptionPane.showConfirmDialog(null,
                "Click ok if you are ok", "Be ok!", JOptionPane.DEFAULT_OPTION);
        // 0=ok
        System.out.println(input);

    }
}

Sortie:

swing-comfirm-dialog-2b

Un autre exemple simple utilisant YES_NO_CANCEL_OPTION:

ConfirmDialog2b.java

package com.example.confirmDialog;

import javax.swing.JOptionPane;

public class ConfirmDialog2b {

    public static void main(String[] args) {

        int input = JOptionPane.showConfirmDialog(null,
                "Do you want to proceed?", "Select an Option...",JOptionPane.YES_NO_CANCEL_OPTION);

    // 0=yes, 1=no, 2=cancel
    System.out.println(input);

    }
}

Sortie:

swing-comfirm-dialog-2c

3. Composant, objet, chaîne, int & int

Donnez votre boîte de dialogue de confirmation avec l'icône d'erreur:

ConfirmDialog3.java

package com.example.confirmDialog;

import javax.swing.JOptionPane;

public class ConfirmDialog3 {

    public static void main(String[] args) {

        int input = JOptionPane.showConfirmDialog(null, "Do you want to proceed?", "Select an Option...",
                JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE);

    // 0=yes, 1=no, 2=cancel
    System.out.println(input);

    }
}

Sortie:

swing-comfirm-dialog-2d

4. Composant, objet, chaîne, int, int et icône

Rendez votre boîte de dialogue de confirmation «plus jolie» Exemple avecIcon récupéré à partir d'un répertoire:

ConfirmDialog4a.java

package com.example.confirmDialog;

import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

public class ConfirmDialog4a {

    public static void main(String[] args) {

        ImageIcon icon = new ImageIcon("src/images/turtle64.png");
    int input = JOptionPane.showConfirmDialog(null, "Do you like turtles?", "Be honest...",
            JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, icon);

        // 0=yes, 1=no, 2=cancel
    System.out.println(input);

    }
}

Sortie:

swing-comfirm-dialog-2e

Exemple avecComponent défini sur aframe:

ConfirmDialogInFrame.java

package com.example.confirmDialog;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.awt.Color;

public class ConfirmDialogInFrame extends JFrame{

    public ConfirmDialogInFrame() {
        getContentPane().setBackground(Color.DARK_GRAY);
        setTitle("Confirm Dialog in Frame");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        setResizable(false);
        setSize(400, 300);
        getContentPane().setLayout(null);
    }

    public static void main(String[] args){
        ImageIcon icon = new ImageIcon("src/images/turtle64.png");
        int input = JOptionPane.showConfirmDialog(new ConfirmDialogInFrame(),
                "I appear as part of the frame!!", "Customized Dialog",
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, icon);

        // 0=ok, 2=cancel
        System.out.println(input);
    }
}

Sortie:

swing-comfirm-dialog-2f

5. Un exemple plus avancé

Pour cet exemple, nous transmettons unJPanel comme paramètre Object. LeJPanel est personnalisé et a unJLabel ajouté. Nous manipulons également la taille desOptionPane en utilisant un appel àUIManager.

ConfirmDialogPanel.java

package com.example.messageDialog;

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

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

public class ConfirmDialogPanel {

    public static void main(String[] args) {

        ImageIcon icon = new ImageIcon("src/images/lock64.png");

        JPanel panel = new JPanel();
        panel.setBackground(new Color(102, 205, 170));
        panel.setSize(new Dimension(200, 64));
        panel.setLayout(null);

        JLabel label1 = new JLabel("This file requires administrator rights.");
        label1.setVerticalAlignment(SwingConstants.BOTTOM);
        label1.setBounds(0, 0, 200, 32);
        label1.setFont(new Font("Arial", Font.BOLD, 10));
        label1.setHorizontalAlignment(SwingConstants.CENTER);
        panel.add(label1);

        JLabel label2 = new JLabel("Are you sure you want to continue?");
        label2.setVerticalAlignment(SwingConstants.TOP);
        label2.setHorizontalAlignment(SwingConstants.CENTER);
        label2.setFont(new Font("Arial", Font.BOLD, 10));
        label2.setBounds(0, 32, 200, 32);
        panel.add(label2);

        UIManager.put("OptionPane.minimumSize", new Dimension(300, 120));
        int input = JOptionPane.showConfirmDialog(null, panel, "Admin Rights Confirmation",
                JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, icon);

        // 0=yes, 1=no, 2=cancel
        System.out.println(input);

    }

}

Sortie:

swing-comfirm-dialog-2g