简体   繁体   中英

Resizing Jpanel when resizing JFrame

I need to draw a xy axis coordinate system on a JPanel. I want to implement a function that when resize JFrame, the x,y axis coordinate can resize automatically.

public void paintComponent(Graphics gl) {

 Graphics2D g = (Graphics2D) gl;
 g.setColor(new Color(222, 222, 222));
 g.fillRect(0, 0, this.getWidth(), this.getHeight());
 g.setColor(new Color(0, 0, 0));
 int x=15;
 int y=15;
 g.drawString("20", 0, 10);
 for(int i=1;i<=20;i++) {
     g.drawLine(x, y+(35*(i-1)), x, y+(35*i));
     g.drawString(""+(20-i), 0, y+(35*i));
 }
 for(int i=1;i<=10;i++) {
     g.drawLine(x+(70*(i-1)),715, x+(70*i), 715);
     g.drawString(""+i,  x+(70*i),730);
 }
}

This is how I draw the xy coordinate system.
Could you give me hint for resizing it ?

Use an ComponentListener and listen to the resize Events fired up. Invalidate your UI to force an repaint which cause your paintComponent will be called.

ComponentListener

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM