如何在Java中绘制线条

| 我想知道Java中是否有一个函数可以从坐标(x1,x2)到(y1,y2)画一条线? 我想要做的是这样的事情:
drawLine(x1, x2, x3, x4);
而且我希望能够在代码中的任何时候执行此操作,从而使多行同时出现。 我试图做到这一点:
public void paint(Graphics g){
   g.drawLine(0, 0, 100, 100);
}
但这使我无法控制何时使用该函数,而且我无法弄清楚如何多次调用它。 希望你明白我的意思! 附言我想创建一个包含许多坐标的坐标系。     
已邀请:
绘制线条的摆动组件的一个非常简单的示例。它在内部保留一个列表,其中包含使用方法addLine添加的行。每次添加新行时,都会调用重新绘制以告知图形子系统需要新绘制。 该类还包括一些用法示例。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class LinesComponent extends JComponent{

private static class Line{
    final int x1; 
    final int y1;
    final int x2;
    final int y2;   
    final Color color;

    public Line(int x1, int y1, int x2, int y2, Color color) {
        this.x1 = x1;
        this.y1 = y1;
        this.x2 = x2;
        this.y2 = y2;
        this.color = color;
    }               
}

private final LinkedList<Line> lines = new LinkedList<Line>();

public void addLine(int x1, int x2, int x3, int x4) {
    addLine(x1, x2, x3, x4, Color.black);
}

public void addLine(int x1, int x2, int x3, int x4, Color color) {
    lines.add(new Line(x1,x2,x3,x4, color));        
    repaint();
}

public void clearLines() {
    lines.clear();
    repaint();
}

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    for (Line line : lines) {
        g.setColor(line.color);
        g.drawLine(line.x1, line.y1, line.x2, line.y2);
    }
}

public static void main(String[] args) {
    JFrame testFrame = new JFrame();
    testFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    final LinesComponent comp = new LinesComponent();
    comp.setPreferredSize(new Dimension(320, 200));
    testFrame.getContentPane().add(comp, BorderLayout.CENTER);
    JPanel buttonsPanel = new JPanel();
    JButton newLineButton = new JButton(\"New Line\");
    JButton clearButton = new JButton(\"Clear\");
    buttonsPanel.add(newLineButton);
    buttonsPanel.add(clearButton);
    testFrame.getContentPane().add(buttonsPanel, BorderLayout.SOUTH);
    newLineButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int x1 = (int) (Math.random()*320);
            int x2 = (int) (Math.random()*320);
            int y1 = (int) (Math.random()*200);
            int y2 = (int) (Math.random()*200);
            Color randomColor = new Color((float)Math.random(), (float)Math.random(), (float)Math.random());
            comp.addLine(x1, y1, x2, y2, randomColor);
        }
    });
    clearButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            comp.clearLines();
        }
    });
    testFrame.pack();
    testFrame.setVisible(true);
}

}
    
将行存储在某种类型的列表中。当需要绘画时,请遍历列表并绘制每一个。像这样:
DrawLines
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.geom.Line2D;

import javax.swing.JOptionPane;
import javax.swing.JComponent;
import javax.swing.SwingUtilities;

import java.util.ArrayList;
import java.util.Random;

class DrawLines {

