helloMundo
helloMundo

Reputation: 87

How to scale an object according to window size?

I am trying to create a shape inside of a JPanel, and as the JPanel increases and decreases the size of the shape also changes accordingly.

   protected void paintComponent(Graphics g)
   {
      super.paintComponent(g);
      g.drawLine(0,100,50,0);
   }

My problem is that I don't know how to scale it using something along the lines of this.getHeight() or this.getLength().

Upvotes: 2

Views: 2890

Answers (2)

Andrew Thompson
Andrew Thompson

Reputation: 168825

Besides the path outlined by @MadProgrammer, there are two other ways I can think of to scale graphics.

Swing components can generally rely on the Graphics object actually being a Graphics2D object.

  1. We can then use Graphics2D.scale(sx,sy).
  2. A scale instance of an AffineTransform (obtained using getScaleInstance(sx,sy). Set it to the Graphics2D before drawing.

Using either method, the original co-ordinates will be scaled as needed.

Upvotes: 3

MadProgrammer
MadProgrammer

Reputation: 347204

Assuming you mean you want to maintain a proportional ratio as the component size changes...

There are a few ways to do this...

You could start by determining the "default" values, that is, if the "preferred" width was 200, the line start point would 50% of the width and the end point would be 25% of the width.

This would allow you to do something like...

int width = getWidth();
int x1 = (int)(Math.round(width * 0.5d);
int x2 = (int)(Math.round(width * 0.25d);
g.drawLine(0, x1, x2, 0);

Upvotes: 2

Related Questions