简体   繁体   中英

Java - Set JPanel to fixed size and scale it to window

I want my JPanel to be fixed size of 800x600, but if JFrame size changes, JPanel will scale, keeping original size of 800x600. For example, if I draw a string on JPanel, and stretch window 2 times, string will be stretched 2 times too.

I tried

g2d.scale(frame.getWidth() / 800, frame.getHeight() / 600);

But if I change width of frame to 0.5, the color on background (used g2d.fillRect after g2d.scale ) will cover only half of frame.

First thing i can say in Swing, never paint by yourself and use LayoutManager for layouting. When you really have to draw by yourself, create a new Graphics2d from the original and dispose after usage. On this Graphics you can set your properties.

At first i would consider putting the Panel in a BorderLayout(Center) inside the Frame. Without your code its quite hard to know how to help you.

Found a solution to this problem.

Created BufferedImage at creation of Panel, ie

bimg = new BufferedImage(800, 600, BufferedImage.TYPE_INT_RGB);

Got graphics out of it, ie

g2d = bimg.createGraphics();

Performed all drawing operations on it, then drawn the scaled image on JPanel.

    g.drawImage(bimg, 0, 0, getWidth(), getHeight(), null);

(Where getXX() returns XX of panel). After resizing the window, it clearly looks that background and string, drawn on BufferedImage, are stretched, keeping original size same.

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