您好,我正在尝试执行一些程序,允许我更改字体颜色,因此如果我使用了复选框,但问题是颜色的组合。我可以组合两种颜色使其成为我的字体颜色吗?
Font font = new Font("Arial", Font.BOLD, 12);
field.setFont(font);
field.setForeground(Color.YELLOW);// can i do this Color.YELLOW+GREEN ?
最佳答案
为什么不呢?
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();
}
});
}
}
有关颜色操作的更多信息,您可以在那里找到:
- RGB color model
- Computing the combined color of two colors (Over operator)
- Java: Operations with Colors (add, subtract)? - Colors in a constant class
- Convert RGB values into integer pixel
- Set Color as int value for use in setRGB(int x, int y, int rgb) method? — Java
- Algorithm for Additive Color Mixing for RGB Values
- Calculation of a mixed color in RGB
- Mixing two RGB color vectors to get resultant
- ...
关于java - 字体问题需要更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21795514/