【问题标题】:JLabel doesn't show up when calling paint mehtod调用paint方法时JLabel不显示
【发布时间】:2020-12-27 16:18:43
【问题描述】:

这是我年终项目的一小部分,我正在尝试在 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);
    }
}

【问题讨论】:

  • 不要使用空布局。不要使用 setBounds()。不要覆盖 JFrame 上的paint()。自定义绘画是通过覆盖 JPanel 上的 paintComponent() 来完成的,然后将面板添加到框架中。框架的内容面板已经是一个JPanel,不需要再创建另一个面板。阅读 Custom Painting 上的 Swing 教程部分。下载其中一个工作示例并根据您的特定要求对其进行修改。
  • 永远不要直接在 JFrame 中绘制,而是在 JPanel 中覆盖paintComponent,并且在覆盖任何绘制方法(paint、paintComponent、paintBorders...)时,您几乎总是需要在您的覆盖中调用相应的超级方法。

标签: java swing jlabel paint


【解决方案1】:

正如在 cmets 中已经说过的,不要覆盖 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
    }
};

【讨论】:

    猜你喜欢
    • 2019-09-01
    • 2020-11-15
    • 2015-09-24
    • 2012-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    相关资源
    最近更新 更多