Search code examples
javaswingjlabeljava-canvas

Adding Jlabel on top of canvas


Is there any way that i can add a jlabel on top of the canvas? In my code, the constructor of my frame adds the label first before adding the canvas but when i run it it does not show the label.

I am painting the background of my canvas.


Solution

  • Suggestions:

    1. Don't use Canvas objects. You've got a Swing GUI and should use the Swing equivalent -- a JPanel.
    2. Draw the background image in the JPanel's paintComponent method as the tutorials and hundreds of examples on this site will show you.
    3. Add the JLabel to the JPanel not to the JFrame.
    4. Then add the JPanel to the JFrame.
    5. Layout managers and your understanding of them are critical. Understand that a JPanel uses FlowLayout by default, and if you add a single JLabel to it, it will be placed in the center top region of the JPanel. Requisite Layout Manager Tutorial Link