Is it possible to use Color hex in JLabel such as #02f7fc?
I want to use A-F colors. Using label.setForeground(Color.(BLUE/RED/BLACK/…); is so boring.
The following should allow you to set the colour using hex with the use of the decode method.
label.setForeground(Color.decode("#FFFF00"));
As @Andrew said, you can use a new Color(int rgb):
import java.awt.*;
import javax.swing.*;
public class HexColorTest {
public JComponent makeUI() {
JPanel p = new JPanel();
p.add(makeLabel(new Color(0xff0000)));
p.add(makeLabel(new Color(Integer.parseInt("#00ff00".substring(1), 16))));
p.add(new JLabel("<html><span style='color: #0000ff'>#0000ff"));
return p;
}
private static JLabel makeLabel(Color c) {
JLabel label = new JLabel(String.format("#%06x", c.getRGB() & 0xffffff));
label.setForeground(c);
return label;
}
public static void main(String... args) {
EventQueue.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new HexColorTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With