[英]How can I change the foreground color of a text based on the background it is on?
I have a JCheckbox
,this is in a JPanel
, that is supposed to show an image in the JPanel
, when you select it.我有一个
JCheckbox
,这是一个JPanel
,是应该显示的图像JPanel
,当你选择它。 The problem is this: as you can see in the screenshot, the text of the JCheckbox
is difficult to read because of the image.问题是:正如您在屏幕截图中看到的,
JCheckbox
的文本由于图像而难以阅读。
I was thinking if there was some way to contrast the text to the image, so that the color of the text is the opposite of the image.我在想是否有某种方法可以将文本与图像进行对比,使文本的颜色与图像相反。
I know that there're other ways to fix it, like setting the JCheckbox
outside the image, but I'd have to change design of my program and structure code.我知道还有其他方法可以修复它,例如在图像外设置
JCheckbox
,但我必须更改程序和结构代码的设计。
For example, here's how I want it to look:例如,这是我希望它的外观:
.
.
This is all the code that the JCheckBox
currently has, it is something simple:这是
JCheckBox
当前拥有的所有代码,很简单:
final JCheckBox INFO_IMG = new JCheckBox("Ver img");
INFO_IMG.setFont(new Font("Dialog", 0, 12));
INFO_IMG.setBounds(-2, 2, 78, 13);
INFO_IMG.setOpaque(false);
INFO_IMG.setFocusable(false);
INFO_IMG.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(final ItemEvent ie) {
if (1 == ie.getStateChange()) {
INFO_IMG.setText("Ver info");
IMG.setVisible(true);
/* INFO_IMG.setForegound(ROBOT.getPixelColor(
(int)INFO_IMG.getLocationOnScreen.getX() + 12
,(int) INFO_IMG.getLocationOnScreen().getY() + 10));
This is another way that I had thought of,
although it does not work well,would also have to get
the opposite color from the one return.
*/
} else {
INFO_IMG.setText("Ver img");
IMG.setVisible(false);
}
}
});
add(INFO_IMG);
Well, I have found this way to do it, but unfortunately it only works for black and white, can you think of other ways?嗯,我已经找到了这种方法,但不幸的是它只适用于黑白,你能想到其他方法吗?
Public Color contrast(Image image) {
BufferedImage buffered = toBufferedImage(image);
int black = 0, white = 0;
for (int x = 0; x < buffered.getWidth(); x++) {
for (int y = 0; y < buffered.getHeight(); y++) {
if(buffered.getRGB(x, y) == Color.BLACK.getRGB()) {
black++;
}else {
white++;
}
}
}
System.out.println("Blanco: " + white + ", Negro: " + black);
return (white > black) ? Color.BLACK : Color.WHITE;
}
private BufferedImage toBufferedImage(Image image) {
int width = image.getWidth(null);
int height = image.getHeight(null);
int argb = BufferedImage.TYPE_BYTE_BINARY;
BufferedImage buffered = new BufferedImage(width, height, argb);
Graphics2D g2 = buffered.createGraphics();
g2.drawImage(image, 0, 0, null);
g2.dispose();
// JOptionPane.showMessageDialog(null, new ImageIcon(buffered));
return buffered;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.