d808ebd3e6ce9f9e94bef8008a075cdf59a8c51d
[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
26   /**
27    * Shows a colour chooser dialog with the given parent component, title, and
28    * (optionally) initially selected colour. The chosen colour is passed back to
29    * the listener. There is no action if the dialog is cancelled.
30    * 
31    * @param parent
32    * @param title
33    * @param initialColour
34    * @param listener
35    */
36   public static void showColourChooser(Component parent, String title,
37           Color initialColour, ColourChooserListener listener)
38   {
39     JColorChooser colorChooser = new JColorChooser();
40     if (initialColour != null)
41     {
42       colorChooser.setColor(initialColour);
43     }
44     ActionListener onChoose = evt -> listener
45             .colourSelected(colorChooser.getColor());
46     ActionListener onCancel = evt -> listener.cancel();
47     JDialog dialog = JColorChooser.createDialog(parent, title, true,
48             colorChooser, onChoose, onCancel);
49     dialog.setVisible(true);
50   }
51
52   /**
53    * A convenience method that shows a colour chooser, with initial colour the
54    * background of the given 'paintable', and updates its background colour and
55    * repaints it after a colour selection is made
56    * 
57    * @param parent
58    * @param title
59    * @param paintable
60    */
61   public static void showColourChooser(Component parent, String title,
62           JComponent paintable)
63   {
64     ColourChooserListener listener = new ColourChooserListener()
65     {
66       @Override
67       public void colourSelected(Color c)
68       {
69         paintable.setBackground(c);
70         paintable.repaint();
71       }
72     };
73     JalviewColourChooser.showColourChooser(parent, title,
74             paintable.getBackground(), listener);
75   }
76 }