Can you increase line thickness when using Java Graphics for an applet? I don't believe that BasicStroke works [duplicate]
Asked Answered
E

1

16

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???
    }
}
Etheleneethelin answered 8/6, 2013 at 2:6 Comment(0)
O
41

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.

Olszewski answered 8/6, 2013 at 3:40 Comment(7)
I did it without using super.paintCompontent(g);Etheleneethelin
the risks of not doing the super call include not having the sub-classed component do proper background handling, including possible look and feel configuration of colors, icons, transparencies, etc. Yes, it works, but odds are it doesn't work in a lot of scenarios that you haven't tested yet.Olszewski
@EdwinBuck do I have to have the paintComponent() method, or can I do this in the paint() method? The arguments are the same. Is there some sort of risk?Cipher
They are the same thing @Johnny CoderPropellant
@JohnnyCoder Overriding paint() is not the same thing as overriding paintComponent(). Paint() calls a number of methods in Swing, including paintComponent(), paintBorder(), and paintChildren() and also might update the ui delegate, which might redraw the background (to allow the painter's algorithm to work on transparent backgrounds). I would recommend not overriding the paint() method unless you have taken precautions that your code will work properly with borders, transparent backgrounds, and look-and-feel overrides.Olszewski
I know this is 4 years late, but thanks for all the help everyoneEtheleneethelin
@Etheleneethelin Better late than never, and I'm glad it helped you out.Olszewski

© 2022 - 2024 — McMap. All rights reserved.