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
Window resize event?
提问by Ameer Jewdaki
采纳答案by Yuval Adam
Implement a ComponentAdapter
with componentResized()
:
实现一个ComponentAdapter
具有componentResized()
:
frame.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent componentEvent) {
// do stuff
}
});
回答by Valentin Rocher
You have to use componentResized
from ComponentListener.
您必须使用componentResized
from ComponentListener。
回答by trashgod
Overriding particular methods of ComponentAdapter
is 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());
}
});