PageRenderTime 43ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/projects/netbeans-7.3/j2ee.common/src/org/netbeans/modules/j2ee/common/method/impl/ReturnTypeUIHelper.java

https://gitlab.com/essere.lab.public/qualitas.class-corpus
Java | 428 lines | 273 code | 79 blank | 76 comment | 42 complexity | 495cdcca28ade0f671203f4f2db54ffb MD5 | raw file
  1. /*
  2. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
  3. *
  4. * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
  5. *
  6. * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
  7. * Other names may be trademarks of their respective owners.
  8. *
  9. * The contents of this file are subject to the terms of either the GNU
  10. * General Public License Version 2 only ("GPL") or the Common
  11. * Development and Distribution License("CDDL") (collectively, the
  12. * "License"). You may not use this file except in compliance with the
  13. * License. You can obtain a copy of the License at
  14. * http://www.netbeans.org/cddl-gplv2.html
  15. * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
  16. * specific language governing permissions and limitations under the
  17. * License. When distributing the software, include this License Header
  18. * Notice in each file and include the License file at
  19. * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
  20. * particular file as subject to the "Classpath" exception as provided
  21. * by Oracle in the GPL Version 2 section of the License file that
  22. * accompanied this code. If applicable, add the following below the
  23. * License Header, with the fields enclosed by brackets [] replaced by
  24. * your own identifying information:
  25. * "Portions Copyrighted [year] [name of copyright owner]"
  26. *
  27. * Contributor(s):
  28. *
  29. * The Original Software is NetBeans. The Initial Developer of the Original
  30. * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
  31. * Microsystems, Inc. All Rights Reserved.
  32. *
  33. * If you wish your version of this file to be governed by only the CDDL
  34. * or only the GPL Version 2, indicate your decision by adding
  35. * "[Contributor] elects to include this software in this distribution
  36. * under the [CDDL or GPL Version 2] license." If you do not indicate a
  37. * single choice of license, a recipient has the option to distribute
  38. * your version of this file under either the CDDL, the GPL Version 2 or
  39. * to extend the choice of license to its licensees as provided above.
  40. * However, if you add GPL Version 2 code and therefore, elected the GPL
  41. * Version 2 license, then the option applies only if the new code is
  42. * made subject to such option by the copyright holder.
  43. */
  44. package org.netbeans.modules.j2ee.common.method.impl;
  45. import java.awt.Color;
  46. import java.awt.Component;
  47. import java.awt.Dimension;
  48. import java.awt.event.ActionEvent;
  49. import java.awt.event.ActionListener;
  50. import java.awt.event.InputEvent;
  51. import java.awt.event.KeyAdapter;
  52. import java.awt.event.KeyEvent;
  53. import java.lang.reflect.Method;
  54. import java.util.Arrays;
  55. import java.util.LinkedList;
  56. import java.util.List;
  57. import java.util.Set;
  58. import java.util.logging.Level;
  59. import java.util.logging.Logger;
  60. import javax.lang.model.element.TypeElement;
  61. import javax.swing.AbstractListModel;
  62. import javax.swing.ComboBoxEditor;
  63. import javax.swing.DefaultListCellRenderer;
  64. import javax.swing.JComboBox;
  65. import javax.swing.JList;
  66. import javax.swing.JSeparator;
  67. import javax.swing.ListCellRenderer;
  68. import javax.swing.MutableComboBoxModel;
  69. import javax.swing.SwingUtilities;
  70. import javax.swing.text.JTextComponent;
  71. import org.netbeans.api.java.source.ClassIndex.NameKind;
  72. import org.netbeans.api.java.source.ClassIndex.SearchScope;
  73. import org.netbeans.api.java.source.ClasspathInfo;
  74. import org.netbeans.api.java.source.ElementHandle;
  75. import org.netbeans.api.java.source.ui.TypeElementFinder;
  76. import org.netbeans.modules.j2ee.common.DatasourceUIHelper;
  77. import org.openide.util.NbBundle;
  78. /**
  79. *
  80. * ReturnTypeUIHelper populates and manages the content of the combobox for a return type of method
  81. *
  82. * @see DatasourceUIHelper
  83. *
  84. * @author Martin Adamek
  85. */
  86. public final class ReturnTypeUIHelper {
  87. private static final List<String> LVALUE_TYPES = Arrays.asList(new String[] {
  88. "boolean", "int", "char", "byte", "short", "long", "float", "double", // NOI18N
  89. "Object", "String" // NOI18N
  90. });
  91. private static final class Separator extends JSeparator {
  92. Separator() {
  93. setPreferredSize(new Dimension(getWidth(), 1));
  94. setForeground(Color.BLACK);
  95. }
  96. }
  97. static final Separator SEPARATOR_ITEM = new Separator();
  98. static final Object NEW_ITEM = new Object() {
  99. @Override
  100. public String toString() {
  101. return NbBundle.getMessage(ReturnTypeUIHelper.class, "LBL_Choose"); // NOI18N
  102. }
  103. };
  104. private static class ReturnTypeComboBoxModel extends AbstractListModel implements MutableComboBoxModel {
  105. private List<Object> items;
  106. private Object selectedItem;
  107. private List<String> returnTypes;
  108. private Object previousItem;
  109. private ReturnTypeComboBoxModel(List<String> returnTypes, List<Object> items) {
  110. this.returnTypes = returnTypes;
  111. this.items = items;
  112. }
  113. public void setSelectedItem(Object anItem) {
  114. if (selectedItem == null || !selectedItem.equals(anItem)) {
  115. previousItem = selectedItem;
  116. selectedItem = anItem;
  117. fireContentsChanged(this, 0, -1);
  118. }
  119. }
  120. public Object getSelectedItem() {
  121. return selectedItem;
  122. }
  123. public Object getElementAt(int index) {
  124. return items.get(index);
  125. }
  126. public int getSize() {
  127. return items.size();
  128. }
  129. Object getPreviousItem() {
  130. return previousItem;
  131. }
  132. List<String> getReturnTypes() {
  133. return returnTypes;
  134. }
  135. public void addElement(Object elem) {
  136. items.add(elem);
  137. }
  138. public void removeElement(Object elem) {
  139. items.remove(elem);
  140. }
  141. public void insertElementAt(Object elem, int index) {
  142. items.set(index, elem);
  143. }
  144. public void removeElementAt(int index) {
  145. items.remove(index);
  146. }
  147. }
  148. /**
  149. * Get data source list cell renderer.
  150. * @return data source list cell renderer instance.
  151. * @since 1.16
  152. */
  153. public static ListCellRenderer createDatasourceListCellRenderer() {
  154. return new ReturnTypeListCellRenderer();
  155. }
  156. private static class ReturnTypeListCellRenderer extends DefaultListCellRenderer {
  157. @Override
  158. public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
  159. if (isSelected) {
  160. setBackground(list.getSelectionBackground());
  161. setForeground(list.getSelectionForeground());
  162. } else {
  163. setBackground(list.getBackground());
  164. setForeground(list.getForeground());
  165. }
  166. if (value == SEPARATOR_ITEM) {
  167. return SEPARATOR_ITEM;
  168. }
  169. else {
  170. setText(value != null ? value.toString() : ""); // NOI18N
  171. setToolTipText(""); // NOI18N
  172. }
  173. return this;
  174. }
  175. }
  176. private static class ReturnTypeComboBoxEditor implements ComboBoxEditor {
  177. private ComboBoxEditor delegate;
  178. private Object oldValue;
  179. ReturnTypeComboBoxEditor(ComboBoxEditor delegate) {
  180. this.delegate = delegate;
  181. }
  182. public Component getEditorComponent() {
  183. return delegate.getEditorComponent();
  184. }
  185. public void setItem(Object anObject) {
  186. JTextComponent editor = getEditor();
  187. if (anObject != null) {
  188. String text = anObject.toString();
  189. editor.setText(text);
  190. oldValue = anObject;
  191. }
  192. else {
  193. editor.setText("");
  194. }
  195. }
  196. // this method is taken from javax.swing.plaf.basic.BasicComboBoxEditor
  197. public Object getItem() {
  198. JTextComponent editor = getEditor();
  199. Object newValue = editor.getText();
  200. if (oldValue != null && !(oldValue instanceof String)) {
  201. // The original value is not a string. Should return the value in it's
  202. // original type.
  203. if (newValue.equals(oldValue.toString())) {
  204. return oldValue;
  205. } else {
  206. // Must take the value from the editor and get the value and cast it to the new type.
  207. Class<?> cls = oldValue.getClass();
  208. try {
  209. Method method = cls.getMethod("valueOf", String.class); // NOI18N
  210. newValue = method.invoke(oldValue, new Object[] { editor.getText() });
  211. } catch (Exception ex) {
  212. // Fail silently and return the newValue (a String object)
  213. Logger.getLogger("ReturnTypeUIHelper").log(Level.FINE, "ignored excep[tion", ex); //NOI18N
  214. }
  215. }
  216. }
  217. return newValue;
  218. }
  219. public void selectAll() {
  220. delegate.selectAll();
  221. }
  222. public void addActionListener(ActionListener l) {
  223. delegate.addActionListener(l);
  224. }
  225. public void removeActionListener(ActionListener l) {
  226. delegate.removeActionListener(l);
  227. }
  228. private JTextComponent getEditor() {
  229. Component comp = getEditorComponent();
  230. assert (comp instanceof JTextComponent);
  231. return (JTextComponent)comp;
  232. }
  233. }
  234. private ReturnTypeUIHelper() {
  235. }
  236. /**
  237. * Entry point for the combobox initialization. It connects combobox with its content and
  238. * add items for the combobox content management.
  239. *
  240. * @param provider Java EE module provider.
  241. * @param combo combobox to manage.
  242. */
  243. public static void connect(JComboBox combo, ClasspathInfo cpInfo) {
  244. connect(combo, null, cpInfo);
  245. }
  246. private static final void connect(final JComboBox combo, final String selectedType, final ClasspathInfo cpInfo) {
  247. combo.setEditable(true);
  248. combo.setEditor(new ReturnTypeComboBoxEditor(combo.getEditor()));
  249. combo.setRenderer(new ReturnTypeListCellRenderer());
  250. populate(LVALUE_TYPES, true, combo, selectedType, false);
  251. Component toListenOn = (combo.isEditable() ? combo.getEditor().getEditorComponent() : combo);
  252. toListenOn.addKeyListener(new KeyAdapter() {
  253. public void keyPressed(final KeyEvent e) {
  254. int keyCode = e.getKeyCode();
  255. if (KeyEvent.VK_ENTER == keyCode) {
  256. Object selectedItem = combo.getSelectedItem();
  257. if (selectedItem == NEW_ITEM) {
  258. performBrowseType(combo, cpInfo);
  259. e.consume();
  260. }
  261. }
  262. }
  263. });
  264. combo.addActionListener(new ActionListener() {
  265. Object previousItem;
  266. int previousIndex = combo.getSelectedIndex();
  267. public void actionPerformed(ActionEvent e) {
  268. Object selectedItem = combo.getSelectedItem();
  269. // skipping of separator
  270. if (selectedItem == SEPARATOR_ITEM) {
  271. int selectedIndex = combo.getSelectedIndex();
  272. if (selectedIndex > previousIndex) {
  273. previousIndex = selectedIndex + 1;
  274. previousItem = combo.getItemAt(previousIndex);
  275. } else {
  276. previousIndex = selectedIndex - 1;
  277. previousItem = combo.getItemAt(previousIndex);
  278. }
  279. combo.setSelectedItem(previousItem);
  280. // handling mouse click, see KeyEvent.getKeyModifiersText(e.getModifiers())
  281. } else if ((e.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
  282. if (selectedItem == NEW_ITEM) {
  283. performBrowseType(combo, cpInfo);
  284. }
  285. }
  286. }
  287. });
  288. }
  289. private static void performBrowseType(final JComboBox combo, final ClasspathInfo cpInfo) {
  290. final ReturnTypeComboBoxModel model = (ReturnTypeComboBoxModel) combo.getModel();
  291. combo.setPopupVisible(false);
  292. SwingUtilities.invokeLater(new Runnable() {
  293. public void run() {
  294. final ElementHandle<TypeElement> handle = TypeElementFinder.find(cpInfo, new TypeElementFinder.Customizer() {
  295. public Set<ElementHandle<TypeElement>> query(ClasspathInfo classpathInfo, String textForQuery, NameKind nameKind, Set<SearchScope> searchScopes) {//GEN-LAST:event_browseButtonActionPerformed
  296. return classpathInfo.getClassIndex().getDeclaredTypes(textForQuery, nameKind, searchScopes);
  297. }
  298. public boolean accept(ElementHandle<TypeElement> typeHandle) {
  299. return true;
  300. }
  301. });
  302. combo.setPopupVisible(false);
  303. if (handle == null) {
  304. SwingUtilities.invokeLater(new Runnable() {
  305. public void run() {
  306. setSelectedItem(combo, model.getPreviousItem());
  307. }
  308. });
  309. } else {
  310. setSelectedItem(combo, handle.getQualifiedName());
  311. }
  312. }
  313. });
  314. }
  315. private static List populate(List<String> types, boolean creationSupported, final JComboBox combo, final String selectedType, boolean selectItemLater) {
  316. List<Object> items = (types == null ? new LinkedList<Object>() : new LinkedList<Object>(types));
  317. if (items.size() > 0) {
  318. items.add(SEPARATOR_ITEM);
  319. }
  320. if (creationSupported) {
  321. items.add(NEW_ITEM);
  322. }
  323. ReturnTypeComboBoxModel model = new ReturnTypeComboBoxModel(types, items);
  324. combo.setModel(model);
  325. if (selectedType != null) {
  326. // Ensure that the correct item is selected before listeners like FocusListener are called.
  327. // ActionListener.actionPerformed() is not called if this method is already called from
  328. // actionPerformed(), in that case selectItemLater should be set to true and setSelectedItem()
  329. // below is called asynchronously so that the actionPerformed() is called
  330. setSelectedItem(combo, selectedType);
  331. if (selectItemLater) {
  332. SwingUtilities.invokeLater(new Runnable() { // postpone item selection to enable event firing from JCombobox.setSelectedItem()
  333. public void run() {
  334. setSelectedItem(combo, selectedType);
  335. // populate(LVALUE_TYPES, true, combo, "Object", false);
  336. }
  337. });
  338. }
  339. }
  340. return types;
  341. }
  342. private static void setSelectedItem(final JComboBox combo, final Object item) {
  343. combo.setSelectedItem(item);
  344. if (combo.isEditable() && combo.getEditor() != null) {
  345. // item must be set in the editor in case of editable combobox
  346. combo.configureEditor(combo.getEditor(), combo.getSelectedItem());
  347. }
  348. }
  349. }