// MyPanel2.java // -- extends MyPanel1.java to show the use of colors /** * We further elaborate on MyPanel1 to show colors. * The 13 standard colors are: * black, blue, cyan, darkGray * gray, green, lightGray, magenta * orange, pink, red, white, yellow * Thus, before any drawing actions, you can set * the color by calling * g.setColor(Color.pink); * You can also synthesize your own color with * Color(int R, int G, int B) * E.g., * g.setColor(new Color(0, 128, 255)); * You can make a current color brighter or darker: * c.brighter().brighter(); * c.darker(); * Other useful methods are: * JFrame f = new MyFrame(); * f.setBackground(Color.white); * f.setForeground(Color.lightGray); * f.show(); **/ import java.awt.*; import java.awt.event.*; import javax.swing.*; // text panel class textPanel extends JPanel { // override the paintComponent method // THIS IS THE MAIN DEMO OF THIS EXAMPLE public void paintComponent(Graphics g) { super.paintComponent(g); Font f = new Font("SansSerif", Font.BOLD, 14); FontMetrics fm = g.getFontMetrics(f); g.setFont(f); g.setColor(Color.magenta); int cx = 75; int cy = 100; g.drawString("Hello, ", cx, cy); cx += fm.stringWidth("Hello, "); g.setColor(new Color(64, 128, 0)); //dull green g.drawString("World!", cx, cy); } //paintComponent } //class textPanel class MyFrame extends JFrame { public MyFrame() { // Frame Parameters setTitle("My Color Frame"); setSize(300,200); // default size is 0,0 setLocation(10,200); // default is 0,0 (top left corner) setBackground(Color.yellow); // shown briefly, then replaced by Grey. setForeground(Color.pink); // when is this shown??? // Window Listeners addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } //windowClosing }); //addWindowLister // Add Panels Container contentPane = getContentPane(); contentPane.add(new textPanel()); } //constructor MyFrame } //class MyFrame public class MyPanel2 { public static void main(String[] args) { JFrame f = new MyFrame(); f.show(); } //main } //class MyPanel2 /* NOTES: * The class SystemColor has various color elements * for the entire desktop: thus we can use "SystemColor.XXX" * where XXX= * desktop (Background color of desktop) * activeCaption * activeCaptionText * activeCaptionBorder * inactiveCaption, etc * window (Background for windows) * windowBorder * windowText * menu * menuText * ... */