I have this basic Java application in witch dim_x and dim_y represent the dimensions of the window and the canvas within it. How can I get these values to change as the user changes the size of the window so that what is drawn on the canvas shrinks/expands accordingly?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MLM extends Canvas {
static int dim_x = 720;
static int dim_y = 480;
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Canvas canvas = new MLM();
canvas.setSize(dim_x, dim_y);
frame.getContentPane().add(canvas);
frame.pack();
frame.setVisible(true);
}
public void paint(Graphics g) {
// some stuff is drawn here using dim_x and dim_y
}
}
EDIT:
following Binyamin’s answer I’ve tried adding this which works, but is there a better way to do it? As in, with not making canvas static, maybe?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MLM extends Canvas {
static int dim_x = 720;
static int dim_y = 480;
static Canvas canvas;
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
canvas = new MLM();
canvas.setSize(dim_x, dim_y);
frame.getContentPane().add(canvas);
frame.pack();
frame.setVisible(true);
frame.addComponentListener(new ComponentListener(){
public void componentResized(ComponentEvent e) {
Dimension d = canvas.getSize();
dim_x = d.width;
dim_y = d.height;
}
public void componentHidden(ComponentEvent e) {}
public void componentMoved(ComponentEvent e) {}
public void componentShown(ComponentEvent e) {}
});
}
public void paint(Graphics g) {
// some stuff is drawn here using dim_x and dim_y
}
}
Add a component listener, and implement
componentResized. Look here.