简体   繁体   English

调用paint方法时JLabel不显示

[英]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.这是我年终项目的一小部分,我正在尝试在 JFrame 中添加一条带有 JLabel 的直线。 if i remove the JLabel then the line will show up, else it won't.如果我删除 JLabel 则该行将显示,否则不会。 i only know about java swing therefore i don't have any experience for java graphics.我只知道 java swing 因此我对 java 图形没有任何经验。

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);
    }
}

As already said in the comments, don't override the #paint(Graphics g) method of the JFrame .正如评论中已经说过的,不要覆盖 JFrame 的JFrame #paint(Graphics g)方法。 Instead override the #paintComponent(Graphics g) method of your contentPane .而是覆盖contentPane#paintComponent(Graphics g)方法。

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
    }
};

I don't know if it is really necessary that you call:我不知道您是否真的有必要致电:

super.paintComponent(Graphics g);

maybe that is also done by #paintChildren(Graphics g);也许这也是由#paintChildren(Graphics g); by the Component class.通过Component class。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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