java - WindowListener 未按预期工作

标签 java swing jframe listener

我希望我的 GUI 在出现 JOptionPane 时进行一些检查。 因为我找不到任何其他方法,所以我可以在每次应用程序窗口失去焦点时执行这些操作(它只是检查一个字符串)。为此,我在我的 JFrame 上添加了以下代码:

appFrame.addWindowListener(new WindowAdapter() {

            @Override
            public void windowLostFocus(WindowEvent e) {
                System.out.println("Focus Lost");

            }
            @Override
            public void windowClosing(WindowEvent e) {
                //some other stuff here that work
            }
});

窗口关闭监听器工作正常。尽管当 JFrame 没有聚焦时什么也没有发生。每次我从 JFrame 切换到其他窗口时,不应该打印“Focus Lost”吗?另外,当显示 JOptionPane 时会触发此方法吗?

最佳答案

对我来说关键是您希望通过更改字符串变量来触发 GUI 的更改。我认为解决此问题的最佳方法是使用 PropertyChangeListenerSupport 使 String 变量成为绑定(bind)属性。通过这种方式,您可以让 GUI 将 PropertyChangeListener 附加到包含 String 变量的类,然后在它发生变化时收到通知,从而允许您适本地更新 GUI。

如果您选择这条路线,请考虑为被观察类提供一个 SwingPropertyChangeSupport 字段,以便在 Swing 事件线程上通知监听器并希望避免任何 Swing 并发问题。

这是一个简单的例子:

import java.awt.Dimension;
import java.awt.event.*;
import java.beans.*;
import javax.swing.*;
import javax.swing.event.SwingPropertyChangeSupport;

public class ShowPropertyChangeSupport {
   @SuppressWarnings("serial")
   private static void createAndShowGui() {
      final MainGUI mainGui = new MainGUI("Title");
      final ObservedClass observedClass = new ObservedClass();
      observedClass.addPropertyChangeListener(new PropertyChangeListener() {

         @Override
         public void propertyChange(PropertyChangeEvent pcEvt) {
            if (pcEvt.getPropertyName().equals(ObservedClass.BOUND_PROPERTY)) {
               mainGui.setTitle(pcEvt.getNewValue().toString());
            }
         }
      });

      mainGui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      mainGui.pack();
      mainGui.setLocationRelativeTo(null);
      mainGui.setVisible(true);

      int timerDelay = 6000; // every 6 seconds
      new Timer(timerDelay, new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent arg0) {
            String result = JOptionPane.showInputDialog(mainGui,
                  "Please enter a String", "Set GUI title", JOptionPane.PLAIN_MESSAGE);
            if (result != null) {
               observedClass.setBoundProperty(result);
            }
         }
      }){{setInitialDelay(1000);}}.start();
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

// ** note that I don't like extending JFrame,
// but will do this for sake of example simplicity
class MainGUI extends JFrame {
   public MainGUI(String title) {
      super(title);
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(400, 300);
   }

}

class ObservedClass {
   public static final String BOUND_PROPERTY = "bound property";
   private String boundProperty = "";
   private SwingPropertyChangeSupport spcSupport = new SwingPropertyChangeSupport(
         this);

   public SwingPropertyChangeSupport getSpcSupport() {
      return spcSupport;
   }

   public void setSpcSupport(SwingPropertyChangeSupport spcSupport) {
      this.spcSupport = spcSupport;
   }

   public String getBoundProperty() {
      return boundProperty;
   }

   public void setBoundProperty(String boundProperty) {
      String oldValue = this.boundProperty;
      String newValue = boundProperty;
      this.boundProperty = newValue;
      spcSupport.firePropertyChange(BOUND_PROPERTY, oldValue, newValue);
   }

   public void addPropertyChangeListener(PropertyChangeListener listener) {
      spcSupport.addPropertyChangeListener(listener);
   }

   public void removePropertyChangeListener(PropertyChangeListener listener) {
      spcSupport.removePropertyChangeListener(listener);
   }

}

在我看来,所有这一切的关键是使用监听器,以便具有绑定(bind)属性的类——被监听的字符串——不知道 GUI、监听器和 GUI,同样没有具有绑定(bind)属性的类的知识。它们完全解耦。

关于java - WindowListener 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10198936/

相关文章:

java - 图形用户界面 : JButton Covering almost the entire screen

java - 求直角三角形的斜边

java - 为什么 java.lang.Iterable.forEach() 会调用 requireNonNull()?

java - 使用修订 ID 检索 CouchDB 文档的先前修订?

java - 为什么 SwingUtilities.invokeLater() 会导致 JButton 卡住?

java - Swing 绘制在不正确的坐标上

java - 包含相同值的 HashMap

将图像显示到 JFrame 时出现 java.lang.NullPointerException

Java JInternalFrame 到 JPanel

java - JFrame 删除 JPanel 并添加新的 JPanel