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