johnbumble
johnbumble

Reputation: 700

creating a stroked shape

I am having trouble with creating a stroked shape in BasicStroke Outline = new BasicStroke(10f, 50, 50);. The error I am currently getting is error:

can't find symbol canvas.setStroke(Outline) pointing to the dot.

I am new to constructors so any help would be great and the only thing I did similar to this was creating an instance of Scanner.

import javax.swing.JFrame;
import java.awt.Graphics;
import java.awt.Color; //sets color
import java.awt.BasicStroke;
import java.awt.Graphics2D;
public class ColoredOlypmicRings extends JFrame
{
 //varriables go here


public void paint(Graphics canvas)
{
 super.paint (canvas);

canvas.setColor(Color.green);
canvas.drawOval(100,100,100,100); //color green
canvas.setColor(Color.red);
canvas.drawOval(200,200,100,100); //color red
final BasicStroke Outline = new BasicStroke(10f, 50, 50);
canvas.setStroke(Outline);

canvas.drawOval(300,300,200,200);
}

 public ColoredOlypmicRings()
 {
 setSize(600,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
 }

public static void main(String[] args)
{
 ColoredOlypmicRings guiWindow = new ColoredOlypmicRings();
guiWindow.setVisible(true);
 }
}

Upvotes: 0

Views: 255

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

The Graphics class can't handle Strokes and doesn't have methods for setting it as its API will tell you.

The Graphics2D class on the other hand can handle this class and should be used to handle it. So cast your Graphics object to a Graphics2D object.

e.g.,

@Override
protected void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setStroke(....); // do it here after casting
}

Also check out the BasicStroke API as you're not using the constructor correctly, passing in incorrect parameters.

Other issues:

  • Don't draw directly in a JFrame or other top-level window.
  • Instead draw in the paintComnponent method of a JPanel that is displayed in the JFrame.
  • The three int BasicStroke constructor is being mis-used as the 2nd and 3rd parameters should be constants that represent the cap and join state of the Stroke object.

Upvotes: 3

Related Questions