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

时间:2012-02-13 20:32:02

标签: java swing events listener awt

我有这个基本的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
    }
}

编辑: 按照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
    }
}

3 个答案:

答案 0 :(得分:7)

添加组件侦听器,并实现componentResizedLook here

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

答案 1 :(得分:4)

  1. 不要混合AWT&没有充分理由摆动组件(这种使用并不是很好的理由)。您可以使用CanvasJComponent代替JPanel
  2. 此处没有用于检测调整大小的用例。如果调整用户界面的大小,则会调用自定义呈现组件的paint()paintComponent(),您只需getWidth() / getHeight()即可发现呈现区域的大小

答案 2 :(得分:1)

根据我的经验,当AWT Canvas嵌套在JPanel中时,Canvas的paint()方法在窗口展开时调用,而不是在缩小窗口时调用。因此,Canvas可以成长但不会缩减。我用JComponent的子类化重构了子类化的Canvas。