Java 窗口大小调整事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2303305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:53:16  来源:igfitidea点击:

Window resize event?

javaswing

提问by Ameer Jewdaki

我正在使用 java 编写一个简单的绘画程序,我希望在调整 JFrame 组件大小时调用一些方法。但是我找不到像 windowResizedListener 这样的任何方法或像 windowResizedEvent 这样的事件。

我能做什么?!

采纳答案by Yuval Adam

Implement a ComponentAdapterwith componentResized():

实现一个ComponentAdapter具有componentResized()

frame.addComponentListener(new ComponentAdapter() {
    public void componentResized(ComponentEvent componentEvent) {
        // do stuff
    }
});

回答by Valentin Rocher

You have to use componentResizedfrom ComponentListener.

您必须使用componentResizedfrom ComponentListener

回答by trashgod

Overriding particular methods of ComponentAdapteris a convenient alternative to implementing all the methods of ComponentListener.

覆盖 的特定方法ComponentAdapter是实现 的所有方法的便捷替代方法ComponentListener

回答by maximusg

To access the Window Re-size method event I used Implement ComponentListener inside a subclass. This is a custom JPanel class you can use to write the window-size to a JLabel inside a GUI. Just implement this class in your main method and add it to your JFrame and you can resize the window and it will dynamically show you the Pixel size of your window. (Note you must add your JFrame object to the Class)

为了访问 Window Re-size 方法事件,我在子类中使用了Implement ComponentListener。这是一个自定义 JPanel 类,可用于将窗口大小写入 GUI 内的 JLabel。只需在您的 main 方法中实现这个类并将其添加到您的 JFrame 中,您就可以调整窗口的大小,它会动态地向您显示窗口的像素大小。(请注意,您必须将 JFrame 对象添加到类中)

package EventHandledClasses;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentListener;
public class DisplayWindowWidth extends JPanel{
JLabel display;
JFrame frame;
public DisplayWindowWidth(JFrame frame){
        display = new JLabel("---");
        this.frame = frame;

        frame.addComponentListener(new FrameListen());
        add(display);
        setBackground(Color.white);
    }

    private class FrameListen implements ComponentListener{
        public void componentHidden(ComponentEvent arg0) {
        }
        public void componentMoved(ComponentEvent arg0) {   
        }
        public void componentResized(ComponentEvent arg0) {
            String message = " Width: " +
            Integer.toString(frame.getWidth());
            display.setText(message);

        }
        public void componentShown(ComponentEvent arg0) {

        }
    }
}

回答by Eduardo Oliveros

An example with ComponentAdapter

ComponentAdapter 示例

//Detect windows changes
window.addComponentListener(new ComponentAdapter( ) {
  public void componentResized(ComponentEvent ev) {
   label.setText(ev.toString());
  }
});