【问题标题】:Two questions on using Window Listeners in Java Swing Desktop ApplicationsJava Swing桌面应用中使用Window Listeners的两个问题
【发布时间】:2011-04-25 11:46:13
【问题描述】:

**** 请注意,我的问题是关于另一个线程中的答案。但是,当我在该线程中发布问题时,它被删除了。所以我在这里重新发布这个问题(带有指向我所指的确切帖子的链接)。 ****

我有几个与此 thread 相关的问题。如果我有一个计时器 (updateTimer),我想在窗口关闭时取消它,我可以用它代替 System.out.println("Windows Closing");陈述?或者我是否必须将它放在实际的“视图”类中(我有三个类 DesktopApplication.App、DesktopApplication.View 和 DesktopApplication.AboutBox,并且配置窗口方法在 .App 类中)。

沿着这条线,如果我可以把 updateTimer.cancel(); line in,那么这是否意味着我可以从文件中读取/写入,也可以填充文本框(WindowOpen 事件)并在关闭事件中将信息写入文件?

我想要做的是:当我的应用程序启动(并且主窗口打开)时,我想检查配置文件。如果它存在,那么我想从该文件中获取用户名、密码、隧道 ID 和 IP 地址——并在主 jPanel 中填充它们各自的文本框。如果它不存在,那么我不会对它做任何事情。

在关闭应用程序时,我希望发生两件事:1) 任何正在运行的 UpdateTimer 都将被取消(以有效和干净地关闭应用程序)和 2) 将用户名、密码、隧道 ID 和 IP 地址写入下次运行的配置文件。

我在Netbeans中创建了文件,所以“exitMenu”是自动生成的,没有配置“关闭按钮”。所以我需要使用 WindowClosing 来完成这个(或者破解文本编辑器中的“exitMenu”方法,希望它不会对 Netbeans 造成问题)。

我还应该补充一点,用户名和密码实际上是真实用户名和密码的 MD5 哈希值。因此,虽然有人可能会打开文本文件并阅读它们,但他们只会看到如下内容:

c28de38997efb893872d893982ac 3289ab83ce8f398289d938999cab 12345 192.168.2.2

谢谢,祝你有美好的一天:)

帕特里克。 已编辑以包含有关将存储的“用户名和密码”的信息。

【问题讨论】:

  • 你当然可以在窗口关闭事件中取消定时器。
  • 感谢您的回答。我想我的问题真的是“这需要进入哪个类文件?”由于尝试将其放入 App 文件似乎不起作用(@Override Configure Windows 方法所在的位置)。所以我想我必须将它手动编码到“视图”类文件中(显示主 JPanel 和其他所有内容的文件)。

标签: java swing netbeans listeners jsr296


【解决方案1】:

我可以用它代替 System.out.println("Windows Closing");陈述?

是的,你可以在你的监听器中放任意代码

沿着这条线,如果我可以把 updateTimer.cancel(); line in,那么这是否意味着我可以从文件中读取/写入,也可以填充文本框(WindowOpen 事件)并在关闭事件中将信息写入文件?

是的

【讨论】:

  • 感谢您的快速回答。我会试试看,但我应该问我是否需要做任何特别的事情(因为 UpdateTimer 的声明在 .View 文件中)。
  • 好的,所以我昨天试过了,但是没有用。我认为最后,我必须将代码放入 TunnelBrokerUpdateView.java 类文件(而不是其他线程中建议的 TunnelBrokerUpdateApp.java 类文件)。主要问题是 Netbeans 6.9.1 并不容易。当您单击主 JPanel 时,您会认为他们有“窗口侦听器”或“窗口关闭”的右键单击选项。没有。所以,现在只好手动添加监听器,希望能把它放在正确的位置(因为initComponents()方法是form自动生成的)。
【解决方案2】:

我最终是如何做到这一点的。

在我的“TunnelbrokerUpdateView”类(实际处理主框架的类)中,我添加了以下代码:

