ユーザーが背景色として2色のいずれかを選択できるようにダイアログをポップアップしようとしています。特に見栄えを良くするために、問題の色で表示する2つの選択肢を指定します。
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の代わりにJButton.toString()の戻り値がドロップダウンに表示されます。また、JLabelとLabelを試してみました。APIによると、JButtonはコンポーネントであるため、そのままダイアログに追加する必要があります。JButtonを'message'パラメーターに追加すると、期待どおりに表示されます。
私が間違っていることについて何か考えはありますか?