How to draw lines in Java

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

    Store the lines in some type of list. When it comes time to paint them, iterate the list and draw each one. Like this:

    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 lines;
        Random random;
    
        LineComponent(int width, int height) {
            super();
            setPreferredSize(new Dimension(width,height));
            lines = new ArrayList();
            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()
                    );
            }
        }
    }
    

    Screenshot

    enter image description here

提交回复
热议问题