Java JFrame background color not working

前端 未结 4 1451
名媛妹妹
名媛妹妹 2020-12-11 19:05

I tried using:

frame1.getContentPane().setBackground(Color.yellow);

But it is not working. Can anyone help me?

import java.         


        
相关标签:
4条回答
  • 2020-12-11 19:34

    Since you did not post an SSCCE, I will do it for you. This shows how to change the background color of a JFrame. Starting from this, you can start adding components to the JFrame and see where you go wrong, instead of letting us look at a few hundred lines of code.

    import javax.swing.JFrame;
    import java.awt.Color;
    import java.awt.EventQueue;
    
    public class ColoredFrame {
    
      public static void main( String[] args ) {
        EventQueue.invokeLater( new Runnable() {
          @Override
          public void run() {
            JFrame frame = new JFrame( "TestFrame" );
            frame.getContentPane().setBackground( Color.PINK );
            //frame contains nothing, so set size
            frame.setSize( 200, 200 );
            frame.setVisible( true );
            frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
          }
        } );
      }
    }
    
    0 讨论(0)
  • 2020-12-11 19:37

    I know this is a very old question, but for others that are looking for the right answer this could also be written as following:

    frame1.getContentPane().setBackground(new Color (255,255,102)); //or whatever color you want in the RGB range
    
    0 讨论(0)
  • 2020-12-11 19:38

    Just put your setVisible(true); at the end of your constructor.

    Moreover you had added mainPnl on your JFrame, so changing colour of the JFrame will be useless,

    so instead of writing

    add(mainPnl);
    

    in your GameFrame class, you better be using

    setContentPane(mainPnl);
    

    for frame1.getContentPane().setBackground(Color.YELLOW); to work.

    Hope this might help

    Regards

    0 讨论(0)
  • 2020-12-11 19:39

    You should give background color to JPanel and then use this JPanel in your JFrame rather than giving direct background to your JFrame.

    0 讨论(0)
提交回复
热议问题