繁体   English   中英

调用paint方法时JLabel不显示

[英]JLabel doesn't show up when calling paint mehtod

这是我年终项目的一小部分,我正在尝试在 JFrame 中添加一条带有 JLabel 的直线。 如果我删除 JLabel 则该行将显示,否则不会。 我只知道 java swing 因此我对 java 图形没有任何经验。

先感谢您:)

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

正如评论中已经说过的,不要覆盖 JFrame 的JFrame #paint(Graphics g)方法。 而是覆盖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
    }
};

我不知道您是否真的有必要致电:

super.paintComponent(Graphics g);

也许这也是由#paintChildren(Graphics g); 通过Component class。

暂无
暂无

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

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