Java Tutorial/Swing/JColorChooser

Материал из Java эксперт
Перейти к: навигация, поиск

Adding a Custom Color Chooser Panel to a JColorChooser Dialog

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.colorchooser.AbstractColorChooserPanel;
public class Main {
  public static void main(String[] argv) {
    JColorChooser chooser = new JColorChooser();
    chooser.addChooserPanel(new MyChooserPanel());
  }
}
class MyChooserPanel extends AbstractColorChooserPanel {
  public void buildChooser() {
    setLayout(new GridLayout(0, 3));
    makeAddButton("Red", Color.red);
    makeAddButton("Green", Color.green);
    makeAddButton("Blue", Color.blue);
  }
  public void updateChooser() {
  }
  public String getDisplayName() {
    return "MyChooserPanel";
  }
  public Icon getSmallDisplayIcon() {
    return null;
  }
  public Icon getLargeDisplayIcon() {
    return null;
  }
  private void makeAddButton(String name, Color color) {
    JButton button = new JButton(name);
    button.setBackground(color);
    button.setAction(setColorAction);
    add(button);
  }
  Action setColorAction = new AbstractAction() {
    public void actionPerformed(ActionEvent evt) {
      JButton button = (JButton) evt.getSource();
      getColorSelectionModel().setSelectedColor(button.getBackground());
    }
  };
}





Changing the Color Chooser Panels

  1. Create your own by subclassing the AbstractColorChooserPanel class.
  2. To add a new panel to the existing set, call: public void addChooserPanel(AbstractColorChooserPanel panel)
  3. To remove it: public AbstractColorChooserPanel removeChooserPanel(AbstractColorChooserPanel panel)
  4. To replace the existing set of panels: setChooserPanels(AbstractColorChooserPanel panels[ ])



public abstract class AbstractColorChooserPanel extends JPanel {
  public AbstractColorChooserPanel();
  protected abstract void buildChooser();
  protected Color getColorFromModel();
  public ColorSelectionModel getColorSelectionModel();
  public int getDisplayMnemonicIndex();
  public abstract String getDisplayName();
  public abstract Icon getLargeDisplayIcon();
  public int getMnemonic();
  public abstract Icon getSmallDisplayIcon();
  public void installChooserPanel(JColorChooser);
  public void paint(Graphics);
  public void uninstallChooserPanel(JColorChooser);
  public abstract void updateChooser();
}





Choose foreground or background color

/*
 * Created on 17.12.2004
 *
 */
/*
This file is part of BORG.
    BORG is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.
    BORG is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
    You should have received a copy of the GNU General Public License
    along with BORG; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
Copyright 2003 by Mike Berger
 */

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;

/**
 * GUI control to easy choose foreground or background color.
 * Indicates color to be stored by its own foreground or background.
 * 
 * @author bsv
 * 
 */
public class JButtonKnowsBgColor extends JButton {
  // colorProperty is ONE color, but can be indicated by fore or back color
  protected Color colorProperty;
  // bg=true means "choosed color is background color"
  // bg=false means "choosed color is foreground color"
  protected boolean bg;
  
  public JButtonKnowsBgColor( String p_text, Color p_color, boolean p_bg ){
    setText( p_text );
    setColorProperty( p_color );
    setBg( p_bg );
    setColorByProperty();
    addActionListener(new ModalListener());
        
  }
  
  public void setColorByProperty(){
    if( isBg() ){
      setBackground( getColorProperty() );
    } else {
      setForeground( getColorProperty() );
    }
  }
  // for testing purposes only
  public static void main(String[] args) {
    JButtonKnowsBgColor jbkbc = new JButtonKnowsBgColor( "choose back", Color.RED, true );
    JButtonKnowsBgColor jbkbc1 = new JButtonKnowsBgColor( "choose fore", Color.BLUE, false );
    JFrame jf = new JFrame();
    jf.setLayout( new BorderLayout() );
    jf.getContentPane().add( jbkbc, BorderLayout.NORTH );
    jf.getContentPane().add( jbkbc1, BorderLayout.CENTER );
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jf.setSize( 100, 200 );
    jf.setVisible(true);
  }
  /**
   * @return Returns the color.
   */
  public Color getColorProperty() {
    return colorProperty;
  }
  /**
   * @param color The color to set.
   */
  public void setColorProperty(Color color) {
    this.colorProperty = color;
  }
  /**
   * @return Returns the bg.
   */
  protected boolean isBg() {
    return bg;
  }
  /**
   * @param bg The bg to set.
   */
  protected void setBg(boolean bg) {
    this.bg = bg;
  }
  private class ModalListener implements ActionListener{
    public void actionPerformed(ActionEvent event){
      Color selected = JColorChooser.showDialog(
        null, 
        isBg()?"Set background":"Set foreground", 
        getColorProperty());
      setColorProperty(selected);
      setColorByProperty();
      }
   }
}





Creating a JColorChooser Dialog

import java.awt.Color;
import javax.swing.JColorChooser;
public class Main {
  public static void main(String[] argv) {
    Color initialColor = Color.red;
    Color newColor = JColorChooser.showDialog(null, "Dialog Title", initialColor);
  }
}





Creating and Showing a JColorChooser Pop-Up Window

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
public class ColorSamplePopup {
  public static void main(String args[]) {
    JFrame frame = new JFrame("JColorChooser Sample Popup");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final JButton button = new JButton("Pick to Change Background");
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        Color initialBackground = button.getBackground();
        Color background = JColorChooser.showDialog(null, "Change Button Background",
            initialBackground);
        if (background != null) {
          button.setBackground(background);
        }
      }
    };
    button.addActionListener(actionListener);
    frame.add(button, BorderLayout.CENTER);
    frame.setSize(300, 100);
    frame.setVisible(true);
  }
}





Customizing Action Listeners on JColorChooser Buttons

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
public class CreateColorSamplePopup {
  public static void main(String args[]) {
    final JColorChooser colorChooser = new JColorChooser(Color.RED);
    ActionListener okActionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        System.out.println("Color change rejected");
      }
    };
    // For cancel selection, change button background to red
    ActionListener cancelActionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        System.out.println("cancled");
      }
    };
    final JDialog dialog = JColorChooser.createDialog(null, "Change Button Background", true,
        colorChooser, okActionListener, cancelActionListener);
    dialog.setVisible(true);
  }
}





Customizing a JColorChooser Look and Feel

Property StringObject TypeColorChooser.backgroundColorColorChooser.cancelTextStringColorChooser.fontFontColorChooser.foregroundColorColorChooser.hsbBlueTextStringColorChooser.hsbBrightnessTextStringColorChooser.hsbDisplayedMnemonicIndexIntegerColorChooser.hsbGreenTextStringColorChooser.hsbHueTextStringColorChooser.hsbMnemonicIntegerColorChooser.hsbNameTextStringColorChooser.hsbRedTextStringColorChooser.hsbSaturationTextStringColorChooser.okTextStringColorChooser.panelsAbstractColorChooserPanel[ ]ColorChooser.previewTextStringColorChooser.resetMnemonicIntegerColorChooser.resetTextStringColorChooser.rgbBlueDisplayedMnemonicIndexIntegerColorChooser.rgbBlueMnemonicIntegerColorChooser.rgbBlueTextStringColorChooser.rgbGreenDisplayedMnemonicIndexIntegerColorChooser.rgbGreenMnemonicIntegerColorChooser.rgbGreenTextStringColorChooser.rgbMnemonicIntegerColorChooser.rgbNameTextStringColorChooser.rgbRedDisplayedMnemonicIndexIntegerColorChooser.rgbRedMnemonicIntegerColorChooser.rgbRedTextStringColorChooser.sampleTextStringColorChooser.showPreviewPanelTextBooleanColorChooser.swatchesDefaultRecentColorColorColorChooser.swatchesDisplayedMnemonicIndexIntegerColorChooser.swatchesMnemonicIntegerColorChooser.swatchesNameTextStringColorChooser.swatchesRecentSwatchSizeDimensionColorChooser.swatchesRecentTextStringColorChooser.swatchesSwatchSizeDimensionColorChooserUIString


Customizing the Preview Panel of a JColorChooser Dialog

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JColorChooser;
import javax.swing.JComponent;
import javax.swing.colorchooser.ColorSelectionModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Main {
  public static void main(String[] argv) {
    JColorChooser chooser = new JColorChooser();
    final MyPreviewPanel pre = new MyPreviewPanel(chooser);
    chooser.setPreviewPanel(pre);
    
    ColorSelectionModel model = chooser.getSelectionModel();
    model.addChangeListener(new ChangeListener() {
      public void stateChanged(ChangeEvent evt) {
        ColorSelectionModel model = (ColorSelectionModel) evt.getSource();
        pre.curColor = model.getSelectedColor();
      }
    });
 
    
  }
}
class MyPreviewPanel extends JComponent {
  Color curColor;
  public MyPreviewPanel(JColorChooser chooser) {
    curColor = chooser.getColor();
    
    setPreferredSize(new Dimension(50, 50));
  }
  public void paint(Graphics g) {
    g.setColor(curColor);
    g.fillRect(0, 0, getWidth() - 1, getHeight() - 1);
  }
}





