I am kind of stuck at maintaining aspect ratio on my JPanel
.
I have default generated JFrame
from Netbeans with Border layout. Whole frame is filled with my JPanel
(from my custom class GraphicsPanel.java extending JPanel
).
GraphicsPanel class have only one over ridden method for drawing graphics with some basic constructor. I have one rectangle and polygon on my JPanel
.
What I'm trying to achieve is when I re-size the frame I want to keep my JPanel
on aspect ratio 4:3 (or something similar to it). When the frame is too big for aspect ratio it will fill the frame back ground with some default color.
I've read some topics about aspect ratio (for example this). But no luck and I still have no clue how to do it.
There's my code from my JPanel
class. I'm beginner and I'm trying to learn how to work with Java graphics (draw, fill, resize etc) so please go easy on me.
import java.awt.Color;
import java.awt.Graphics;
public class GraphicsPanel extends javax.swing.JPanel {
private int x;
private int z;
private int y;
public GraphicsPanel() { //constructor
initComponents();
x = getHeight() / 2;
z = getWidth() / 2;
y = getHeight() - 1;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
x = getHeight() / 2;
z = getWidth() / 2;
y = getHeight() - 1;
setBackground(new Color(255, 255, 255));
g.setColor(Color.red);
g.fillRect(0, x, getWidth() - 1, y);
g.setColor(Color.blue);
int[] poleX = {0, 0, z};
int[] poleY = {0, y, x};
g.fillPolygon(poleX, poleY, 3);
}
}