2012-11-11 6 views
11

Wie fügen Sie benutzerdefinierten Text zu den Schaltflächen eines JOptionPane.showInputDialog hinzu?Java: Benutzerdefinierte Schaltflächen in showInputDialog

Ich weiß über diese Frage JOptionPane showInputDialog with custom buttons, aber es beantwortet nicht die gestellte Frage, es verweist sie nur auf JavaDocs, die es nicht beantwortet.

-Code So Far:
Object[] options1 = {"Try This Number", "Choose A Random Number", "Quit"};

JOptionPane.showOptionDialog(null, 
       "Enter a number between 0 and 10000", 
       "Enter a Number", 
       JOptionPane.YES_NO_CANCEL_OPTION, 
       JOptionPane.PLAIN_MESSAGE, 
       null, 
       options1, 
       null); 

How I want it to look

Ich möchte ein Textfeld dazu hinzuzufügen.

+1

Könnten Sie erweitern auf Ihre Anforderungen ein bisschen mehr. Was hast du bisher? – Whymarrh

+0

Die Verweise auf die Javadocs (in diesem Fall zumindest) ist die richtige Antwort. Keine Notwendigkeit, hier zu schreiben, was andere bereits geschrieben haben. – vainolo

Antwort

18

Sie benutzerdefinierte Komponente anstelle einer Zeichenfolge Nachricht verwenden können, zum Beispiel:

import javax.swing.JLabel; 
import javax.swing.JOptionPane; 
import javax.swing.JPanel; 
import javax.swing.JTextField; 

public class TestDialog { 

    public static void main(String[] args) { 
     Object[] options1 = { "Try This Number", "Choose A Random Number", 
       "Quit" }; 

     JPanel panel = new JPanel(); 
     panel.add(new JLabel("Enter number between 0 and 1000")); 
     JTextField textField = new JTextField(10); 
     panel.add(textField); 

     int result = JOptionPane.showOptionDialog(null, panel, "Enter a Number", 
       JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, 
       null, options1, null); 
     if (result == JOptionPane.YES_OPTION){ 
      JOptionPane.showMessageDialog(null, textField.getText()); 
     } 
    } 
} 

enter image description here

+0

und wie erhalten Sie den Wert der Eingabe? – ZuluDeltaNiner

+0

@ZuluDeltaNiner aus dem Textfeld im Panel. Bitte siehe letzte Änderung. – tenorsax

+0

Wenn es nur eine Eingabe war und es kein Textfeld gab, wie konnte man das Ergebnis erhalten? –

8

Werfen Sie einen Blick auf How to Make Dialogs: Customizing Button Text. Hier

ist ein Beispiel gegeben:

enter image description here

Object[] options = {"Yes, please", 
        "No, thanks", 
        "No eggs, no ham!"}; 
int n = JOptionPane.showOptionDialog(frame,//parent container of JOptionPane 
    "Would you like some green eggs to go " 
    + "with that ham?", 
    "A Silly Question", 
    JOptionPane.YES_NO_CANCEL_OPTION, 
    JOptionPane.QUESTION_MESSAGE, 
    null,//do not use a custom Icon 
    options,//the titles of buttons 
    options[2]);//default button title 
Verwandte Themen