6dc8a2bf10e4424164e5d806d06b3e32e3821784
[jalview.git] / src / jalview / gui / JalviewColourChooser.java
1 package jalview.gui;
2
3 import java.awt.Color;
4 import java.awt.Component;
5 import java.awt.event.ActionListener;
6
7 import javax.swing.JColorChooser;
8 import javax.swing.JComponent;
9 import javax.swing.JDialog;
10
11 /**
12  * A helper class that shows a JColorChooser and passes the selected colour back
13  * to a listener
14  */
15 public class JalviewColourChooser
16 {
17   public interface ColourChooserListener
18   {
19     void colourSelected(Color c);
20     
21     default void cancel() {};
22   }
23
24   /**
25    * Shows a colour chooser dialog with the given parent component, title, and
26    * (optionally) initially selected colour. The chosen colour is passed back to
27    * the listener. There is no action if the dialog is cancelled.
28    * 
29    * @param parent
30    * @param title
31    * @param initialColour
32    * @param listener
33    */
34   public static void showColourChooser(Component parent, String title,
35           Color initialColour, ColourChooserListener listener)
36   {
37     JColorChooser colorChooser = new JColorChooser();
38     if (initialColour != null)
39     {
40       colorChooser.setColor(initialColour);
41     }
42     ActionListener onChoose = evt -> listener.colourSelected(colorChooser.getColor());
43     ActionListener onCancel = evt -> listener.cancel();
44         JDialog dialog = JColorChooser.createDialog(parent, title, true, colorChooser,
45                 onChoose, onCancel);
46         dialog.setVisible(true);
47   }
48
49   /**
50    * A convenience method that shows a colour chooser, with initial colour the
51    * background of the given 'paintable', and updates its background colour and
52    * repaints it after a colour selection is made
53    * 
54    * @param parent
55    * @param title
56    * @param paintable
57    */
58   public static void showColourChooser(Component parent, String title,
59           JComponent paintable)
60   {
61     ColourChooserListener listener = new ColourChooserListener()
62     {
63       @Override
64       public void colourSelected(Color c)
65       {
66         paintable.setBackground(c);
67         paintable.repaint();
68       }
69     };
70     JalviewColourChooser.showColourChooser(parent, title,
71             paintable.getBackground(), listener);
72   }
73 }