    public static void main(String[] args) {

        Runnable r = new Runnable() {
            public void run() {
                LineComponent lineComponent = new LineComponent(400,400);
                for (int ii=0; ii<30; ii++) {
                    lineComponent.addLine();
                }
                JOptionPane.showMessageDialog(null, lineComponent);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

class LineComponent extends JComponent {

    ArrayList<Line2D.Double> lines;
    Random random;

    LineComponent(int width, int height) {
        super();
        setPreferredSize(new Dimension(width,height));
        lines = new ArrayList<Line2D.Double>();
        random = new Random();
    }

    public void addLine() {
        int width = (int)getPreferredSize().getWidth();
        int height = (int)getPreferredSize().getHeight();
        Line2D.Double line = new Line2D.Double(
            random.nextInt(width),
            random.nextInt(height),
            random.nextInt(width),
            random.nextInt(height)
            );
        lines.add(line);
        repaint();
    }

    public void paintComponent(Graphics g) {
        g.setColor(Color.white);
        g.fillRect(0, 0, getWidth(), getHeight());
        Dimension d = getPreferredSize();
        g.setColor(Color.black);
        for (Line2D.Double line : lines) {
            g.drawLine(
                (int)line.getX1(),
                (int)line.getY1(),
                (int)line.getX2(),
                (int)line.getY2()
                );
        }
    }
}
屏幕截图     
您需要创建一个扩展Component的类。在那里,您可以重写paint方法并将绘画代码放入:
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...
}

}
将此组件放入应用程序的GUI中。如果您使用的是Swing,则需要扩展JComponent并重写paintComponent。 正如Helios所说,绘画代码实际上告诉系统组件的外观。当系统认为需要(重新)绘制(例如,是否将窗口移到组件前面)时,系统将询问此信息(调用绘制代码)。     
在您的课堂上,您应该有:
public void paint(Graphics g){
   g.drawLine(x1, y1, x2, y2);
}
然后在代码中,如果需要,您将更改x1,y1,x2,y2并调用
repaint();
。     
我了解您使用Java AWT API进行绘图。当控件需要重新绘制时,将调用paint方法。而且我很确定它在Graphics参数中提供了需要重绘的矩形(以避免重绘所有矩形)。 因此,如果要显示固定图像,则只需绘制该方法所需的任何内容即可。 如果您要设置动画,我认为您可以使某些区域无效,并且paint方法将被自动调用。因此,您可以修改状态,调用无效,然后它将再次被调用。     
给你一些想法:
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);
  }
}
    
您可以使用要在其上绘制的组件的getGraphics方法。反过来,这应允许您绘制线并进行其他操作,这些可通过Graphics类获得     
我构建了一类用于绘制点,线,矩形,圆等的方法。我将其设计为将窗口视为一张方格纸,其中原点不必在左上角,y值随你增加而增加。这是我画线的方式:
public static void drawLine (double x1, double y1, double x2, double y2)
{       
    ((Graphics2D)g).draw(new Line2D.Double(x0+x1*scale, y0-y1*scale, x0+x2*scale, y0-y2*scale));
}
在上面的示例中,“ 10”代表屏幕坐标的原点,“ 11”是比例因子。输入参数将作为图形坐标而不是屏幕坐标提供。没有ѭ12被调用。您可以保存该直线,直到绘制完所需的所有线条。 我想到有人可能不想用方格纸思考:
    ((Graphics2D)g).draw(new Line2D.Double(x1, y1, x2, y2));
注意使用the14 use。这使我们可以使用双精度而不是整数绘制
Line2D
对象。除了其他形状之外,我的课堂还支持3D透视图和多种便捷方法(例如绘制以给定半径的特定点为中心的圆)。如果有人感兴趣,我很乐意分享更多此类。     
a simple line , after that you can see also a doted line 

import java.awt.*;

import javax.swing.*;

import java.awt.Graphics.*;

import java.awt.Graphics2D.*;

import javax.swing.JFrame;

import javax.swing.JPanel;

import java.awt.BasicStroke;

import java.awt.Event.*;

import java.awt.Component.*;

import javax.swing.SwingUtilities;


/**
 *
 * @author junaid
 */
public class JunaidLine extends JPanel{


//private Graphics Graphics;

private void doDrawing(Graphics g){

Graphics2D g2d=(Graphics2D) g;

float[] dash1 = {2f,0f,2f};

g2d.drawLine(20, 40, 250, 40);

BasicStroke bs1 = new BasicStroke(1,BasicStroke.CAP_BUTT,

                    BasicStroke.JOIN_ROUND,1.0f,dash1,2f);

g2d.setStroke(bs1);

g2d.drawLine(20, 80, 250, 80);

    }

@Override

public void paintComponent(Graphics g){

super.paintComponent( g);

doDrawing(g);

}


}

class BasicStrokes extends JFrame{

public  BasicStrokes(){

initUI();

}

private void initUI(){

setTitle(\"line\");

setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

add(new JunaidLine());

setSize(280,270);

setLocationRelativeTo(null);

}

/**

* @param args the command line arguments

*/

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable(){   

@Override

public void run(){

BasicStrokes bs = new BasicStrokes();

bs.setVisible(true);

}                

});

}


}
    
要回答您的原始问题,从ѭ17到
(x2, y2)
。 例如, 这是画一条水平线:
g.drawLine( 10, 30, 90, 30 );
与 这是画一条垂直线:
g.drawLine( 10, 30, 10, 90 );
希望对您有所帮助。     

要回复问题请先登录注册