Το στοιχείο JOptionPane

Το στοιχείο JOptionPane ανήκει στην κατηγορία Dialog Box ή Dialog Window.

Το JOptionPane είναι ένα modal παράθυρο και εμφανίζει σημειώσεις, ειδοποιήσεις, προτροπές και άλλες πληροφορίες στον χρήστη στη διάρκεια εκτέλεσης μιας εφαρμογής.

Για κάθε παράθυρο υπάρχει η αντίστοιχη μέθοδος. Ο γενικός τύπος είναι:

showXxxDialog

Όπου Xxx το είδος του παραθύρου που θα ανοίξει. Έτσι έχουμε:

Δημιουργία απλών παραθύρων διαλόγου

Τα παράθυρα αυτά δημιουργούνται με την μέθοδο showMessageDialog για εμφάνιση μηνυμάτων και την showOptionDialog για προτροπή επιλογής.

showMessageDialog

default title and icon

JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green.");

custom title, warning icon

JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green.", "Inane warning", JOptionPane.WARNING_MESSAGE);

custom title, error icon

JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green.", "Inane error", JOptionPane.ERROR_MESSAGE);

custom title, no icon

JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green.", "A plain message", JOptionPane.PLAIN_MESSAGE);

custom title, custom icon

JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green.", "Inane custom dialog", JOptionPane.INFORMATION_MESSAGE, icon);

Για το icon μπορείτε να χρησιμοποιήσετε την παρακάτω εντολή.

ImageIcon icon = new ImageIcon("icon.png");

showOptionDialog

Εμφανίζει ένα παράθυρο με προτροπή, κουμπιά, εικονίδια, μηνύματα κλπ.

//Custom button text
Object[] options = {"Yes, please",
                    "No, thanks",
                    "No eggs, no ham!"};
int n = JOptionPane.showOptionDialog(frame,
    "Would you like some green eggs to go "
    + "with that ham?",
    "A Silly Question",
    JOptionPane.YES_NO_CANCEL_OPTION,
    JOptionPane.QUESTION_MESSAGE,
    null,
    options,
    options[2]);

Εισαγωγή δεδομένων από τον χρήστη

Τα παράθυρα αυτά δημιουργούνται με την μέθοδο showInputDialog.

showInputDialog

showInputDialog με επιλογές

Object[] possibilities = {"ham", "spam", "yam"};
String s = (String)JOptionPane.showInputDialog(
                    frame,
                    "Complete the sentence:\n"
                    + "\"Green eggs and...\"",
                    "Customized Dialog",
                    JOptionPane.PLAIN_MESSAGE,
                    icon,
                    possibilities,
                    "ham");

showInputDialog πεδίο κειμένου

String s = (String)JOptionPane.showInputDialog(
                    frame,
                    "Complete the sentence:\n"
                    + "\"Green eggs and...\"",
                    "Customized Dialog",
                    JOptionPane.PLAIN_MESSAGE,
                    icon,
                    "ham");