2016-09-19 92 views
1

當我使用下面的代碼時,JOptionPane的外觀似乎根據數組中保存的數據項有所不同。有時會出現一個下拉滾動列表(類似於JComboBox)。在其他時候,當數組擁有更多的項目時,組件類似於JList。JOptionPane組件似乎不同

Object wid = JOptionPane.showInputDialog(null, 
        "Choose Width", 
        "Select a Width", JOptionPane.QUESTION_MESSAGE, 
        null, width, "9"); 

有關如何控制顯示哪種類型的組件以及它在尺寸和顏色方面的外觀,我們將不勝感激任何建議嗎?

回答

1

如果使用方法showInputDialog,則無法控制如何構造或設計對話框 。這種方法存在一個快速的方法來構建一個輸入對話框,它可以在你不關心它的外觀或行爲方式時起作用。這一切都取決於環境的感覺。
大多數情況下,這意味着在這種情況下 19個元素或更低的結果在JComboBox和20或更多的結果在JList

如果你想完全控制GUI組件,你需要自己設計它們。 它不像聽起來那麼難。看看這段代碼。不管它有多少物品,它總會產生一個組合框。

final int items = 100; 

// create items 
String[] width = new String[items]; 
for(int i = 0; i < items; i++) width[i] = Integer.toString(i); 

// create the panel 
JPanel panel = new JPanel(); 
panel.setLayout(new GridLayout(2,1)); 
JLabel label = new JLabel("Choose Width"); 
JComboBox<String> cmbBox = new JComboBox<>(width); 
cmbBox.setSelectedIndex(8); 
panel.add(label); 
panel.add(cmbBox); 

// show dialog 
int res = JOptionPane.showConfirmDialog(null, panel, 
      "Select a Width", JOptionPane.OK_CANCEL_OPTION, 
      JOptionPane.QUESTION_MESSAGE, null); 

// get selection 
if(res == JOptionPane.OK_OPTION){ 
    String sel = String.valueOf(cmbBox.getSelectedItem()); 
    System.out.println("you selected: " + sel); 
} 
+0

首先非常感謝! 我可以問你爲什麼使用showConfirmDialog而不是showInputDialog? 他們有什麼區別?我應該什麼時候使用對方? – Sagie

+1

嘗試一下,你會看到不同之處。無論您在自定義面板中使用自己的輸入元素,inputDialog都會創建一個附加文本字段。所以我推薦confirmDialog,因爲它不會創建額外的組件。 – ArcticLord