gpt4 book ai didi

java - Q关于Java WindowListener

转载 作者:行者123 更新时间:2023-12-03 18:36:43 24 4
gpt4 key购买 nike

如果您有一个 WindowListener,那么当窗口关闭时 windowDeactivated(WindowEvent) 事件是否总是发生,或者 windowClosing(WindowEvent ) 在没有 windowDeactivated(WindowEvent) 发生的情况下发生。也就是说,窗口停用是窗口关闭的一部分吗?

最后,windowClosed(WindowEvent) 是否总是(通常)跟在 windowClosing(WindowEvent) 之后?

最佳答案

假设JFrame ,结果似乎取决于 setDefaultCloseOperation();获取 WINDOW_CLOSED 事件需要“在窗口上调用 dispose”,例如通过 DISPOSE_ON_CLOSE,如前所述 here .

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;

/** @see http://stackoverflow.com/questions/2141325 */
public class MyPanel extends JPanel {

private static final Random RND = new Random();
private static final WindowAdapter listener = new WindowAdapter() {

@Override
public void windowClosed(WindowEvent e) {
print(e);
}

@Override
public void windowClosing(WindowEvent e) {
print(e);
}

@Override
public void windowDeactivated(WindowEvent e) {
print(e);
}

private void print(WindowEvent e) {
System.out.println(e.getWindow().getName() + ":" + e);
}
};

public MyPanel() {
this.setBackground(new Color(RND.nextInt()));
}

@Override
public Dimension getPreferredSize() {
return new Dimension(320, 240);
}

private static void create() {
for (int i = 0; i < 2; i++) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setTitle(String.valueOf(i));
f.add(new MyPanel());
f.addWindowListener(listener);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {

@Override
public void run() {
create();
}
});
}
}

关于java - Q关于Java WindowListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2141325/

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