Friday, April 15, 2005

How to add Button Color

Program

Basic idea

JButton colorButton = new JButton("Color Button");
colorButton.setBackground(Color.red);
colorButton.setForeground(Color.white);

Complete program

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingApplication extends JFrame {
    public static void main(String[] args) {
        new SwingApplication().createFrame();
    }

    void createFrame() {
        setTitle(getClass().getName());
        createContentPane();

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

        pack();
        setVisible(true);
    }

    void createContentPane() {
        JPanel jPanel = new JPanel();

        JButton grayButton = new JButton("Gray Button");
        JButton colorButton = new JButton("Color Button");
        colorButton.setBackground(Color.red);
        colorButton.setForeground(Color.white);

        jPanel.add(grayButton);
        jPanel.add(colorButton);
        getContentPane().add(jPanel);
    }
}

Output

[user]$ javac SwingApplication.java
[user]$ java SwingApplication