I was doing my homework on Graphics2d and Polygon, however I am not able to search (or maybe using wrong keyword?) the solution of my homework.
Hoemwork question screenshot:
The code below is the first approach I have tried, I only see empty screen. After some searching on Google, I realized I got wrong usage of .scale and .translate, so I move it before the .drawPolygon, this time I can see the polygon, but it is after I enlarge my window, which means it is not visible within the 300, 300 initially?
import javax.swing.*;
public class PolygonExample extends JFrame{
public PolygonExample(){
super("Drawing Red Polygon");
setSize(300, 300);
setVisible (true);
}
public void paint (Graphics g){
super.paint(g);
int xValue[] = {0, 10, 7, -7, -10};
int yValue[] = {-10, -2, 10, 10, -2};
Polygon polygon = new Polygon(xValue, yValue, 5);
g.setColor(Color.RED);
g.drawPolygon(polygon);
Graphics2D g2d = (Graphics2D) g;
g2d.scale(5.0, 5.0);
g2d.translate(150, 150);
}
public static void main(String[] args) {
new PolygonExample();
}
}
I expect the polygon would be drawn on the center of the display area (within 300x300), but I didn't see anything on the screen. After enlarge window, I can see my polygon but it is not within the 300, 300 area I have set
import javax.swing.*;
import java.awt.geom.AffineTransform;
public class PolygonExample extends JFrame{
public PolygonExample(){
super("Drawing Red Polygon");
setSize(300, 300);
setVisible (true);
}
public void paint (Graphics g){
super.paint(g);
int xValue[] = {0, 10, 7, -7, -10};
int yValue[] = {-10, -2, 10, 10, -2};
Polygon polygon = new Polygon(xValue, yValue, 5);
g.setColor(Color.RED);
Graphics2D g2d = (Graphics2D) g;
AffineTransform at = new AffineTransform(5., 0., 0., 5., 150., 150.);
g2d.setTransform(at);
g.drawPolygon(polygon);
}
public static void main(String[] args) {
new PolygonExample();
}
}
The code above done what I wanted to do
Thanks @MadProgrammer for the resource
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.