Colors And
Fonts
Instructions: 1. Keep clicking on the panel to
generate random images.
Complete Source
Code
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ColorsAndFonts {
public static class
DPanel extends
JPanel {
int red, green, blue, f, x, y;
String s1;
Font font0 = new
Font("Courier",Font.BOLD, 36);
Font font1 = new
Font("Times New Roman", Font.PLAIN, 20);
Font font2 = new
Font("Ariel", Font.BOLD, 26);
Font font3 = new
Font("Times New Roman", Font.ITALIC, 60);
Font[] fonts =
{font0,font1,font2,font3};
public void
paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 1; i <= 50; i++) {
red = (int) Math.round(255*Math.random());
green = (int) Math.round(255*Math.random());
blue = (int) Math.round(255*Math.random());
Color color = new Color(red,green,blue);
f = (int) Math.round(3*Math.random());
x = (int) Math.round(450*Math.random());
y = (int) Math.round(450*Math.random());
g.setColor(color);
g.setFont(fonts[f]);
g.drawString(s1,x,y);
}
}
public DPanel(String
s1) {
this.s1 = s1;
}
public DPanel()
{
s1 = "Java!";
}
}
public static class
EventHandler implements
MouseListener {
public void
mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent
e) {
Component source = (Component) e.getSource();
source.repaint();
}
public void
mouseClicked(MouseEvent e) {}
public void
mouseEntered(MouseEvent e) {}
public void
mouseExited(MouseEvent e) {}
}
public static void
main(String[] args) {
DPanel myPanel =
new DPanel("Dilip");
myPanel.setBackground(Color.BLACK);
EventHandler
listener = new EventHandler();
myPanel.addMouseListener(listener);
JFrame window =
new JFrame("Colors and Fonts");
window.add(myPanel);
window.setSize(500,500);
window.setLocation(100,100);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
}
|