2011-12-01 76 views
2

我創建了一個按鈕,打開一個JOptionPane。它允許用戶輸入一個string..>> String str = JOptionPane.showInputDialog如何獲取用戶輸入到joptionpane中的文本並使用它來搜索用戶對象?JOptionPane和從輸入中獲取文本

非常感謝

+0

你是怎麼保存的userobjects? – Jomoos

回答

0

你的目的,它有點不清楚,但是從我如何理解它,你只是想知道如何進入信息,這可以通過簡單地調用變量來完成。

要查看變量中的內容,請使用System.out.println(變量名稱);

請定義userobjects?

希望這會有所幫助。

6

返回的字符串是用戶輸入的內容,或NULL,如果用戶選擇取消:

String whatTheUserEntered = JOptionPane.showInputDialog(...); 
if (whatTheUserEntered == null) { 
    System.out.println("The user canceled"); 
} 
1

雖然@JB Nizet已經給了很好的回答。如果有人再次尋找這個問題,我想添加一個簡短的代碼示例僅供參考。

public class JOptionPaneExample 

私人雙重價格;

private JTextField priceField; 

private JLabel priceLabel; 

public JOptionPaneExample() 
{ 
    priceField = new JTextField(10); 
} 

public void createAndDisplayGUI() 
{ 
    int selection = JOptionPane.showConfirmDialog(null, getPanel(), "Price Form : ", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); 

    if (selection == JOptionPane.OK_OPTION) 
    { 
     price = Double.valueOf(priceField.getText()); 

     JOptionPane.showMessageDialog(null, "Price is : " + Double.toString(price), "Price : ", JOptionPane.PLAIN_MESSAGE); 
    } 
    else if (selection == JOptionPane.CANCEL_OPTION) 
    { 
     // Do something here. 
    } 
} 

private JPanel getPanel() 
{ 
    JPanel basePanel = new JPanel(); 
    basePanel.setOpaque(true); 
    basePanel.setBackground(Color.BLUE.darker()); 

    JPanel centerPanel = new JPanel(); 
    centerPanel.setLayout(new GridLayout(3, 2, 5, 5)); 
    centerPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); 
    centerPanel.setOpaque(true); 
    centerPanel.setBackground(Color.WHITE); 

    priceLabel = new JLabel("Enter Price : "); 

    centerPanel.add(priceLabel); 
    centerPanel.add(priceField); 

    basePanel.add(centerPanel); 

    return basePanel; 
} 

}

相同的代碼可以發現this blog

-1
import javax.swing.*; 
    class Test 
    { 
     public static void main (String args[]) 
     { 
      String name = JOptionPane.showInputDialog("Enter the name"); 
     } 
    }