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???
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
user2465406
  • 169
  • 1
  • 1
  • 7

1 Answers1

40

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.

Edwin Buck
  • 69,361
  • 7
  • 100
  • 138
  • I did it without using super.paintCompontent(g); – user2465406 Jun 11 '13 at 21:18
  • 1
    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. – Edwin Buck Jun 11 '13 at 21:36
  • 1
    @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? – Ungeheuer May 21 '15 at 02:47
  • They are the same thing @Johnny Coder – Ajay Aug 29 '16 at 19:04
  • @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. – Edwin Buck Aug 29 '16 at 19:11
  • I know this is 4 years late, but thanks for all the help everyone – user2465406 Dec 05 '17 at 07:55
  • @user2465406 Better late than never, and I'm glad it helped you out. – Edwin Buck Dec 05 '17 at 16:12