java background color

java background color

To set the background color of a Java application, you can use the setBackground() method of the Component class, which is the superclass of all Java GUI components. The setBackground() method takes a Color object as an argument and sets the background color of the component to the specified color.

Here is an example of how to set the background color of a Java AWT (Abstract Window Toolkit) application:

ref‮‬er to:lautturi.com
import java.awt.Frame;
import java.awt.Color;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class BackgroundColorExample extends Frame {

    public BackgroundColorExample() {
        setBackground(Color.BLUE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    public static void main(String[] args) {
        BackgroundColorExample frame = new BackgroundColorExample();
        frame.setSize(200, 200);
        frame.setVisible(true);
    }
}

In this example, the BackgroundColorExample class extends the Frame class and sets the background color to blue using the setBackground() method. The Color class is part of the java.awt package and provides several predefined colors as static fields, such as Color.BLUE, Color.RED, Color.GREEN, etc.

To run the example, create a new Java class and copy the code into it. Run the class using the java command. A window with a blue background will be displayed.

You can also use the setBackground() method to set the background color of other GUI components, such as buttons, labels, text fields, etc. For example:

import java.awt.Button;
import java.awt.Color;

...

Button button = new Button("Click me");
button.setBackground(Color.YELLOW);

This code creates a button with the label "Click me" and sets the background color to yellow using the setBackground() method.

Created Time:2017-11-03 00:14:45  Author:lautturi