2011-03-24 25 views
0

我試圖彈出一個對話框,允許用戶選擇兩種顏色之一作爲背景顏色。爲了使它看起來特別漂亮,我想兩個選擇要顯示在有問題的顏色,即:JOptionsPane在'options'參數中顯示組件作爲Component.toString()

import java.awt.Color; 
import java.awt.Label; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JOptionPane; 

public class JOptionPaneTest extends JFrame{ 

    public static void main(String[] args) { 
     new JOptionPaneTest(); 
    } 

    public JOptionPaneTest() { 
     Object[] possibilities = new Object[2]; 
     JButton black = new JButton("Black"); 
     JButton white = new JButton("White"); 
     black.setBackground(Color.black); 
     white.setBackground(Color.white); 
     black.setForeground(Color.white); 
     white.setForeground(Color.black); 
     possibilities[0] = black; 
     possibilities[1] = white; 

     JButton l = (JButton)JOptionPane.showInputDialog(this, 
       "Please specify the background color", "Background check", 
       JOptionPane.QUESTION_MESSAGE, null, possibilities, 
       possibilities[0]); 
     System.out.println("" + l); 
    } 
} 

但是,這並不工作 - 它顯示JButton.toString()的返回值在下拉而不是JButton。我也嘗試過JLabel和Label。根據API,JButton應該被添加到對話框中,因爲它們是組件。如果我將JButton添加到'message'參數中,它會按預期顯示。

任何想法我做錯了什麼?

回答

0

Java的API是性能稍微不清楚這一點。在頂部描述瞭如何解釋options,但是options是用戶可以選擇的YES,NO,CANCEL ...可能性,繪製在按鈕行中。你所談論的selectionValues,然後API(去命名showInputDialog最後的方法)是明確的:

selectionValues - 對象的數組,給出可能選擇
它是由UI決定如何最好地表示selectionValues,但通常會使用JComboBox,JList或JTextField。

從我的經驗,使用toString()顯示在selectionValues傳遞的對象,其結果是在JComboBoxJList顯示,所以你不能用油畫定製顯示選擇值;你需要實現你自己的對話框。

您可以通過message作爲Component,這樣可以提供一個傳說有關selectionValues,在那裏你可以展示與背景顏色標籤來表示每個顏色可選,從而提供assitance從selectionValues選擇一個值的用戶。

+0

在所有應有的尊重下,你引用的文本對我來說不是很清楚 - 那裏沒有任何內容表示輸入僅限於字符串,如果是,那麼使String類型更有意義[]而不是Object []。當然我的經驗和你的一樣。 – elhefe 2011-03-24 22:23:54

0

應該是showInputDialog中的字符串數組而不是jbutton(possibilites)的數組,但這樣就不會有背景顏色。我不認爲存在任何方式showInputDialog實現這樣的顏色選擇器()

String[] str = {"aaa", "bbb"}; 

JButton l = (JButton)JOptionPane.showInputDialog(this, 
      "Please specify the background color", "Background check", 
      JOptionPane.QUESTION_MESSAGE, null, str, str[0]); 
+0

在API中,我明確指出它可以是組件,圖標或其他任何東西的數組(後者通過toString()轉換爲字符串,每個API都將對象添加到對話框中,所以我發佈的代碼應該可以工作 – elhefe 2011-03-24 22:09:14

+0

對不起,但你不相信這個API,在這個組件中最重要的是toString()方法,它是否是擺動對象或對象 - 無所謂調用toString() – smas 2011-03-24 22:24:16