• Post Reply Bookmark Topic Watch Topic
  • New Topic

Setting background colour for JPanel.

 
Dave Rea
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all, prepare yourselves for a really tough question (one of many I'm likely to ask!)

All I want to do is set my JPanel background to black, I thought this would do it but it doesn't. What am I doing wrong??

public class Display extends JPanel {

public Display() {

setBackground(Color.BLACK);
}

Thanks in advance for any answers!
 
Campbell Ritchie
Marshal
Posts: 52532
119
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

I shall move this discussion to where we usually discuss such questions: the GUIs forum.
You don't usually set colours in the constructor, but in the paintComponent(Graphics) method. Not paintComponents nor paint. Note two things:
  • 1: Protected access.
  • 2: You will need the super. call if anything changes when the component is repainted.
  •  
    Campbell Ritchie
    Marshal
    Posts: 52532
    119
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I tried it outBoth versions appear to work, but for some reason which I am not sure about the local class in version 2 has to be declared before it is used. otherwise it won't compile.
     
    Campbell Ritchie
    Marshal
    Posts: 52532
    119
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I think we need more information before anybody can answer your original question.
     
    Dave Rea
    Greenhorn
    Posts: 4
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Campbell Ritchie wrote:I think we need more information before anybody can answer your original question.


    No, you got it first time Campbell, thanks so much. Sorry I was afk until now, so obviously couldn't respond.

    And thanks for moving the question. I thought the basic nature of it would mean it would belong in the beginner section.

    Thanks again!
     
    Rob Camick
    Ranch Hand
    Posts: 2699
    10
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    You should not set the background Color in the paintComponent() method. You should never set any property of the component in any painting method. Swing components automatically repaint() themselves when a property is changed. Normally this will only involve one repaint, but there is the potential for an infinite loop to be created.

    I don't see any problem with the original code. It is fine to set the background in the constructor. Whenever you ask a question you need to post a SSCCE so we can see exactly what you are doing.
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!