Display Color chooser dialog

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
public class ColorSample {
  public static void main(String args[]) {
    JFrame f = new JFrame("JColorChooser Sample");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final JButton button = new JButton("Pick to Change Background");
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        Color initialBackground = button.getBackground();
        Color background = JColorChooser.showDialog(null, "JColorChooser Sample", initialBackground);
        if (background != null) {
          button.setBackground(background);
        }
      }
    };
    button.addActionListener(actionListener);
    f.add(button, BorderLayout.CENTER);
    f.setSize(300, 200);
    f.setVisible(true);
  }
}





Dragging-and-Dropping Colors Across JColorChooser Components

import java.awt.BorderLayout;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
public class DoubleColor {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Double Color Choosers");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JColorChooser left = new JColorChooser();
    left.setDragEnabled(true);
    frame.add(left, BorderLayout.WEST);
    JColorChooser right = new JColorChooser();
    right.setDragEnabled(true);
    frame.add(right, BorderLayout.EAST);
    frame.pack();
    frame.setVisible(true);
  }
}





Getting and Setting the Selected Color in a JColorChooser Dialog

import java.awt.Color;
import javax.swing.JColorChooser;
public class Main {
  public static void main(String[] argv) {
    JColorChooser chooser = new JColorChooser();
    // Set the selected color
    chooser.setColor(Color.red);
    // Get current selected color
    Color color = chooser.getColor();
  }
}





JColorChooser with custom preview panel

  1. To turn off the preview panel, change the previewPanel to a not-null component.
  2. When the property is set to null, the default preview panel for the look and feel is shown.
  3. Setting the property to an empty JPanel serves the purpose of not showing the preview panel.



import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class JColorChooserWithCustomPreviewPanel {
  public static void main(String[] a) {
    final JLabel previewLabel = new JLabel("I Love Swing", JLabel.CENTER);
    previewLabel.setFont(new Font("Serif", Font.BOLD | Font.ITALIC, 48));
    previewLabel.setSize(previewLabel.getPreferredSize());
    previewLabel.setBorder(BorderFactory.createEmptyBorder(0,0,1,0));
    
    JColorChooser colorChooser = new JColorChooser();
    colorChooser.setPreviewPanel(previewLabel);
    JDialog d = colorChooser.createDialog(null,"",true,colorChooser,null,null);
    
    d.setVisible(true);
  }
}





Linking JColorChooser with component"s color

import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class JColorChooserSample {
  public static void main(String args[]) {
    JFrame frame = new JFrame("JColorChooser Popup");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final JLabel label = new JLabel("www.jexp.ru", JLabel.CENTER);
    label.setFont(new Font("Serif", Font.BOLD | Font.ITALIC, 48));
    frame.add(label, BorderLayout.SOUTH);
    final JColorChooser colorChooser = new JColorChooser(label.getBackground());
    colorChooser.setBorder(BorderFactory.createTitledBorder("Pick Foreground Color"));
    frame.add(colorChooser, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
  }
}





Listening for OK and Cancel Events in a JColorChooser Dialog

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
public class Main {
  public static void main(String[] argv) {
    final JColorChooser chooser = new JColorChooser();
    ActionListener okListener = new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        Color newColor = chooser.getColor();
      }
    };
    ActionListener cancelListener = new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        Color newColor = chooser.getColor();
      }
    };
    boolean modal = false;
    JDialog dialog = JColorChooser.createDialog(null, "Dialog Title", modal, chooser, okListener,
        cancelListener);
    dialog.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent evt) {
        Color newColor = chooser.getColor();
      }
    });
  }
}





