是否可以在
Color
中使用JLabel
十六进制,例如#02f7fc
?
我想使用 A-F 颜色。使用 label.setForeground(Color.(BLUE/RED/BLACK/…);
太无聊了。
以下应该允许您使用解码方法使用十六进制设置颜色。
label.setForeground(Color.decode("#FFFF00"));
javafx.scene.paint.Color
转换为java.awt.Color
。
private static Color awtColor(javafx.scene.paint.Color fxColor) {
return new Color(
(float) fxColor.getRed(),
(float) fxColor.getGreen(),
(float) fxColor.getBlue(),
(float) fxColor.getOpacity());
}
通过合适的
import
语句,您就可以利用 JavaFX Color
API。此示例使用 Color.web()
创建“使用 HTML 或 CSS 属性字符串指定的 RGB 颜色。”
import static javafx.scene.paint.Color.web;
…
label.setForeground(awtColor(web("0xF0F8FF"))); // ALICEBLUE
label.setForegroundn(awtColor(web("AliceBlue"))); // #F0F8FF
正如@Andrew所说,你可以使用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);
});
}
}
如果你想使用它作为背景,那么你可以这样做:
label.setBackground(Color.decode("#02f7fc"))
您还可以通过以下方式设置颜色:
label.setBackground(new Color(0x02f7fc))