Java Color使用更明亮的方法

时间:2012-08-27 15:47:58

标签: java awt

这有什么问题?我预计,如果我应用d = 30的颜色,它会比d = 0更亮。但事实并非如此。这里颜色应该从一个面板变为面板(我预期)。

package default;

import java.awt.Color;
import java.awt.Dimension;

import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class test
{
    public static void main(String[] args)
    {
        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        frame.getContentPane().add(panel);
        frame.setMinimumSize(new Dimension(600,100));
        panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));

        for(int i = 100; i > 0; i = i-10)
        {
            JPanel p = new JPanel();
            p.setPreferredSize(new Dimension(20,20));
            p.add(new JLabel(String.valueOf(i)));
            Double d = Double.valueOf(i);

            Color color = Color.red.brighter();
            while(d > 0)
            {
                color = color.brighter();
                d = d-5;
            }

            p.setBackground(color);
            panel.add(p);
        }

        frame.setVisible(true);
    }
}

1 个答案:

答案 0 :(得分:4)

Java的brighter()颜色算法假设如果R,G或B从0开始,则它保持为0.“没有百万倍,仍然没有。”

import java.awt.Color;

public class QuickTest {

    public static void brighten(Color color, int d) {
        System.out.println("brighten");
        while(d > 0)
        {
            System.out.println(color);
            color = color.brighter();
            d = d-1;
        }
        System.out.println(color);
    }

    public static void main(String[] args) throws Exception {
        int d = 3;
        brighten(Color.red,3);
        brighten(new Color(45,125,0),3);
        brighten(new Color(45,125,1),3);
    }
}

输出

brighten
java.awt.Color[r=255,g=0,b=0]
java.awt.Color[r=255,g=0,b=0]
java.awt.Color[r=255,g=0,b=0]
java.awt.Color[r=255,g=0,b=0]
brighten
java.awt.Color[r=45,g=125,b=0]
java.awt.Color[r=64,g=178,b=0]
java.awt.Color[r=91,g=254,b=0]
java.awt.Color[r=130,g=255,b=0]
brighten
java.awt.Color[r=45,g=125,b=1]
java.awt.Color[r=64,g=178,b=4]
java.awt.Color[r=91,g=254,b=5]
java.awt.Color[r=130,g=255,b=7]

更新

但并非总是......

brighten(new Color(0,0,0),3);

..生产:

brighten
java.awt.Color[r=0,g=0,b=0]
java.awt.Color[r=3,g=3,b=3]
java.awt.Color[r=4,g=4,b=4]
java.awt.Color[r=5,g=5,b=5]