Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

setLocationRelativeTo(null) - problems with setBackground

 
Stephen Foy
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whenever i add this 'setLocationRelativeTo(null)' my setBackground is disregarded. Why is this??

Here is the part of the class with setLocation


Here is the class where setBackground is being defined

 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you tried adding



as the first line in paint?
 
Stephen Foy
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yep, still the same problem though.
 
Craig Wood
Ranch Hand
Posts: 1535
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The call to setOpaque(true) should be moved up into the constructor; it only needs to be called once. Similarly, the call g.setColor(Color.black) can be moved up above the for loop.
It's okay to override the paint method in your JComponent class. For custom drawing in which you do not want/need to draw over child components it's better to override paintComponent

The setBackground call won't do anything in the JComponent unless you use it like this

Even easier is to extend JPanel instead of JComponent. Then you can place the setBackground call in the constructor, omit the setOpaque call and

 
Stephen Foy
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks alot! thats spot on. Thanks for the tips also, theres always room to improve!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic