Choosing Colors for Custom Components

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.setColor(SystemColor.control);		g.fillRect(0, 0, size.width, size.height);		g.setColor(SystemColor.controlText);		g.drawString("Testing", 10, 20);		g.setColor(SystemColor.controlShadow);		g.drawRect(0, 0, size.width - 2, size.height - 2);		g.setColor(SystemColor.controlLtHighlight);		g.drawRect(1, 1, size.width - 1, size.height - 1);		g.setColor(SystemColor.controlDkShadow);		g.drawRect(0, 0, size.width - 1, size.height - 1);		g.setColor(SystemColor.controlHighlight);		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.

See also  Does It Make Sense to Splurge on a Laptop?

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist