Java Example Program / Sample Source Code
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class DrawColor {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(new CustomComponent());
frame.setSize(350, 350);
frame.setVisible(true);
}
}
class CustomComponent extends JComponent {
private static final long serialVersionUID = 7810714503460777765L;
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
// Using predefined color
g2d.setColor(Color.red);
g2d.fill(new Rectangle(25, 25, 200, 200));
// Using custom color
int red = 230;
int green = 45;
int blue = 67;
g2d.setColor(new Color(red, green, blue));
g2d.fill(new Rectangle(45, 45, 200, 200));
}
} |
|
|