简体   繁体   English

drawLine()方法不绘制任何内容

[英]drawLine() method not drawing anything

So I have this class inside a class which is an implementation of JPanel. 所以我在一个类的内部包含了这个类,该类是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);
    } 
    }

This is a snippet of code which creates a single instance of Line: 这是创建Line的单个实例的代码段:

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

I really don't know what I am doing wrong here. 我真的不知道我在做什么错。 When I draw a rectangle, everything is nicely drawn. 当我绘制一个矩形时,一切都很好地绘制了。

when I set the height to remotely big number it works. 当我将高度设置为较大的数字时,它会起作用。

The default size of a Swing component is (0, 0). Swing组件的默认大小为(0,0)。 Since the size is 0, there is nothing to paint. 由于大小为0,因此无需绘画。

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

Using the above information this means your component needs a size of (120, 40). 使用以上信息,这意味着您的组件需要大小为(120,40)。 That is, width = 20 + 100 and height = 20 + 20, in order for the component to be painted. 也就是说,宽度= 20 + 100,高度= 20 + 20,以便对组件进行喷涂。

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

Only part of your line will be painted, since you set the width to 80, not 120. 由于将宽度设置为80,而不是120,因此仅会绘制部分线条。

Read the section from the Swing tutorial on Custom Painting for more information and examples. 阅读Swing教程上有关自定义绘画的部分,以获取更多信息和示例。

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

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