Behnam Ezazi
Behnam Ezazi

Reputation: 69

I need simplest way to draw a line in java in AWT panel

I need the simplest way to draw a line between to coordinates. Since this drawing line in my code will be repeated more than 200 times in a loop i need the easiest way. I'm drawing the lines in a AWT panel component.

Upvotes: 1

Views: 711

Answers (2)

Felix Rindt
Felix Rindt

Reputation: 131

If you want to switch to Swing you would use the JPanel and overwrite the paintComponent() method.

import java.awt.Graphics;

import javax.swing.JPanel;

public class PanelWithLine extends JPanel {

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawLine(x1,y1,x2,y2);
    }

}

You can than redraw everything by calling repaint() on your Jpanel.
You would probably change the coordinates and then call the repaint() method in your loop.

Upvotes: 2

ControlAltDel
ControlAltDel

Reputation: 35011

It's been a long time since I've used java.awt.Panel, but it should be something like:

class Foo extends Panel {
  public void paint(Graphics g) {
    super.paint(g);
    g.drawLine(x1,y1,x2,y2);
    g.drawLine(x3,y3,x4,y4);
    //...
  }
}

Upvotes: 2

Related Questions