JColorChooser改变Java中的字体颜色

时间:2014-02-13 05:28:04

标签: java swing event-handling jcolorchooser

如何使用JColorChooser更改java swing中的字体颜色?

2 个答案:

答案 0 :(得分:1)

     import java.awt.*;
     import java.awt.event.*;
     import javax.swing.*;



    public class JColorChooserExample extends JFrame
                                       implements ActionListener
     {


    private JButton b;
    private Container c;
    private Color color;

   public JColorChooserExample(String title)
    {
      super(title);

      color = Color.pink;
       c = getContentPane();
       c.setLayout(new FlowLayout());
      c.setBackground(color);

       c.add(new JLabel(
          "Click button to select a new background color"));
       b = new JButton("Color");
       b.setToolTipText("Click here to change color");
       b.addActionListener(this);
       c.add(b);

      addWindowListener(new MyWindowCloser());
    }

    public void actionPerformed(ActionEvent e)
    {
      color = JColorChooser.showDialog(
                  this, "Select a Background Color", color);
      if (color != null)
       {
           c.setBackground(color);
       }
    }

    public static void main(String[] args)
    {
       JColorChooserExample jcce =
           new JColorChooserExample("JColorChooser Example");
       jcce.pack();
       jcce.setVisible(true);
    }
 }

并阅读此tutorial

答案 1 :(得分:0)

以下是创建JColorChooser实例并将其添加到容器的示例中的代码:

public class ColorChooserDemo extends JPanel ... {
public ColorChooserDemo() {
    super(new BorderLayout());
    banner = new JLabel("Welcome to the Tutorial Zone!",
                        JLabel.CENTER);
    banner.setForeground(Color.yellow);
    . . .
    tcc = new JColorChooser(banner.getForeground());
    . . .
    add(tcc, BorderLayout.PAGE_END);
}

以下代码注册并实现了更改侦听器:

tcc.getSelectionModel().addChangeListener(this);
. . .

public void stateChanged(ChangeEvent e) {
Color newColor = tcc.getColor();
banner.setForeground(newColor);
}