2010-01-18 88 views
6

我想要做的是有一個JTextArea而不是JTextField的JOptionPane inputDialog。
我試圖把JTextArea的消息參數的內部,像這樣JOptionPane自定義輸入

Object[] inputText = new Object[]{new JLabel("Enter Graph Information"), 
            newJTextArea("",20,10)}; 
graphInfo=(String)JOptionPane.showInputDialog(null, 
               inputText, 
               "Create Graph", 
               JOptionPane.PLAIN_MESSAGE, 
               null, 
               null, 
               ""); 

但它仍然具有文本字段在底部,我不能從JTextArea中的文本。 有沒有辦法刪除原始文本字段,並從jtextarea中獲取文本或完全替換文本區域的文本字段?如果可能,我試圖避免必須進行自定義對話框,這「看起來」像是應該很容易做的事情?

+0

可能重複【JAVA - 如何創建自定義對話框(http://stackoverflow.com/questions/789517/java-how-to-create-a-custom-dialog-box) – Tony 2014-10-25 11:38:46

回答

7

你說得對;你只需要使用showConfirmDialog而不是showMessageDialog,它允許你通過任何Component作爲你的「消息」,並讓它顯示在JDialog內。如果用戶單擊確定,則可以捕獲JTextArea的內容;例如

int okCxl = JOptionPane.showConfirmDialog(SwingUtilities.getWindowAncestor(this), 
            textArea, 
            "Enter Data", 
            JOptionPane.OK_CANCEL_OPTION) 

if (okCxl == JOptionPane.OK_OPTION) { 
    String text = textArea.getText(); 
    // Process text. 
} 

如果你想顯示在您的JTextArea您可以創建並傳遞一個包含兩個ComponentJPanel結合的JLabel;例如

JTextArea textArea = ... 
JPanel pnl = new JPanel(new BorderLayout()); 

pnl.add(new JLabel("Please enter some data:"), BorderLayout.NORTH); 
pnl.add(textArea, BorderLayout.CENTER); 

JOptionPane.show... 
+0

+1你打我吧:)另外,我不知道SwingUtilities.getWindowAncestor() - 很酷。 – 2010-01-18 21:55:13

+0

謝謝。我曾經使用JOptionPane.getFrameForComponent(this),但是實現SwingUtilities.getWindowAncestor會更好,以防對話框的父類也是JDialog。 – Adamski 2010-01-18 21:57:10

+0

哥們謝謝你。完美的答案! – 2010-01-19 04:46:43