How to draw lines in Java

前端 未结 10 1983
梦毁少年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:14

    You can use the getGraphics method of the component on which you would like to draw. This in turn should allow you to draw lines and make other things which are available through the Graphics class

    0 讨论(0)
  • 2020-11-30 03:14

    To answer your original question, it's (x1, y1) to (x2, y2).

    For example,

    This is to draw a horizontal line:

    g.drawLine( 10, 30, 90, 30 );
    

    vs

    This is to draw a vertical line:

    g.drawLine( 10, 30, 10, 90 );
    

    I hope it helps.

    0 讨论(0)
  • 2020-11-30 03:18

    To give you some idea:

    public void paint(Graphics g) {
       drawCoordinates(g);
    }
    
    private void drawCoordinates(Graphics g) {
    
      // get width & height here (w,h)
    
      // define grid width (dh, dv)
    
      for (int x = 0; i < w; i += dh) {
        g.drawLine(x, 0, x, h);
      }
      for (int y = 0; j < h; j += dv) {
          g.drawLine(0, y, w, y);
      }
    }
    
    0 讨论(0)
  • 2020-11-30 03:19

    In your class you should have:

    public void paint(Graphics g){
       g.drawLine(x1, y1, x2, y2);
    }
    

    Then in code if there is needed you will change x1, y1, x2, y2 and call repaint();.

    0 讨论(0)
提交回复
热议问题