简体   繁体   中英

How do I add JLabels over the Graphics class

I created a test class for my pong game to be able to add JLabels on my JFrame. However when I used the graphics class, the JLabel does not show up and I can't fix the problem.

import java.awt.Color;
import java.awt.Graphics;

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

public class Main extends JFrame {

    JLabel label;

    public Main() {
        JPanel p = new JPanel();
        p.setLayout(null);

        label = new JLabel("Text inside");
        label.setBounds(1100, 500, 200, 50);
        p.add(label);
        add(p);

        setSize(1700, 712);
        setTitle("Title");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public void paint(Graphics g) {

        g.setColor(Color.green);
        g.fillRect(0, 0, 1700, 712);
        g.setColor(Color.DARK_GRAY);
        g.drawRect(1050, 450, 300, 200);
    }

    public static void main(String[] args) {
        new Main();
    }
}

The JavaDoc for Window.paint() clearly states:

If this method is reimplemented, super.paint(g) should be called so that lightweight components are properly rendered.

You don't do this, so your lightweight components (ie your JLabel s) are no longer rendered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM