How to draw lines in Java

前端 未结 10 2030
梦毁少年i
梦毁少年i 2020-11-30 02:42

I\'m wondering if there\'s a funciton in Java that can draw a line from the coordinates (x1, x2) to (y1, y2)?

What I want is to do something like this:



        
10条回答
  •  渐次进展
    2020-11-30 03:13

    You need to create a class that extends Component. There you can override the paint method and put your painting code in:

    package blah.whatever;
    
    import java.awt.Component;
    import java.awt.Graphics;
    
    public class TestAWT extends Component {
    
    /** @see java.awt.Component#paint(java.awt.Graphics) */
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.drawLine(0,0,100,100);
        g.drawLine(10, 10, 20, 300);
        // more drawing code here...
    }
    
    }
    

    Put this component into the GUI of your application. If you're using Swing, you need to extend JComponent and override paintComponent, instead.

    As Helios mentioned, the painting code actually tells the system how your component looks like. The system will ask for this information (call your painting code) when it thinks it needs to be (re)painted, for example, if a window is moved in front of your component.

提交回复
热议问题