|
| |
We can use the foreground color to change the color of text, and other
drawable items. Here's an example:
Note that we change the color for the Graphics object, not the panel!
package swingExamples;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JPanel;
class ColorTextDisplayPanel extends JPanel
{
public void paintComponent(Graphics g)
{
if (fm == null)
{
fm = g.getFontMetrics(f);
fim = g.getFontMetrics(fi);
}
String s1 = "Greetings from ";
String s2 = "JavaLand";
String s3 = " !";
int w1 = fm.stringWidth(s1);
int w2 = fim.stringWidth(s2);
int w3 = fm.stringWidth(s3);
// Determine the size of the client area
Dimension d = getSize();
Insets in = getInsets();
int client_width = d.width - in.right - in.left;
int client_height = d.height - in.bottom - in.top;
int cx = (client_width - w1 - w2 - w3)/2;
int cy = client_height/2;
// Draw a green rectangle
// Save the current color so we can later reset it.
Color originalColor = g.getColor();
g.setColor(Color.GREEN);
g.drawRect(10, 10, client_width - 20, client_height - 20);
// Restore the original color
g.setColor(originalColor);
// Now draw the first part of the string in the default color
g.setFont(f);
g.drawString(s1, cx, cy);
cx += w1;
// Draw the second part of the string in magenta
g.setColor(Color.MAGENTA);
g.setFont(fi);
g.drawString(s2, cx, cy);
cx += w2;
// Draw the third part of the string in the original color
g.setColor(originalColor);
g.setFont(f);
g.drawString(s3, cx, cy);
}
private Font f = new Font("Serif", Font.BOLD, 16);
private Font fi = new Font("Serif", Font.BOLD | Font.ITALIC, 16);
private FontMetrics fm;
private FontMetrics fim;
}
class ColorTextDisplayFrame extends JFrame
{
public ColorTextDisplayFrame()
{
setTitle("ColorTextDisplay");
setSize(300, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.add( new ColorTextDisplayPanel() );
}
}
public class ColorTextDisplay
{
public static void main(String[] args)
{
ColorTextDisplayFrame frame = new ColorTextDisplayFrame();
frame.setVisible(true);
}
}
|

Or, we can specify the color to be used, via its red, green and blue
components, by replacing the line:
g.setColor(Color.MAGENTA);
with:
g.setColor( new Color(200, 150, 50) ); // red, green, blue
to produce:

|