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