Listening to Color Selection Changes

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.colorchooser.ColorSelectionModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class ListeningJColorChooserSample {
  public static void main(String args[]) {
    JFrame frame = new JFrame("JColorChooser Popup");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final JLabel label = new JLabel("www.jexp.ru", JLabel.CENTER);
    label.setFont(new Font("Serif", Font.BOLD | Font.ITALIC, 48));
    frame.add(label, BorderLayout.SOUTH);
    final JColorChooser colorChooser = new JColorChooser(label.getBackground());
    ColorSelectionModel model = colorChooser.getSelectionModel();
    ChangeListener changeListener = new ChangeListener() {
      public void stateChanged(ChangeEvent changeEvent) {
        Color newForegroundColor = colorChooser.getColor();
        label.setForeground(newForegroundColor);
      }
    };
    model.addChangeListener(changeListener);
    frame.add(colorChooser, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
  }
}





Preview pane simply displays the currently selected color.

class MyPreviewPane extends JLabel{
  Color curColor;
  public MyPreviewPane(JColorChooser chooser) {
    curColor = chooser.getColor();
    ColorSelectionModel model = chooser.getSelectionModel();
    model.addChangeListener(new ChangeListener() {
      public void stateChanged(ChangeEvent evt) {
        ColorSelectionModel model = (ColorSelectionModel) evt.getSource();
        curColor = model.getSelectedColor();
      }
    });
    setPreferredSize(new Dimension(50, 50));
  }
  public void paint(Graphics g) {
    g.setColor(curColor);
    g.fillRect(0, 0, getWidth() - 1, getHeight() - 1);
  }
}





Removing a Color Chooser Panel from a JColorChooser Dialog

import javax.swing.JColorChooser;
import javax.swing.colorchooser.AbstractColorChooserPanel;
public class Main {
  public static void main(String[] argv) {
    JColorChooser chooser = new JColorChooser();
    AbstractColorChooserPanel[] oldPanels = chooser.getChooserPanels();
    for (int i = 0; i < oldPanels.length; i++) {
      String clsName = oldPanels[i].getClass().getName();
      if (clsName.equals("javax.swing.colorchooser.DefaultSwatchChooserPanel")) {
        chooser.removeChooserPanel(oldPanels[i]);
      } else if (clsName.equals("javax.swing.colorchooser.DefaultRGBChooserPanel")) {
        chooser.removeChooserPanel(oldPanels[i]);
      } else if (clsName.equals("javax.swing.colorchooser.DefaultHSBChooserPanel")) {
        chooser.removeChooserPanel(oldPanels[i]);
      }
    }
  }
}





Removing the Preview Panel from a JColorChooser Dialog

import javax.swing.JColorChooser;
import javax.swing.JPanel;
public class Main {
  public static void main(String[] argv) {
    JColorChooser chooser = new JColorChooser();
    chooser.setPreviewPanel(new JPanel());
  }
}





Retrieving the Color Chooser Panels in a JColorChooser Dialog

import javax.swing.JColorChooser;
import javax.swing.colorchooser.AbstractColorChooserPanel;
public class Main {
  public static void main(String[] argv) {
    JColorChooser chooser = new JColorChooser();
    findPanel(chooser, "javax.swing.colorchooser.DefaultSwatchChooserPanel");
    findPanel(chooser, "javax.swing.colorchooser.DefaultHSBChooserPanel");
    findPanel(chooser, "javax.swing.colorchooser.DefaultRGBChooserPanel");
  }
  public static AbstractColorChooserPanel findPanel(JColorChooser chooser, String name) {
    AbstractColorChooserPanel[] panels = chooser.getChooserPanels();
    for (int i = 0; i < panels.length; i++) {
      String clsName = panels[i].getClass().getName();
      if (clsName.equals(name)) {
        return panels[i];
      }
    }
    return null;
  }
}





Setting the Order of the Color Chooser Panel Tabs in a JColorChooser Dialog

import javax.swing.JColorChooser;
import javax.swing.colorchooser.AbstractColorChooserPanel;
public class Main {
  public static void main(String[] argv) {
    JColorChooser chooser = new JColorChooser();
    int numPanels = chooser.getChooserPanels().length;
    AbstractColorChooserPanel[] newPanels = new AbstractColorChooserPanel[numPanels];
    newPanels[0] = findPanel(chooser, "javax.swing.colorchooser.DefaultHSBChooserPanel");
    newPanels[1] = findPanel(chooser, "javax.swing.colorchooser.DefaultRGBChooserPanel");
    newPanels[2] = findPanel(chooser, "javax.swing.colorchooser.DefaultSwatchChooserPanel");
    chooser.setChooserPanels(newPanels);
  }
  public static AbstractColorChooserPanel findPanel(JColorChooser chooser, String name) {
    AbstractColorChooserPanel[] panels = chooser.getChooserPanels();
    for (int i = 0; i < panels.length; i++) {
      String clsName = panels[i].getClass().getName();
      if (clsName.equals(name)) {
        return panels[i];
      }
    }
    return null;
  }
}





Use a Color Chooser

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ColorChooser_01 extends JFrame {
  private JLabel sampleText = new JLabel("Label");
  private JButton chooseButton = new JButton("Choose Color");
  public static void main(String[] args) {
    new ColorChooser_01();
  }
  public ColorChooser_01() {
    this.setSize(300, 100);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel1 = new JPanel();
    sampleText.setBackground(null);
    panel1.add(sampleText);
    chooseButton.addActionListener(new ButtonListener());
    panel1.add(chooseButton);
    this.add(panel1);
    this.setVisible(true);
  }
  private class ButtonListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      Color c = JColorChooser.showDialog(null, "Choose a Color", sampleText.getForeground());
      if (c != null)
        sampleText.setForeground(c);
    }
  }
}