首页 > 解决方案 > 如何根据文本所在的背景更改文本的前景色?

问题描述

我有一个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);

标签: javaswingawtjlabel

解决方案


嗯,我找到了这种方法,可惜它只适用于黑白,你能想到其他方法吗?


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;
}

推荐阅读