1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| public class ExamplePrompt {
public static void main(String[] args) {
JFrame frame = new JFrame("Démo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComboBox<String> combo = new JComboBox<>();
combo.setRenderer(new PromptComboBoxRenderer(combo, "Choisissez un truc...", Color.GRAY, Font.ITALIC));
for(int i=1; i<=10; i++) {
combo.addItem("Choix " + i);
}
combo.setSelectedIndex(-1);
frame.add(combo);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static class PromptComboBoxRenderer extends DefaultListCellRenderer {
private final String prompt;
private final Component combo;
private final Color foreground;
private final Color promptColor;
private final Font font;
private final Font promptFont;
public PromptComboBoxRenderer(JComboBox<?> combo, String prompt, Color promptColor, Integer promptStyle) {
this.prompt = prompt;
this.combo = combo;
this.foreground = combo.getForeground();
this.font = combo.getFont();
this.promptColor = promptColor==null?foreground:promptColor;
this.promptFont = promptStyle==null?font:this.font.deriveFont(promptStyle);
}
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected,
boolean hasFocus) {
Component component = super.getListCellRendererComponent(list, value, index, isSelected, hasFocus);
if (index == -1 && value == null) {
setText(prompt);
combo.setFont(promptFont);
combo.setForeground(promptColor);
}
else {
combo.setFont(font);
combo.setForeground(foreground);
}
return component;
}
}
} |
Partager