如何在Java swing中使用JColorChooser更改字体颜色?
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);
}
}
And read this tutorial also
Here is the code from the example that creates a JColorChooser instance and adds it to a container:
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);
}
The following code registers and implements the change listener:
tcc.getSelectionModel().addChangeListener(this);
. . .
public void stateChanged(ChangeEvent e) {
Color newColor = tcc.getColor();
banner.setForeground(newColor);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.