2014-07-26 303 views
0

我想在java中繪製虛線和波浪線。 我可以使用Graphics - 和g.drawLine()方法繪製正常線條。 有沒有簡單的方法來繪製Graphics2D或其他類似的虛線和波浪線?Java - 如何繪製虛線和波浪線?

現在我使用MouseListener的座標繪製線條。所以它就像MS Paint一樣。

+1

[在java中繪製虛線]的可能重複(http://stackoverflow.com/questions/21989082/drawing-dashed-line-in-java) – DavidPostill

+0

線條是全部水平/垂直還是可以任意角度? –

+0

@AndrewThompson他們可以是任何角度。虛線問題已解決。我現在遇到了波浪線問題。 –

回答

1

虛線,as presented by Kevin Workman:

public void drawDashedLine(Graphics g, int x1, int y1, int x2, int y2){ 

      //creates a copy of the Graphics instance 
      Graphics2D g2d = (Graphics2D) g.create(); 

      Stroke dashed = new BasicStroke(3, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[]{9}, 0); 
      g2d.setStroke(dashed); 
      g2d.drawLine(x1, y1, x2, y2); 

      //gets rid of the copy 
      g2d.dispose(); 
    } 

您可以創建虛線喜歡用這個。

波浪線,as presented by Tiger:

import java.awt.geom.*; 
import java.awt.*; 
import javax.swing.*; 

public class CurveDraw extends JFrame { 
     public static void main(String[] args) { 
       CurveDraw frame = new CurveDraw(); 
       frame.setVisible(true); 
     } 
     public CurveDraw() { 
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       setSize(400,400); 
     } 
     public void paint(Graphics g) { 
       QuadCurve2D.Double curve = new QuadCurve2D.Double(50,100,100,170,150,100); 
       ((Graphics2D)g).draw(curve); 
     } 
} 

Docs.oracle to learn more about Swing wavy line

Curvy line

Docs.oracle to learn more about Swing

+0

謝謝我會試試..但是波浪線呢? –

+0

已更新@Mike_NotGuilty。這些保存在我的電腦上。他們應該工作。 –

+3

請不要建議人們,特別是像@Mike_NotGuilty這樣的新手,直接在JFrame的繪畫方法中繪製。看到這就像抓釘子抓黑板一樣。它讓我厭惡我的胃。 –