Buddy
Buddy

Reputation: 33

paintComponent method doesn't draw anything when I pass class's variable

My java code:

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;

import javax.swing.JPanel;

public class ConcentricCircles2D extends JPanel {
double myX = 0;
double myY = 0;
int myWidth = getWidth();
int myHeight = getHeight();

public void paintComponent(Graphics g)
{

    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.setPaint(Color.BLUE);                  
    g2.setStroke(new BasicStroke(5.0f)); 
    g2.draw(new Ellipse2D.Double(myX, myY, myWidth, myHeight));

}

When I use a local variable inside the paintComponent method it works just fine. How can I solve the problem? (I create the panel on separate class.)

Upvotes: 2

Views: 119

Answers (1)

RubioRic
RubioRic

Reputation: 2468

myWidth and myHeight values are set only when the ConcentricCircles2D object is instantiated. It has zero weight and height at this point.

So this sentence

Ellipse2D.Double(myX, myY, myWidth, myHeight)

is equal to

Ellipse2D.Double(0, 0, 0, 0)

and it will paint no ellipse at all.

Replace the sentence

 g2.draw(new Ellipse2D.Double(myX, myY, myWidth, myHeight));

with your original

 g2.draw(new Ellipse2D.Double(0, 0, getWidth(), getHeight()));

and an ellipse centered in the parent JFrame will be drawn and its dimensions will change if you resize its parent.

Upvotes: 1

Related Questions