如何使用 JColorChooser 在 java swing 中更改字体颜色?
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);
}
}
并阅读本教程
下面是创建 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);
}