Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use Color Hex in JLabel like #02f7fc?

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.

like image 438
Rborn Aries Avatar asked Oct 16 '25 15:10

Rborn Aries


2 Answers

The following should allow you to set the colour using hex with the use of the decode method.

label.setForeground(Color.decode("#FFFF00"));
like image 142
Chains Avatar answered Oct 18 '25 05:10

Chains


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);
    });
  }
}
like image 34
aterai Avatar answered Oct 18 '25 03:10

aterai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!