I'm trying to pop up a dialog to allow the user to select one of two colors as a background color. To make it look especially spiffy, I'd like to two choices to be displayed in the color in question, i.e.:
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);
}
}
However, this doesn't work - it displays the JButton.toString() return values in a drop down instead of the JButton. I also tried JLabel and Label for the heck of it. According to the API, the JButtons should be added to the dialog as is since they're Components. If I add the JButton to the 'message' parameter it does display as expected.
Any idea what I'm doing wrong?
The Java API is slighly unclear about this point. At the top describes how to interpret the options
, but options
are the YES, NO, CANCEL... possibilities the user can choose, painted in the buttons row. You are talking about the selectionValues
, and then the API (go to last method named showInputDialog
) is clear:
selectionValues
- an array of Objects that gives the possible selections
It is up to the UI to decide how best to represent the selectionValues, but usually a JComboBox, JList, or JTextField will be used.
From my experience, the objects passed in the selectionValues
are displayed using toString()
and the result is shown in a JComboBox
or a JList
, so you can not show selection values with custom painting; you need to implement you own dialog for that.
You can pass the message
as a Component
so you can provide a legend to the user about the selectionValues
, where you can show labels with background colors to indicate each color available and thus provide assitance selecting a value from selectionValues
.