PatrickDickey
PatrickDickey

Reputation: 133

Two questions on using Window Listeners in Java Swing Desktop Applications

**** Please note that my question is regarding the answers in another thread. However, when I posted the question in that thread, it was deleted. So I'm reposting the question here (with a link to the exact post that I'm referring to). ****

I have a couple of questions that go along with this thread. If I have a Timer (updateTimer), which I want to cancel when the window is closing, can I put that in place of the System.out.println("Windows Closing"); statement? Or would I have to put it in the actual "View" class (I have three classes DesktopApplication.App, DesktopApplication.View, and DesktopApplication.AboutBox and the configure Window method is in the .App class).

Along that line, if I can put the updateTimer.cancel(); line in, then does this mean I can read/write from a file, and popluate textboxes also (WindowOpen event) and write the information to the file in the closing event?

What I want to do is the following: When my application starts (and the main window opens) I want to check for a configuration file. If it exists, then I want to get the username, password, tunnel ID, and IP Address from that file--and populate their respective text boxes in the main jPanel. If it doesn't exist, then I won't do anything with it.

On closing the application, I want two things to happen: 1) any UpdateTimers that are running will be cancelled (to effectively and cleanly close the application) and 2) write the username, password, tunnel ID and IP Address to the configuration file for the next run.

I've created the file in Netbeans, so the "exitMenu" is automatically generated, and there is no "close button" configured. So I need to use WindowClosing to accomplish this (or hack the "exitMenu" method in a text editor and hope it doesn't create issues with Netbeans).

I should also add that the username and password are actually MD5 hashes of the real username and password. So, while someone can possibly open the text file and read them, they'll only see something like this:

c28de38997efb893872d893982ac 3289ab83ce8f398289d938999cab 12345 192.168.2.2

Thanks, and have a great day:)

Patrick. Edited to include information about the "Username and Password" that will be stored.

Upvotes: 1

Views: 837

Answers (2)

PatrickDickey
PatrickDickey

Reputation: 133

How I ended up accomplishing this is like this.

In my "TunnelbrokerUpdateView" class (the one that actually handles the main frame), I added the following code:

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);
}

I added this into the "public TunnelbrokerUpdateView(SingleFrameApplication app)" method. So, everything works as I wanted it to. I'm sure there are better ways of incorporating the user information, but this was quick and dirty. In the future, I do plan on encrypting the data (or making it into a format that isn't readable normally), since there's a password hash involved.

Hopefully this will help someone else in the future.

(for reference, here's the entire method (including the stuff that Netbeans automatically puts in)

    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);
}

Have a great day:) Patrick.

Upvotes: 0

sbridges
sbridges

Reputation: 25150

can I put that in place of the System.out.println("Windows Closing"); statement?

Yes, you can put arbitrary code in your listener

Along that line, if I can put the updateTimer.cancel(); line in, then does this mean I can read/write from a file, and popluate textboxes also (WindowOpen event) and write the information to the file in the closing event?

Yes

Upvotes: 1

Related Questions