<chunkynotes version="1.0" title="Java Swing">
   <summary>JAVA Swing GUI tips and howtos.</summary>

<intro>
</intro>

<chunk title="Opening and saving files using a JFileChooser">
<p>This example shows how to use a single filechooser to open and save. The
filechooser will remember the directory it entered last which makes it a lot
easier for the user. openFile and saveFile can be buttons or menu items with
an ActionListener.</p>
<sample>
<src>
   public void actionPerformed(ActionEvent event)
   {
      Object source = event.getSource();

      if (source == openFile)
      {
         if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
         {
            try
            {
               File file = fileChooser.getSelectedFile(); //get file(path+name)
               BufferedReader in = new BufferedReader (new FileReader(file));
               //in.readLine() etc
            }
            catch (Exception e) { //ignore...
            }
         }
         else { //user cancelled...
         }
      }
      else if (source == saveFile)
      {
         if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
         {
            try
            {
               File file = fileChooser.getSelectedFile();
               PrintWriter out = new PrintWriter(file);
               //out.print() etc
               out.close();
            }
            catch (Exception e) { //ignore...
            }
         }
         else { //user cancelled...
         }
      }
</src>
</sample>
</chunk>

<chunk title="Making JPopupMenu pop up">
<p>Create the JPopupMenu and add JMenuItems to it (and ActionListeners to the
items) like a normal JMenu. But instead of adding it to a menubar, wrap it in
a class that implements MouseAdapter, and use addMouseListener() to add the
listener to the item to popup over:</p>
<sample>
<src>rightClickMeComponent.addMouseListener(new PopupListener(popupMenu))</src>
</sample>

<p>You create the PopupListener class - it needs to call popupMenu.show() to
show the popup when the events are right. This sample PopupListener is a
slightly modified version of the one from
<a href="http://java.sun.com/docs/books/tutorial/index.html">The Java
Tutorial:</a></p>
<sample>
<src>
public class PopupListener extends MouseAdapter
{
   JPopupMenu popup;

   PopupListener(JPopupMenu popupMenu)
   {
         popup = popupMenu;
   }

   public void mousePressed(MouseEvent e)
   {
         if (e.isPopupTrigger())
             popup.show(e.getComponent(), e.getX(), e.getY());
   }

   public void mouseReleased(MouseEvent e)
   {
         if (e.isPopupTrigger())
             popup.show(e.getComponent(), e.getX(), e.getY());
   }
}
</src>
</sample>
</chunk>

</chunkynotes>
