Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java GUI programming: Setting the Fore/Background

I'm just getting into GUI programming, slowly learning.

However I'm having a problem right of the bat. I can't get the Fore/Background color to change in my window at all.

However when I add a label via JLabel and then use setFore/Back, they change colors just fine. Just not the whole window.

I thought .setForeground and .setBackground are supposed to change the color of the window?

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

public class MyWindow {

    public static void main(String args[])
    {
         Runnable init = new Runnable()
         {
             public void run()
             {

                    JFrame myWindow = new JFrame("Hola!");
                    myWindow.setForeground(Color.YELLOW);
                    myWindow.setBackground(Color.YELLOW);
                    myWindow.setSize(400, 300);

                    myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    myWindow.setLayout(null);

                    myWindow.setVisible(true);

             }

         };
         SwingUtilities.invokeLater(init);
    }


}
like image 931
Grumpy ol' Bear Avatar asked Aug 01 '26 14:08

Grumpy ol' Bear


2 Answers

First of all, do not use a null layout. Let the layout manager do its job. Second of all, you need to set the background of the content pane of the JFrame instance, as such

myWindow.getContentPane().setBackground(Color.YELLOW);

See also:

  • Using Top-Level Containers
like image 146
mre Avatar answered Aug 04 '26 04:08

mre


you cannot color a frame. However you can color the ContentPane inside.

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

    public class MyWindow {

        public static void main(String args[])
        {
             Runnable init = new Runnable()
             {
                 public void run()
                 {

                        JFrame myWindow = new JFrame("Hola!");

    myWindow.getContentPane().setBackground(Color.YELLOW);

                        myWindow.setSize(400, 300);

                        myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        myWindow.setLayout(null);

                        myWindow.setVisible(true);

                 }

             };
             SwingUtilities.invokeLater(init);
        }  
    }

this should fix your problem...

like image 36
Stefano Avatar answered Aug 04 '26 03:08

Stefano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!