WindowListener wl = new WindowListener(){

        public void windowOpened(WindowEvent e)
        {
            try
            {
                     FileReader fr = new FileReader (new File("userinfo.txt"));
                     BufferedReader br = new BufferedReader (fr);
                     jTextField1.setText(br.readLine());
                     jPasswordField1.setText(br.readLine());
                     jTextField2.setText(br.readLine());
                     oldIPAddress = br.readLine();
                     br.close();
             }
             catch (FileNotFoundException ex) {
                    // Pop up a dialog box explaining that this information will be saved
                 // and propogated in the future.. "First time running this?"
                    int result = JOptionPane.showConfirmDialog((Component)
            null, "After you enter your user information, this box will no longer show.", "First Run", JOptionPane.DEFAULT_OPTION);
        }
            catch (java.io.IOException ea)
            {
                Logger.getLogger(TunnelbrokerUpdateView.class.getName()).log(Level.SEVERE, null, ea);
            }
        }

        public void windowClosing(WindowEvent e) {
            updateTimer.cancel();
            BufferedWriter userData;

            //Handle saving the user information to a file "userinfo.txt"
            try
            {
                userData = new BufferedWriter(new FileWriter("userinfo.txt"));
                StringBuffer sb = new StringBuffer();
                sb.append(jTextField1.getText());
                sb.append(System.getProperty("line.separator"));
                sb.append(jPasswordField1.getText());
                sb.append(System.getProperty("line.separator"));
                sb.append(jTextField2.getText());
                sb.append(System.getProperty("line.separator"));
                sb.append(oldIPAddress);
                userData.write(sb.toString());
                userData.close();

            }
            catch (java.io.IOException ex)
            {
                Logger.getLogger(TunnelbrokerUpdateView.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        public void windowClosed(WindowEvent e) {
            System.exit(0);
        }

        public void windowIconified(WindowEvent e) {}

        public void windowDeiconified(WindowEvent e) {}

        public void windowActivated(WindowEvent e) {}

        public void windowDeactivated(WindowEvent e) {}

    };
    super.getFrame().addWindowListener(wl);
}

我将此添加到“公共 TunnelbrokerUpdateView(SingleFrameApplication app)”方法中。所以,一切都如我所愿。我确信有更好的方法来整合用户信息,但这又快又脏。将来,我确实计划加密数据(或将其制成无法正常读取的格式),因为其中涉及密码哈希。

希望这将在未来对其他人有所帮助。

(供参考,这是整个方法(包括Netbeans自动放入的东西)

    public TunnelbrokerUpdateView(SingleFrameApplication app) {
    super(app);


    initComponents();




    // status bar initialization - message timeout, idle icon and busy animation, etc
    ResourceMap resourceMap = getResourceMap();
    int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
    messageTimer = new Timer(messageTimeout, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            statusMessageLabel.setText("");
        }
    });
    messageTimer.setRepeats(false);
    int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
    for (int i = 0; i < busyIcons.length; i++) {
        busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
    }
    busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
            statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
        }
    });
    idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
    statusAnimationLabel.setIcon(idleIcon);
    progressBar.setVisible(false);

    // connecting action tasks to status bar via TaskMonitor
    TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
    taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
        public void propertyChange(java.beans.PropertyChangeEvent evt) {
            String propertyName = evt.getPropertyName();
            if ("started".equals(propertyName)) {
                if (!busyIconTimer.isRunning()) {
                    statusAnimationLabel.setIcon(busyIcons[0]);
                    busyIconIndex = 0;
                    busyIconTimer.start();
                }
                progressBar.setVisible(true);
                progressBar.setIndeterminate(true);
            } else if ("done".equals(propertyName)) {
                busyIconTimer.stop();
                statusAnimationLabel.setIcon(idleIcon);
                progressBar.setVisible(false);
                progressBar.setValue(0);
            } else if ("message".equals(propertyName)) {
                String text = (String)(evt.getNewValue());
                statusMessageLabel.setText((text == null) ? "" : text);
                messageTimer.restart();
            } else if ("progress".equals(propertyName)) {
                int value = (Integer)(evt.getNewValue());
                progressBar.setVisible(true);
                progressBar.setIndeterminate(false);
                progressBar.setValue(value);
            }
        }
    });

    // This will take care of Opening and Closing
    WindowListener wl = new WindowListener(){

        public void windowOpened(WindowEvent e)
        {
            try
            {
                     FileReader fr = new FileReader (new File("userinfo.txt"));
                     BufferedReader br = new BufferedReader (fr);
                     jTextField1.setText(br.readLine());
                     jPasswordField1.setText(br.readLine());
                     jTextField2.setText(br.readLine());
                     oldIPAddress = br.readLine();
                     br.close();
             }
             catch (FileNotFoundException ex) {
                    // Pop up a dialog box explaining that this information will be saved
                 // and propogated in the future.. "First time running this?"
                    int result = JOptionPane.showConfirmDialog((Component)
            null, "After you enter your user information, this box will no longer show.", "First Run", JOptionPane.DEFAULT_OPTION);
        }
            catch (java.io.IOException ea)
            {
                Logger.getLogger(TunnelbrokerUpdateView.class.getName()).log(Level.SEVERE, null, ea);
            }
        }

        public void windowClosing(WindowEvent e) {
            updateTimer.cancel();
            BufferedWriter userData;

            //Handle saving the user information to a file "userinfo.txt"
            try
            {
                userData = new BufferedWriter(new FileWriter("userinfo.txt"));
                StringBuffer sb = new StringBuffer();
                sb.append(jTextField1.getText());
                sb.append(System.getProperty("line.separator"));
                sb.append(jPasswordField1.getText());
                sb.append(System.getProperty("line.separator"));
                sb.append(jTextField2.getText());
                sb.append(System.getProperty("line.separator"));
                sb.append(oldIPAddress);
                userData.write(sb.toString());
                userData.close();

            }
            catch (java.io.IOException ex)
            {
                Logger.getLogger(TunnelbrokerUpdateView.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        public void windowClosed(WindowEvent e) {
            System.exit(0);
        }

        public void windowIconified(WindowEvent e) {}

        public void windowDeiconified(WindowEvent e) {}

        public void windowActivated(WindowEvent e) {}

        public void windowDeactivated(WindowEvent e) {}

    };
    super.getFrame().addWindowListener(wl);
}

祝你有美好的一天:) 帕特里克。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 2012-12-12
    • 1970-01-01
    • 2010-11-26
    • 2011-11-21
    • 1970-01-01
    • 2011-09-17
    相关资源
    最近更新 更多