Changing the Color of a Frame

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

In the body of the actionPerformed() method.

Changing the Color of a Frame

We will fill in the actionPerformed() body so that clicking the button changes the color of the frame. To change the color of the frame, do this:

getContentPane().setBackground( Color.red )

A JFrame is a complicated object, made up of many parts. The frame's content pane is where components added to the frame are displayed. The getContentPane() method of the frame returns a reference to the content pane. The setBackground() method of the pane changes its background color.

Other pre-defined colors are Color.green, Color.blue, Color.yellow, and so on. (Look in your Java documentation under the class Color to find more.) Here is the interesting part of our program:

class ButtonFrame extends JFrame implements ActionListener
{
  JButton bChange ;

  // constructor   
  public ButtonFrame() 
  {
   . . . 
  }
   
  public void actionPerformed( ActionEvent evt)
  {
     ;
    repaint();  // ask the system to paint the screen.
  }
  
}

The repaint() will be explained in the next page.

QUESTION 14:

Fill in the blank so that the program changes the frame to blue when the button is clicked.