如何调整此Java应用程序的大小时,我该如何监听?

fle*_*ale 2 java events swing awt listener

我有这个基本的Java应用程序,dim_xdim_y代表窗口和它内部的画布的尺寸.如何在用户更改窗口大小时更改这些值,以便画布上绘制的内容相应缩小/扩展?

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
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:按照Binyamin的回答,我尝试添加这个有效,但是有更好的方法吗?如果没有制作canvas静电,也许?

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
    }
}
Run Code Online (Sandbox Code Playgroud)

MBy*_*ByD 7

添加组件侦听器,并实现componentResized.看这里.

frame.addComponentListener(new ComponentListener(){
    @Override
    public void componentResized(ComponentEvent e) {
        //Get size of frame and do cool stuff with it   
    }
}
Run Code Online (Sandbox Code Playgroud)