JAL-3058 refactored raising JColorChooser for JS compatibility
[jalview.git] / src / jalview / gui / JalviewColourChooser.java
1 package jalview.gui;
2
3 import jalview.gui.JalviewColourChooser.ColourChooserListener;
4
5 import java.awt.Color;
6 import java.awt.Component;
7 import java.awt.event.ActionEvent;
8 import java.awt.event.ActionListener;
9
10 import javax.swing.JColorChooser;
11 import javax.swing.JComponent;
12 import javax.swing.JDialog;
13 import javax.swing.JPanel;
14
15 /**
16  * A helper class that shows a JColorChooser and passes the selected colour back
17  * to a listener
18  */
19 public class JalviewColourChooser
20 {
21   public interface ColourChooserListener
22   {
23     void colourSelected(Color c);
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 al = new ActionListener()
45     {
46       @Override
47       public void actionPerformed(ActionEvent e)
48       {
49         listener.colourSelected(colorChooser.getColor());
50       };
51     };
52     JDialog dialog = JColorChooser.createDialog(parent, title, true,
53             colorChooser, al, null);
54     dialog.setVisible(true);
55   }
56
57   /**
58    * A convenience method that shows a colour chooser, with initial colour the
59    * background of the given 'paintable', and updates its background colour and
60    * repaints it after a colour selection is made
61    * 
62    * @param parent
63    * @param title
64    * @param paintable
65    */
66   public static void showColourChooser(Component parent, String title,
67           JComponent paintable)
68   {
69     ColourChooserListener listener = new ColourChooserListener()
70     {
71       @Override
72       public void colourSelected(Color c)
73       {
74         paintable.setBackground(c);
75         paintable.repaint();
76       }
77     };
78     JalviewColourChooser.showColourChooser(parent, title,
79             paintable.getBackground(), listener);
80   }
81 }