字体问题要改变

时间:2014-02-15 09:05:45

标签: java user-interface fonts

嗨iam尝试做一些允许我改变字体颜色的程序,所以如果我使用了一个复选框,但问题是颜色的组合。我可以组合两种颜色,使其成为我的字体的颜色吗?

Font font = new Font("Arial", Font.BOLD, 12);
                field.setFont(font);
                field.setForeground(Color.YELLOW);// can i do this Color.YELLOW+GREEN ?

1 个答案:

答案 0 :(得分:1)

为什么不呢?

import java.awt.Color;
import java.awt.Font;
import javax.swing.*;        

public class Example {
    private static void createAndShowGUI() {
        JFrame frame = new JFrame("HelloColorfulWorld");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Font font = new Font("Arial", Font.BOLD, 12);

        Color yellowColor = new Color(255, 255, 0); // Yellow  
        Color greenColor = new Color(0, 255, 0); // Green

        Color mixColor = mixTwoColors(yellowColor, greenColor); // Yellow + Green

        JLabel label = new JLabel("Hello, Colorful World!");

        label.setFont(font);
        label.setForeground(mixColor);
        frame.getContentPane().add(label);

        frame.pack();
        frame.setVisible(true);
    }

    public static Color mixTwoColors(Color color1, Color color2) {
        double alpha = color1.getAlpha() + color2.getAlpha();

        double weight1 = color1.getAlpha() / alpha;
        double weight2 = color2.getAlpha() / alpha;

        double r = weight1 * color1.getRed() + weight2 * color2.getRed();
        double g = weight1 * color1.getGreen() + weight2 * color2.getGreen();
        double b = weight1 * color1.getBlue() + weight2 * color2.getBlue();

        double a = Math.max(color1.getAlpha(), color2.getAlpha());

        return new Color((int) r, (int) g, (int) b, (int) a);
    }    

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

enter image description here

有关您可以在那里找到的颜色操作的更多信息: