jlabel在调用paint method时不会出现

ej83mcc0  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(430)

这是我年底项目的一小部分,我正在尝试在jframe中添加一条与jlabel的直线。如果我移除jlabel,那么该行将显示,否则它不会显示。我只知道JavaSwing,因此我对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);
    }
}
vaj7vani

vaj7vani1#

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

我不知道你是否真的有必要打电话给:

super.paintComponent(Graphics g);

也许这也是由 #paintChildren(Graphics g);Component 班级。

相关问题