Mohamed EL Tair
Mohamed EL Tair

Reputation: 357

setting a label always on top even when repainting in java?

i have two panels: pnl and pnl2, pnl2 has a label named car added to it (pnl2.add(car);). i changed layout manager of pnl to border layout and add pnl2 to its south (pnl.add(pnl2, BorderLayout.SOUTH);). pnl itself is added to a frame named GameFrame which extends JFrame (this.add(pnl);).

pnl2 is a normal JPanel, but pnl is of class i made named Road which extends JPanel, in this class i overrided paint method to draw specific objects (white rectangles at different positions), and in the constructor of the frame GameFrame i am using timer to repaint pnl every specific delay to produce an animation (moving white rectangles).

everything is working well but the white rectangles are always drawn on the top of the label named car, is there a way to make this car label always be on the top ?

Upvotes: 0

Views: 185

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

Suggestions:

  1. Override the JPanel's paintComponent not the paint method. The paint method is responsible for painting the JPanel's self and its children, and this can mess you up, whild paintComponent is only responsible for drawing the JPanel itself.
  2. Be sure to call the super's paintComponent method in your override as this is needed for the component to do its own housekeeping painting including the removal of dirty pixels.
  3. Be sure to only do painting in this method and nothing else, no program logic, no reading in of files, no changes of your object's state.
  4. If still stuck, post pertinent code.

Upvotes: 1

Related Questions