Draw a line with a thickness
import java.awt.*;
import java.applet.*;
public class thickLine extends Applet {
public void init( ) { }
public void paint( Graphics g ) {
drawThickLine(g, 0, 0, getSize().width, getSize().height, 5, new Color(0).black);
drawThickLine(g, 0, getSize().height, getSize().width, 0, 5, new Color(0).red);
drawThickLine
(g, getSize().width/2, 0, getSize().width/2, getSize().height, 8, new Color(0).green);
drawThickLine
(g, 0, getSize().height/2, getSize().width, getSize().height/2, 12, new Color(0).blue);
}
public void drawThickLine(
Graphics g, int x1, int y1, int x2, int y2, int thickness, Color c) {
// The thick line is in fact a filled polygon
g.setColor(c);
int dX = x2 - x1;
int dY = y2 - y1;
// line length
double lineLength = Math.sqrt(dX * dX + dY * dY);
// The x and y increments from an endpoint needed to create a rectangle...
double ddx = -scale * (double)dY;
double ddy = scale * (double)dX;
ddx += (ddx > 0) ? 0.5 : -0.5;
ddy += (ddy > 0) ? 0.5 : -0.5;
int dx = (int)ddx;
int dy = (int)ddy;
// Now we can compute the corner points...
int xPoints[] = new int[4];
int yPoints[] = new int[4];
Using JDK1.2 public void paint(Graphics g){
Graphics2D g2d = (Graphics2D)g;
int width = 10;
g2d.setStroke(new BasicStroke(width));
g2d.drawLine(x1, y1, x2, y2);
}
On a Component int width = 10;
BasicStroke bs = new BasicStroke(width);
JLabel l = new JLabel();
l.getGraphics().setStroke(bs);
l.drawLine(0,0,100,100);
Using JDK1.3 import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
public class TestLine extends JFrame{
private MyPanel panel;
public TestLine() {
setSize(200, 200);
panel = new MyPanel();
getContentPane().add( panel, "Center" );
}
public static void main( String [] args ){
TestLine tl = new TestLine();
tl.setVisible( true );
}
}
class MyPanel extends JPanel {
final static BasicStroke stroke = new BasicStroke(2.0f);
final static BasicStroke wideStroke = new BasicStroke(8.0f);