drawLine() 方法不绘制任何东西

drawLine() method not drawing anything

所以我在 class 中有这个 class,它是 JPanel 的一个实现。

    private static class Line extends JComponent {

    private static final long serialVersionUID = 1L;

    @Override
    public void paintComponent(Graphics g) {
        System.out.println("Pozvan paintComponent()");
        g.setColor(Color.YELLOW);
        g.drawLine(20, 20, 100, 20);
        super.paintComponent(g);
    } 
    }

这是创建 Line 的单个实例的代码片段:

        Line line = new Line();
        line.setOpaque(true);
        add(line);

我真的不知道我做错了什么。当我画一个矩形时,一切都画得很漂亮。

when I set the height to remotely big number it works.

Swing 组件的默认大小为 (0, 0)。由于size为0,所以没有画什么

g.drawLine(20, 20, 100, 20);

根据以上信息,这意味着您的组件需要大小为 (120, 40)。也就是width = 20 + 100 height = 20 + 20,这样组件才能被绘制。

I added line.setBounds(20, 20, 80, 50); 

只有部分线条会被绘制,因为您将宽度设置为 80,而不是 120。

阅读 Custom Painting 上的 Swing 教程部分以获取更多信息和示例。