Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Intermediate
Apr 9, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Choosing Colors for Custom Components

When creating a custom user interface component, you often face the problem of deciding what colors to use while drawing the component on the screen. However, to a large extent, this decision has already been made for you. Each system supports a standard color for a given user interface element so that all interface components will have a common "look and feel." For example, the title bars of any inactive windows will be assigned a certain color, while the title bar of the active window is assigned a different color to make it stand out. Also, colors are defined for use when drawing the background and foreground portions of components, as well as colors for drawing their borders to produce a three-dimensional effect when displayed.

Since these colors have already been defined by the user (or through default values provided by the operating system), all that's necessary is for your component to take advantage of them when drawing itself. To access the colors, simply reference the appropriate static instance of the java.awt.SystemColor class:

import java.awt.*;

public class comptest extends Component {

	public void paint(Graphics g) {
		Dimension size = getSize();
		g.fillRect(0, 0, size.width, size.height);
		g.drawString("Testing", 10, 20);
		g.drawRect(0, 0, size.width - 2, size.height - 2);
		g.drawRect(1, 1, size.width - 1, size.height - 1);
		g.drawRect(0, 0, size.width - 1, size.height - 1);
		g.drawRect(0, 0, size.width, size.height);
	}  //  public void paint(Graphics g)

	public Dimension getPreferredSize() {
		return new Dimension(100, 50);
	}  //  public Dimension getPreferredSize()

}  //  public class comptest extends Component
When the paint() method is called, this component will fill its background area, draw a three-dimensional border, and display the string "Testing". This entire process is done using the appropriate system-defined color each element. By using the SystemColor values, custom components can adhere to the operating system's color scheme, providing a more user-friendly interface to your application.
Brett Spell
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date