Results 1 to 2 of 2
  1. #1
    tgrossb is offline Member
    Join Date
    Oct 2016
    Posts
    2
    Rep Power
    0

    Default Create a JFrame object with a colored background

    I am trying to create a JFrame object with a black background. One of my classes is as follows:

    Java Code:
    class StartPanel extends JPanel{
                private int xPos, yPos;
        
                public void newPanel(){
                        JFrame window = new JFrame();
                        window.setSize(300, 300);
                        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        window.setVisible(true);
                        Container c = window.getContentPane();
                        c.add(this);
                        c.setBackground(Color.black);
                }
        
                public void drawUnit(int x, int y){
                        xPos = x;
                        yPos = y;
                        repaint();
                }
                public void paintComponent(Graphics g){
                        super.paintComponent(g);
                        g.setColor(Color.BLUE);
                        g.fillRect(xPos, yPos, 10, 10);
                }
        }
    My main class calls newPanel() then drawUnit(int x, int y), which calls repaint() and then paintComponent, but I'm sure you all know how this works. A black window with a blue square should come up, but instead the background is the default greyish white color. I did not include the import statements, but I am fairly sure that that is not the problem.

  2. #2
    tgrossb is offline Member
    Join Date
    Oct 2016
    Posts
    2
    Rep Power
    0

    Default Re: Create a JFrame object with a colored background

    I missed the obvious. Line 11 should be setBackground(Color.black), not c.setBackground(Color.black).

Similar Threads

  1. background image in jframe
    By pardhu in forum AWT / Swing
    Replies: 1
    Last Post: 11-08-2011, 04:00 AM
  2. JFrame background help?
    By Bimz in forum New To Java
    Replies: 4
    Last Post: 08-20-2011, 07:39 AM
  3. JFrame image background
    By 851marc in forum NetBeans
    Replies: 5
    Last Post: 03-09-2010, 06:27 PM
  4. Need help with JFrame background image
    By ProGenius in forum New To Java
    Replies: 6
    Last Post: 12-27-2009, 04:17 PM
  5. Background in JFrame ( GUI).
    By Twister03 in forum AWT / Swing
    Replies: 2
    Last Post: 03-12-2009, 03:24 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •