Reputation: 87
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
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.
Graphics2D.scale(sx,sy)
.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
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