Can you increase line thickness when using Java Gr

2019-04-04 23:13发布

问题:

This question already has an answer here:

  • Java2D: Increase the line width 2 answers

I am having trouble adjusting line thickness. Can I do that in Graphics or do i have to do it in Graphics2D? If so, how do I alter the program to make it run?

Thanks!

import java.applet.Applet;
import java.awt.*;

public class myAppletNumberOne extends Applet {
    public void paint (Graphics page) {
        //Something here???
    }
}

回答1:

Yes you have to do it in Graphics2D, but that's hardly an issue, as every Graphics in Swing is a Graphics2D object (it just keeps the old interface for compatibility reasons).

public void paintComponent(Graphics g) {

    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.setStroke(new BasicStroke(3));
    g2.drawLine(...);   //thick
    ...

}

As you can see, the g2.setStroke(...) allows you to change the stroke, and there's even a BasicStroke which provides for easy line width selection.