我試圖彈出一個對話框,允許用戶選擇兩種顏色之一作爲背景顏色。爲了使它看起來特別漂亮,我想兩個選擇要顯示在有問題的顏色,即: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'參數中,它會按預期顯示。
任何想法我做錯了什麼?
在所有應有的尊重下,你引用的文本對我來說不是很清楚 - 那裏沒有任何內容表示輸入僅限於字符串,如果是,那麼使String類型更有意義[]而不是Object []。當然我的經驗和你的一樣。 – elhefe 2011-03-24 22:23:54