gpt4 book ai didi

java - 我如何监听此 Java 应用程序何时调整大小?

转载 作者:行者123 更新时间:2023-12-02 11:13:00 25 4
gpt4 key购买 nike

我有这个基本的 Java 应用程序,其中 dim_xdim_y 代表窗口及其内部 Canvas 的尺寸。当用户更改窗口大小时,如何使这些值发生变化,以便 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;

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
}
}

最佳答案

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

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

关于java - 我如何监听此 Java 应用程序何时调整大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9267574/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com