JAL-3141 Added tooltips on Schemes dropdown and Customise checkbox
[jalview.git] / src / jalview / gui / JvSwingUtils.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.gui;
22
23 import jalview.io.IntKeyStringValueEntry;
24 import jalview.util.MessageManager;
25
26 import java.awt.BorderLayout;
27 import java.awt.Color;
28 import java.awt.Component;
29 import java.awt.Font;
30 import java.awt.GridLayout;
31 import java.awt.Rectangle;
32 import java.awt.event.ActionListener;
33 import java.awt.event.MouseAdapter;
34 import java.awt.event.MouseEvent;
35 import java.util.List;
36 import java.util.Objects;
37
38 import javax.swing.AbstractButton;
39 import javax.swing.BorderFactory;
40 import javax.swing.JButton;
41 import javax.swing.JComboBox;
42 import javax.swing.JComponent;
43 import javax.swing.JLabel;
44 import javax.swing.JMenu;
45 import javax.swing.JMenuItem;
46 import javax.swing.JPanel;
47 import javax.swing.JScrollBar;
48 import javax.swing.SwingConstants;
49 import javax.swing.border.Border;
50 import javax.swing.border.TitledBorder;
51
52 /**
53  * useful functions for building Swing GUIs
54  * 
55  * @author JimP
56  * 
57  */
58 public final class JvSwingUtils
59 {
60   /**
61    * wrap a bare html safe string to around 60 characters per line using a CSS
62    * style class specifying word-wrap and break-word
63    * 
64    * @param enclose
65    *          if true, add &lt;html&gt; wrapper tags
66    * @param ttext
67    * 
68    * @return
69    */
70   public static String wrapTooltip(boolean enclose, String ttext)
71   {
72     Objects.requireNonNull(ttext,
73             "Tootip text to format must not be null!");
74     ttext = ttext.trim();
75     boolean maxLengthExceeded = false;
76
77     if (ttext.contains("<br>"))
78     {
79       String[] htmllines = ttext.split("<br>");
80       for (String line : htmllines)
81       {
82         maxLengthExceeded = line.length() > 60;
83         if (maxLengthExceeded)
84         {
85           break;
86         }
87       }
88     }
89     else
90     {
91       maxLengthExceeded = ttext.length() > 60;
92     }
93
94     if (!maxLengthExceeded)
95     {
96       return enclose ? "<html>" + ttext + "</html>" : ttext;
97     }
98
99     return (enclose ? "<html>" : "")
100             + "<style> p.ttip {width: 350; text-align: justify; word-wrap: break-word;}</style><p class=\"ttip\">"
101             + ttext + "</p>" + ((enclose ? "</html>" : ""));
102
103   }
104
105   public static JButton makeButton(String label, String tooltip,
106           ActionListener action)
107   {
108     JButton button = new JButton();
109     button.setText(label);
110     // TODO: get the base font metrics for the Jalview gui from somewhere
111     button.setFont(new java.awt.Font("Verdana", Font.PLAIN, 10));
112     button.setForeground(Color.black);
113     button.setHorizontalAlignment(SwingConstants.CENTER);
114     button.setToolTipText(tooltip);
115     button.addActionListener(action);
116     return button;
117   }
118
119   /**
120    * find or add a submenu with the given title in the given menu
121    * 
122    * @param menu
123    * @param submenu
124    * @return the new or existing submenu
125    */
126   public static JMenu findOrCreateMenu(JMenu menu, String submenu)
127   {
128     JMenu submenuinstance = null;
129     for (int i = 0, iSize = menu.getMenuComponentCount(); i < iSize; i++)
130     {
131       if (menu.getMenuComponent(i) instanceof JMenu
132               && ((JMenu) menu.getMenuComponent(i)).getText()
133                       .equals(submenu))
134       {
135         submenuinstance = (JMenu) menu.getMenuComponent(i);
136       }
137     }
138     if (submenuinstance == null)
139     {
140       submenuinstance = new JMenu(submenu);
141       menu.add(submenuinstance);
142     }
143     return submenuinstance;
144
145   }
146
147   /**
148    * 
149    * @param panel
150    * @param tooltip
151    * @param label
152    * @param valBox
153    * @return the GUI element created that was added to the layout so it's
154    *         attributes can be changed.
155    */
156   public static JPanel addtoLayout(JPanel panel, String tooltip,
157           JComponent label, JComponent valBox)
158   {
159     JPanel laypanel = new JPanel(new GridLayout(1, 2));
160     JPanel labPanel = new JPanel(new BorderLayout());
161     JPanel valPanel = new JPanel();
162     labPanel.setBounds(new Rectangle(7, 7, 158, 23));
163     valPanel.setBounds(new Rectangle(172, 7, 270, 23));
164     labPanel.add(label, BorderLayout.WEST);
165     valPanel.add(valBox);
166     laypanel.add(labPanel);
167     laypanel.add(valPanel);
168     valPanel.setToolTipText(tooltip);
169     labPanel.setToolTipText(tooltip);
170     valBox.setToolTipText(tooltip);
171     panel.add(laypanel);
172     panel.validate();
173     return laypanel;
174   }
175
176   public static void mgAddtoLayout(JPanel cpanel, String tooltip,
177           JLabel jLabel, JComponent name)
178   {
179     mgAddtoLayout(cpanel, tooltip, jLabel, name, null);
180   }
181
182   public static void mgAddtoLayout(JPanel cpanel, String tooltip,
183           JLabel jLabel, JComponent name, String params)
184   {
185     cpanel.add(jLabel);
186     if (params == null)
187     {
188       cpanel.add(name);
189     }
190     else
191     {
192       cpanel.add(name, params);
193     }
194     name.setToolTipText(tooltip);
195     jLabel.setToolTipText(tooltip);
196   }
197
198   /**
199    * standard font for labels and check boxes in dialog boxes
200    * 
201    * @return
202    */
203
204   public static Font getLabelFont()
205   {
206     return getLabelFont(false, false);
207   }
208
209   public static Font getLabelFont(boolean bold, boolean italic)
210   {
211     return new java.awt.Font("Verdana",
212             (!bold && !italic) ? Font.PLAIN
213                     : (bold ? Font.BOLD : 0) + (italic ? Font.ITALIC : 0),
214             11);
215   }
216
217   /**
218    * standard font for editable text areas
219    * 
220    * @return
221    */
222   public static Font getTextAreaFont()
223   {
224     return getLabelFont(false, false);
225   }
226
227   /**
228    * clean up a swing menu. Removes any empty submenus without selection
229    * listeners.
230    * 
231    * @param webService
232    */
233   public static void cleanMenu(JMenu webService)
234   {
235     for (int i = 0; i < webService.getItemCount();)
236     {
237       JMenuItem item = webService.getItem(i);
238       if (item instanceof JMenu && ((JMenu) item).getItemCount() == 0)
239       {
240         webService.remove(i);
241       }
242       else
243       {
244         i++;
245       }
246     }
247   }
248
249   /**
250    * Returns the proportion of its range that a scrollbar's position represents,
251    * as a value between 0 and 1. For example if the whole range is from 0 to
252    * 200, then a position of 40 gives proportion = 0.2.
253    * 
254    * @see http://www.javalobby.org/java/forums/t33050.html#91885334
255    * 
256    * @param scroll
257    * @return
258    */
259   public static float getScrollBarProportion(JScrollBar scroll)
260   {
261     /*
262      * The extent (scroll handle width) deduction gives the true operating range
263      * of possible positions.
264      */
265     int possibleRange = scroll.getMaximum() - scroll.getMinimum()
266             - scroll.getModel().getExtent();
267     float valueInRange = scroll.getValue()
268             - (scroll.getModel().getExtent() / 2f);
269     float proportion = valueInRange / possibleRange;
270     return proportion;
271   }
272
273   /**
274    * Returns the scroll bar position in its range that would match the given
275    * proportion (between 0 and 1) of the whole. For example if the whole range
276    * is from 0 to 200, then a proportion of 0.25 gives position 50.
277    * 
278    * @param scrollbar
279    * @param proportion
280    * @return
281    */
282   public static int getScrollValueForProportion(JScrollBar scrollbar,
283           float proportion)
284   {
285     /*
286      * The extent (scroll handle width) deduction gives the true operating range
287      * of possible positions.
288      */
289     float fraction = proportion
290             * (scrollbar.getMaximum() - scrollbar.getMinimum()
291                     - scrollbar.getModel().getExtent())
292             + (scrollbar.getModel().getExtent() / 2f);
293     return Math.min(Math.round(fraction), scrollbar.getMaximum());
294   }
295
296   public static void jvInitComponent(AbstractButton comp, String i18nString)
297   {
298     setColorAndFont(comp);
299     if (i18nString != null && !i18nString.isEmpty())
300     {
301       comp.setText(MessageManager.getString(i18nString));
302     }
303   }
304
305   public static void jvInitComponent(JComponent comp)
306   {
307     setColorAndFont(comp);
308   }
309
310   private static void setColorAndFont(JComponent comp)
311   {
312     comp.setBackground(Color.white);
313     comp.setFont(JvSwingUtils.getLabelFont());
314   }
315
316   /**
317    * A helper method to build a drop-down choice of values, with tooltips for
318    * the entries
319    * 
320    * @param entries
321    * @param tooltips
322    */
323   public static JComboBox<String> buildComboWithTooltips(
324           List<String> entries, List<String> tooltips)
325   {
326     JComboBox<String> combo = new JComboBox<>();
327     final ComboBoxTooltipRenderer renderer = new ComboBoxTooltipRenderer();
328     combo.setRenderer(renderer);
329     for (String attName : entries)
330     {
331       combo.addItem(attName);
332     }
333     renderer.setTooltips(tooltips);
334     final MouseAdapter mouseListener = new MouseAdapter()
335     {
336       @Override
337       public void mouseEntered(MouseEvent e)
338       {
339         int j = combo.getSelectedIndex();
340         if (j > -1)
341         {
342           combo.setToolTipText(tooltips.get(j));
343         }
344       }
345       @Override
346       public void mouseExited(MouseEvent e)
347       {
348         combo.setToolTipText(null);
349       }
350     };
351     for (Component c : combo.getComponents())
352     {
353       c.addMouseListener(mouseListener);
354     }
355     return combo;
356   }
357
358   /**
359    * A helper method to build a drop-down choice of values, with tooltips for the
360    * entries
361    * 
362    * @param entries
363    * @param tooltips
364    */
365   public static JComboBox<IntKeyStringValueEntry> buildIntKeyStringValueComboWithTooltips(
366           List<IntKeyStringValueEntry> entries, List<String> tooltips)
367   {
368     JComboBox<IntKeyStringValueEntry> combo = new JComboBox<>();
369     final ComboBoxTooltipRenderer renderer = new ComboBoxTooltipRenderer();
370     combo.setRenderer(renderer);
371     for (IntKeyStringValueEntry attName : entries)
372     {
373       combo.addItem(attName);
374     }
375     renderer.setTooltips(tooltips);
376     final MouseAdapter mouseListener = new MouseAdapter()
377     {
378       @Override
379       public void mouseEntered(MouseEvent e)
380       {
381         int j = combo.getSelectedIndex();
382         if (j > -1)
383         {
384           combo.setToolTipText(tooltips.get(j));
385         }
386       }
387
388       @Override
389       public void mouseExited(MouseEvent e)
390       {
391         combo.setToolTipText(null);
392       }
393     };
394     for (Component c : combo.getComponents())
395     {
396       c.addMouseListener(mouseListener);
397     }
398     return combo;
399   }
400
401   /**
402    * Adds a titled border to the component in the default font and position (top
403    * left), optionally witht italic text
404    * 
405    * @param comp
406    * @param title
407    * @param italic
408    */
409   public static TitledBorder createTitledBorder(JComponent comp,
410           String title, boolean italic)
411   {
412     Font font = comp.getFont();
413     if (italic)
414     {
415       font = new Font(font.getName(), Font.ITALIC, font.getSize());
416     }
417     Border border = BorderFactory.createTitledBorder("");
418     TitledBorder titledBorder = BorderFactory.createTitledBorder(border,
419             title, TitledBorder.LEADING, TitledBorder.DEFAULT_POSITION,
420             font);
421     comp.setBorder(titledBorder);
422
423     return titledBorder;
424   }
425
426 }