我试图弹出一个对话框,允许用户选择两种颜色之一作为背景颜色。为了使它看起来特别漂亮,我想两个选择要显示在有问题的颜色,即: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