0

Hi iam trying to do some program that allowed me to change my font color so if i have used a check box but the problem is the combination of the color . can i combine two colors to make it the color of my font ?

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

1 Answers1

1

Why not?

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

More information about operations with colors you can find there:

Community
  • 1
  • 1
  • oh sir how did you do to combine that ? and where did you get the numbers in new colors like (154,205,50); ? – Batusai Feb 15 '14 at 09:44