HunteredEvil
HunteredEvil

Reputation: 1

JLabel doesn't show up when calling paint mehtod

This is small part of my end of year project and I'm trying to add a straight line with JLabel in a JFrame. if i remove the JLabel then the line will show up, else it won't. i only know about java swing therefore i don't have any experience for java graphics.

THANK YOU IN ADVANCE :)

import java.awt.EventQueue;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;

public class Draw extends JFrame {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Draw frame = new Draw();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Draw() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 569, 461);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
        
        JLabel lbl = new JLabel("Show ");
        lbl.setBounds(263, 90, 49, 14);
        contentPane.add(lbl);
    }
    
    @Override
    public void paint(Graphics g) {
        g.drawLine(100, 100, 0, 0);
        g.drawArc(200, 200, 120, 100, 0, 180);
    }
}

Upvotes: 0

Views: 208

Answers (1)

Corni
Corni

Reputation: 96

As already said in the comments, don't override the #paint(Graphics g) method of the JFrame. Instead override the #paintComponent(Graphics g) method of your contentPane.

contentPane = new JPanel() {
    @Override
    protected void paintComponent(Graphics g) {
        //Don't forget to call the super method
        super.paintComponent(Graphics g);
        //Draw the line
        g.drawLine(100, 100, 0, 0);  //Maybe adapt the line's position
    }
};

Upvotes: 1

Related Questions