source: josm/trunk/src/org/openstreetmap/josm/gui/widgets/JosmComboBox.java@ 16448

Last change on this file since 16448 was 16448, checked in by simon04, 4 years ago

see #19251 - Java warnings

  • Property svn:eol-style set to native
File size: 10.2 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.widgets;
3
4import java.awt.Component;
5import java.awt.Dimension;
6import java.awt.event.MouseAdapter;
7import java.awt.event.MouseEvent;
8import java.beans.PropertyChangeEvent;
9import java.beans.PropertyChangeListener;
10import java.util.Arrays;
11import java.util.Collection;
12import java.util.List;
13import java.util.stream.Collectors;
14import java.util.stream.IntStream;
15
16import javax.swing.ComboBoxEditor;
17import javax.swing.ComboBoxModel;
18import javax.swing.DefaultComboBoxModel;
19import javax.swing.JComboBox;
20import javax.swing.JList;
21import javax.swing.JTextField;
22import javax.swing.plaf.basic.ComboPopup;
23import javax.swing.text.JTextComponent;
24
25import org.openstreetmap.josm.gui.util.GuiHelper;
26
27/**
28 * Class overriding each {@link JComboBox} in JOSM to control consistently the number of displayed items at once.<br>
29 * This is needed because of the default Java behaviour that may display the top-down list off the screen (see #7917).
30 * @param <E> the type of the elements of this combo box
31 *
32 * @since 5429 (creation)
33 * @since 7015 (generics for Java 7)
34 */
35public class JosmComboBox<E> extends JComboBox<E> {
36
37 private final ContextMenuHandler handler = new ContextMenuHandler();
38
39 /**
40 * Creates a <code>JosmComboBox</code> with a default data model.
41 * The default data model is an empty list of objects.
42 * Use <code>addItem</code> to add items. By default the first item
43 * in the data model becomes selected.
44 *
45 * @see DefaultComboBoxModel
46 */
47 public JosmComboBox() {
48 init(null);
49 }
50
51 /**
52 * Creates a <code>JosmComboBox</code> with a default data model and
53 * the specified prototype display value.
54 * The default data model is an empty list of objects.
55 * Use <code>addItem</code> to add items. By default the first item
56 * in the data model becomes selected.
57 *
58 * @param prototypeDisplayValue the <code>Object</code> used to compute
59 * the maximum number of elements to be displayed at once before
60 * displaying a scroll bar
61 *
62 * @see DefaultComboBoxModel
63 * @since 5450
64 */
65 public JosmComboBox(E prototypeDisplayValue) {
66 init(prototypeDisplayValue);
67 }
68
69 /**
70 * Creates a <code>JosmComboBox</code> that takes its items from an
71 * existing <code>ComboBoxModel</code>. Since the
72 * <code>ComboBoxModel</code> is provided, a combo box created using
73 * this constructor does not create a default combo box model and
74 * may impact how the insert, remove and add methods behave.
75 *
76 * @param aModel the <code>ComboBoxModel</code> that provides the
77 * displayed list of items
78 * @see DefaultComboBoxModel
79 */
80 public JosmComboBox(ComboBoxModel<E> aModel) {
81 super(aModel);
82 List<E> list = IntStream.range(0, aModel.getSize())
83 .mapToObj(aModel::getElementAt)
84 .collect(Collectors.toList());
85 init(findPrototypeDisplayValue(list));
86 }
87
88 /**
89 * Creates a <code>JosmComboBox</code> that contains the elements
90 * in the specified array. By default the first item in the array
91 * (and therefore the data model) becomes selected.
92 *
93 * @param items an array of objects to insert into the combo box
94 * @see DefaultComboBoxModel
95 */
96 public JosmComboBox(E[] items) {
97 super(items);
98 init(findPrototypeDisplayValue(Arrays.asList(items)));
99 }
100
101 /**
102 * Returns the editor component
103 * @return the editor component
104 * @see ComboBoxEditor#getEditorComponent()
105 * @since 9484
106 */
107 public JTextField getEditorComponent() {
108 return (JTextField) getEditor().getEditorComponent();
109 }
110
111 /**
112 * Finds the prototype display value to use among the given possible candidates.
113 * @param possibleValues The possible candidates that will be iterated.
114 * @return The value that needs the largest display height on screen.
115 * @since 5558
116 */
117 protected final E findPrototypeDisplayValue(Collection<E> possibleValues) {
118 E result = null;
119 int maxHeight = -1;
120 if (possibleValues != null) {
121 // Remind old prototype to restore it later
122 E oldPrototype = getPrototypeDisplayValue();
123 // Get internal JList to directly call the renderer
124 @SuppressWarnings("rawtypes")
125 JList list = getList();
126 try {
127 // Index to give to renderer
128 int i = 0;
129 for (E value : possibleValues) {
130 if (value != null) {
131 // With a "classic" renderer, we could call setPrototypeDisplayValue(value) + getPreferredSize()
132 // but not with TaggingPreset custom renderer that return a dummy height if index is equal to -1
133 // So we explicitly call the renderer by simulating a correct index for the current value
134 @SuppressWarnings("unchecked")
135 Component c = getRenderer().getListCellRendererComponent(list, value, i, true, true);
136 if (c != null) {
137 // Get the real preferred size for the current value
138 Dimension dim = c.getPreferredSize();
139 if (dim.height > maxHeight) {
140 // Larger ? This is our new prototype
141 maxHeight = dim.height;
142 result = value;
143 }
144 }
145 }
146 i++;
147 }
148 } finally {
149 // Restore original prototype
150 setPrototypeDisplayValue(oldPrototype);
151 }
152 }
153 return result;
154 }
155
156 @SuppressWarnings("unchecked")
157 protected final JList<Object> getList() {
158 return IntStream.range(0, getUI().getAccessibleChildrenCount(this))
159 .mapToObj(i -> getUI().getAccessibleChild(this, i))
160 .filter(child -> child instanceof ComboPopup)
161 .map(child -> ((ComboPopup) child).getList())
162 .findFirst().orElse(null);
163 }
164
165 protected final void init(E prototype) {
166 init(prototype, true);
167 }
168
169 protected final void init(E prototype, boolean registerPropertyChangeListener) {
170 if (prototype != null) {
171 setPrototypeDisplayValue(prototype);
172 int screenHeight = GuiHelper.getScreenSize().height;
173 // Compute maximum number of visible items based on the preferred size of the combo box.
174 // This assumes that items have the same height as the combo box, which is not granted by the look and feel
175 int maxsize = (screenHeight/getPreferredSize().height) / 2;
176 // If possible, adjust the maximum number of items with the real height of items
177 // It is not granted this works on every platform (tested OK on Windows)
178 JList<Object> list = getList();
179 if (list != null) {
180 if (!prototype.equals(list.getPrototypeCellValue())) {
181 list.setPrototypeCellValue(prototype);
182 }
183 int height = list.getFixedCellHeight();
184 if (height > 0) {
185 maxsize = (screenHeight/height) / 2;
186 }
187 }
188 setMaximumRowCount(Math.max(getMaximumRowCount(), maxsize));
189 }
190 // Handle text contextual menus for editable comboboxes
191 if (registerPropertyChangeListener) {
192 addPropertyChangeListener("editable", handler);
193 addPropertyChangeListener("editor", handler);
194 }
195 }
196
197 protected class ContextMenuHandler extends MouseAdapter implements PropertyChangeListener {
198
199 private JTextComponent component;
200 private PopupMenuLauncher launcher;
201
202 @Override
203 public void propertyChange(PropertyChangeEvent evt) {
204 if ("editable".equals(evt.getPropertyName())) {
205 if (evt.getNewValue().equals(Boolean.TRUE)) {
206 enableMenu();
207 } else {
208 disableMenu();
209 }
210 } else if ("editor".equals(evt.getPropertyName())) {
211 disableMenu();
212 if (isEditable()) {
213 enableMenu();
214 }
215 }
216 }
217
218 private void enableMenu() {
219 if (launcher == null && editor != null) {
220 Component editorComponent = editor.getEditorComponent();
221 if (editorComponent instanceof JTextComponent) {
222 component = (JTextComponent) editorComponent;
223 component.addMouseListener(this);
224 launcher = TextContextualPopupMenu.enableMenuFor(component, true);
225 }
226 }
227 }
228
229 private void disableMenu() {
230 if (launcher != null) {
231 TextContextualPopupMenu.disableMenuFor(component, launcher);
232 launcher = null;
233 component.removeMouseListener(this);
234 component = null;
235 }
236 }
237
238 private void discardAllUndoableEdits() {
239 if (launcher != null) {
240 launcher.discardAllUndoableEdits();
241 }
242 }
243
244 @Override
245 public void mousePressed(MouseEvent e) {
246 processEvent(e);
247 }
248
249 @Override
250 public void mouseReleased(MouseEvent e) {
251 processEvent(e);
252 }
253
254 private void processEvent(MouseEvent e) {
255 if (launcher != null && !e.isPopupTrigger() && launcher.getMenu().isShowing()) {
256 launcher.getMenu().setVisible(false);
257 }
258 }
259 }
260
261 /**
262 * Reinitializes this {@link JosmComboBox} to the specified values. This may be needed if a custom renderer is used.
263 * @param values The values displayed in the combo box.
264 * @since 5558
265 */
266 public final void reinitialize(Collection<E> values) {
267 init(findPrototypeDisplayValue(values), false);
268 discardAllUndoableEdits();
269 }
270
271 /**
272 * Empties the internal undo manager, if any.
273 * @since 14977
274 */
275 public final void discardAllUndoableEdits() {
276 handler.discardAllUndoableEdits();
277 }
278}
Note: See TracBrowser for help on using the repository browser.