java - 如何根据文本所在的背景更改文本的前景色?
问题描述
我有一个JCheckbox
,这是在一个,当你选择它时,它JPanel
应该在 中显示一个图像。JPanel
问题是这样的:正如您在屏幕截图中看到的那样,JCheckbox
由于图像的原因,文本很难阅读。
我在想是否有某种方法可以将文本与图像进行对比,以使文本的颜色与图像相反。
我知道还有其他方法可以修复它,比如设置JCheckbox
图像的外部,但我必须改变我的程序和结构代码的设计。
例如,这是我希望它的外观:
.
这是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);
解决方案
嗯,我找到了这种方法,可惜它只适用于黑白,你能想到其他方法吗?
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;
}
推荐阅读
- ansible - 如何处理 Ansible 循环中的空列表
- c++ - 如何在 C++ 中检查声明的标识符?
- amazon-web-services - 使用 AWS CLI 命令创建 AWS QuickSight 资源
- python - 无法从网站 Python 获取 cookie
- typescript - 量角器外部的打字稿和异步初始化
- node.js - Vue.js | TypeError:无法读取未定义的属性“then”
- json - Chrome 扩展程序图标未出现
- python - sklearns OneHotEncoder 究竟是如何工作的?
- python - 使用 mpcalc 计算前沿生成时出错
- ruby-on-rails - Rails Webpacker 找不到模块(刚刚升级到 ROR 6.1)