psmith      2003/08/27 22:39:04

  Modified:    src/java/org/apache/log4j/chainsaw LogUI.java
                        NoReceiversWarningPanel.java
  Log:
  Hooked up the new No Receivers warning panel.
  
  I have not had time to hook up the "Remember the
  chosen  config URL" function to this panel, and I would
  like to display a warning icon in the Dialog like
  the JOptionPanel gave us, but that will have to wait
  for next time.
  
  Revision  Changes    Path
  1.8       +165 -128  jakarta-log4j/src/java/org/apache/log4j/chainsaw/LogUI.java
  
  Index: LogUI.java
  ===================================================================
  RCS file: /home/cvs/jakarta-log4j/src/java/org/apache/log4j/chainsaw/LogUI.java,v
  retrieving revision 1.7
  retrieving revision 1.8
  diff -u -r1.7 -r1.8
  --- LogUI.java        7 Aug 2003 07:56:04 -0000       1.7
  +++ LogUI.java        28 Aug 2003 05:39:04 -0000      1.8
  @@ -123,8 +123,8 @@
   import javax.swing.JCheckBoxMenuItem;
   import javax.swing.JComboBox;
   import javax.swing.JComponent;
  +import javax.swing.JDialog;
   import javax.swing.JEditorPane;
  -import javax.swing.JFileChooser;
   import javax.swing.JFrame;
   import javax.swing.JLabel;
   import javax.swing.JMenu;
  @@ -153,7 +153,6 @@
   import javax.swing.event.ListSelectionListener;
   import javax.swing.event.TableColumnModelEvent;
   import javax.swing.event.TableColumnModelListener;
  -import javax.swing.filechooser.FileFilter;
   import javax.swing.table.AbstractTableModel;
   import javax.swing.table.TableColumn;
   import javax.swing.table.TableColumnModel;
  @@ -217,6 +216,8 @@
     private ChainsawAbout aboutBox;
     private final SettingsManager sm = SettingsManager.getInstance();
     private String lookAndFeelClassName;
  +  private final NoReceiversWarningPanel noReceiversWarningPanel =
  +    new NoReceiversWarningPanel();
   
     /**
      * Set to true, if and only if the GUI has completed
  @@ -227,21 +228,20 @@
      */
     private boolean isGUIFullyInitialized = false;
     private Object initializationLock = new Object();
  -  
  +
     /**
      * The shutdownAction is called when the user requests to exit
      * Chainsaw, and by default this exits the VM, but
      * a developer may replace this action with something that better suits
      * their needs
      */
  -  private Action shutdownAction = new AbstractAction() {
  +  private Action shutdownAction =
  +    new AbstractAction() {
  +      public void actionPerformed(ActionEvent e) {
  +        System.exit(0);
  +      }
  +    };
   
  -    public void actionPerformed(ActionEvent e)
  -    {
  -      System.exit(0);
  -    }
  -  };
  -  
     /**
      * Clients can register a ShutdownListener to be notified
      * when the user has requested Chainsaw to exit.
  @@ -280,25 +280,25 @@
   
     /**
      * Registers a ShutdownListener with this calss so that
  -   * it can be notified when the user has requested 
  +   * it can be notified when the user has requested
      * that Chainsaw exit.
  -   * 
  +   *
      * @param l
      */
     public void addShutdownListener(ShutdownListener l) {
  -    shutdownListenerList.add(ShutdownListener.class, l);  
  +    shutdownListenerList.add(ShutdownListener.class, l);
     }
  -  
  +
     /**
  -   * Removes the registered ShutdownListener so 
  +   * Removes the registered ShutdownListener so
      * that the listener will not be notified on a shutdown.
  -   * 
  +   *
      * @param l
      */
     public void removeShutdownListener(ShutdownListener l) {
       shutdownListenerList.remove(ShutdownListener.class, l);
     }
  -  
  +
     /**
      * Starts Chainsaw by attaching a new instance to the Log4J
      * main root Logger via a ChainsawAppender, and activates itself
  @@ -404,15 +404,19 @@
   
             //if both a config file are defined and a log4j.configuration property 
are set,  
             //don't use configFile's configuration
  -          if ((configFile != null) && !configFile.trim().equals("") && 
System.getProperty("log4j.configuration") == null) {
  +          if (
  +            (configFile != null) && !configFile.trim().equals("")
  +              && (System.getProperty("log4j.configuration") == null)) {
               try {
                 URL url = new URL(configFile);
                 OptionConverter.selectAndConfigure(
                   url, null, LogManager.getLoggerRepository());
  -                if (LogUI.this.getStatusBar() != null) {
  -                   LogUI.this.getStatusBar().setMessage(
  -                     "Configured Log4j using remembered URL :: " + url);
  -                }
  +
  +              if (LogUI.this.getStatusBar() != null) {
  +                LogUI.this.getStatusBar().setMessage(
  +                  "Configured Log4j using remembered URL :: " + url);
  +              }
  +
                 LogUI.this.configURLToUse = url;
               } catch (Exception e) {
                 LogLog.error("error occurred initializing log4j", e);
  @@ -425,6 +429,34 @@
           }
         });
   
  +    /**
  +     * This listener sets up the NoReciversWarningPanel and
  +     * loads saves the configs/logfiles
  +     */
  +    sm.addSettingsListener(
  +      new SettingsListener() {
  +        public void loadSettings(LoadSettingsEvent event) {
  +          int size = event.asInt("SavedConfigs.Size");
  +          Object[] configs = new Object[size];
  +
  +          for (int i = 0; i < size; i++) {
  +            configs[i] = event.getSetting("SavedConfigs." + i);
  +          }
  +
  +          noReceiversWarningPanel.getModel().setRememberedConfigs(configs);
  +        }
  +
  +        public void saveSettings(SaveSettingsEvent event) {
  +          Object[] configs =
  +            noReceiversWarningPanel.getModel().getRememberedConfigs();
  +          event.saveSetting("SavedConfigs.Size", configs.length);
  +
  +          for (int i = 0; i < configs.length; i++) {
  +            event.saveSetting("SavedConfigs." + i, configs[i].toString());
  +          }
  +        }
  +      });
  +
       if (
         PluginRegistry.getPlugins(
             LogManager.getLoggerRepository(), Receiver.class).size() == 0) {
  @@ -498,9 +530,9 @@
           //received a statechange event - selection changed - remove icon from 
selected index
           public void stateChanged(ChangeEvent e) {
             if (tabbedPane.getSelectedComponent() instanceof ChainsawTabbedPane) {
  -             if (tabbedPane.getSelectedIndex() > -1) {
  -             tabbedPane.setIconAt(tabbedPane.getSelectedIndex(), null);
  -             }
  +            if (tabbedPane.getSelectedIndex() > -1) {
  +              tabbedPane.setIconAt(tabbedPane.getSelectedIndex(), null);
  +            }
             }
           }
         });
  @@ -562,7 +594,7 @@
                 LogPanel logPanel = getCurrentLogPanel();
   
                 if (logPanel != null) {
  -                  logPanel.undock();
  +                logPanel.undock();
                 }
               }
             }
  @@ -599,78 +631,69 @@
       }
   
       if (noReceiversDefined) {
  -      SwingUtilities.invokeLater(
  -        new Runnable() {
  -          public void run() {
  -            //            TODO This could be done and look better in a custom Dialog
  -            Object[] options =
  -              new String[] {
  -                "Search for a Log4j config file",
  -                "Allow me to specify Receivers manually",
  -                "Nothing thanks, I'm fine"
  -              };
  -            Object initialSelection = options[0];
  -            Object result =
  -              JOptionPane.showInputDialog(
  -                LogUI.this,
  -                "You have no Receivers defined.\n\nYou will not be able to receive 
events from a Remote source unless you define one in the Log4J configuration file.\n",
  -                "No Receivers Defined", JOptionPane.WARNING_MESSAGE, null,
  -                options, initialSelection);
  -
  -            if (result == options[0]) {
  -              //              TODO search for Log4j config            
  -              JFileChooser chooser = new JFileChooser();
  -              chooser.setDialogTitle("Search for Log4j configuration...");
  -              chooser.setDialogType(JFileChooser.OPEN_DIALOG);
  -              chooser.setFileFilter(
  -                new FileFilter() {
  -                  public boolean accept(File f) {
  -                    return f.isDirectory()
  -                    || f.getName().endsWith(".properties")
  -                    || f.getName().endsWith(".xml");
  -                  }
  +      showNoReceiversWarningPanel();
  +    }
  +  }
   
  -                  public String getDescription() {
  -                    return "Log4j Configuration file";
  -                  }
  -                });
  +  /**
  +   * Displays a warning dialog about having no Receivers defined
  +   * and allows the user to choose some options for configuration
  +   */
  +  private void showNoReceiversWarningPanel() {
  +    SwingUtilities.invokeLater(
  +      new Runnable() {
  +        public void run() {
  +          final JDialog dialog = new JDialog(LogUI.this, true);
  +          dialog.setTitle("Warning: You have no Receivers defined...");
  +          dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
  +
  +          dialog.setResizable(false);
  +
  +          noReceiversWarningPanel.setOkActionListener(
  +            new ActionListener() {
  +              public void actionPerformed(ActionEvent e) {
  +                dialog.setVisible(false);
  +              }
  +            });
   
  -              chooser.showOpenDialog(LogUI.this);
  +          dialog.getContentPane().add(noReceiversWarningPanel);
   
  -              if (chooser.getSelectedFile() != null) {
  -                try {
  -                  OptionConverter.selectAndConfigure(
  -                    chooser.getSelectedFile().toURL(), null,
  -                    LogManager.getLoggerRepository());
  -                  receiversPanel.updateReceiverTreeInDispatchThread();
  -
  -                  //                ask if they want this config URL loaded each 
time
  -                  if (
  -                    JOptionPane.showConfirmDialog(
  -                        LogUI.this,
  -                        "Would you like to use this configuration each time?",
  -                        "Please confirm", JOptionPane.YES_NO_OPTION,
  -                        JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
  -                    configURLToUse = chooser.getSelectedFile().toURL();
  -                  }
  -                } catch (Exception e) {
  -                  LogLog.error(
  -                    "Error using selected config file for configuration", e);
  -                }
  -              } else {
  -                //                TODO handle if they don't choose a file
  -              }
  +          dialog.pack();
   
  -              chooser = null;
  -            }
  +          Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
  +          dialog.setLocation(
  +            (screenSize.width / 2) - (dialog.getWidth() / 2),
  +            (screenSize.height / 2) - (dialog.getHeight() / 2));
  +          dialog.show();
  +
  +          dialog.dispose();
  +
  +          if (noReceiversWarningPanel.getModel().isManualMode()) {
  +            toggleReceiversPanel();
  +          } else if (noReceiversWarningPanel.getModel().isLoadConfig()) {
  +            final URL url =
  +              noReceiversWarningPanel.getModel().getConfigToLoad();
  +
  +            if (url != null) {
  +              LogLog.debug("Initialiazing Log4j with " + url.toExternalForm());
  +
  +              new Thread(
  +                new Runnable() {
  +                  public void run() {
  +                    try {
  +                      OptionConverter.selectAndConfigure(
  +                        url, null, LogManager.getLoggerRepository());
  +                    } catch (Exception e) {
  +                      LogLog.error("Error initializing Log4j", e);
  +                    }
   
  -            if (result == options[1]) {
  -              toggleReceiversPanel();
  -            } else {
  +                    receiversPanel.updateReceiverTreeInDispatchThread();
  +                  }
  +                }).start();
               }
             }
  -        });
  -    }
  +        }
  +      });
     }
   
     /**
  @@ -740,32 +763,38 @@
     }
   
     Map getPanels() {
  -     Map m = new HashMap();
  -     Set panelSet = panelMap.entrySet();
  -     Iterator iter = panelSet.iterator();
  -     while (iter.hasNext()) {
  -             Map.Entry entry = (Map.Entry)iter.next();
  -             m.put(entry.getKey(), 
Boolean.valueOf(((DockablePanel)entry.getValue()).isDocked()));
  -     }
  -     return m;
  +    Map m = new HashMap();
  +    Set panelSet = panelMap.entrySet();
  +    Iterator iter = panelSet.iterator();
  +
  +    while (iter.hasNext()) {
  +      Map.Entry entry = (Map.Entry) iter.next();
  +      m.put(
  +        entry.getKey(),
  +        Boolean.valueOf(((DockablePanel) entry.getValue()).isDocked()));
  +    }
  +
  +    return m;
     }
  -  
  +
     void displayPanel(String panelName, boolean display) {
  -     Object o = panelMap.get(panelName);
  -     if (o instanceof LogPanel) {
  -             LogPanel p = (LogPanel)o;
  -
  -             int index = tabbedPane.indexOfTab(panelName);
  -
  -             if (index == -1 && display) {
  -                     tabbedPane.addTab(panelName, p);
  -             }
  -             if (index > -1 && !display) {
  -                     tabbedPane.removeTabAt(index);
  -             }
  -     }
  +    Object o = panelMap.get(panelName);
  +
  +    if (o instanceof LogPanel) {
  +      LogPanel p = (LogPanel) o;
  +
  +      int index = tabbedPane.indexOfTab(panelName);
  +
  +      if ((index == -1) && display) {
  +        tabbedPane.addTab(panelName, p);
  +      }
  +
  +      if ((index > -1) && !display) {
  +        tabbedPane.removeTabAt(index);
  +      }
  +    }
     }
  -             
  +
     /**
      * Shutsdown by ensuring the Appender gets a chance to close.
      */
  @@ -802,10 +831,10 @@
             } catch (Exception e) {
               e.printStackTrace();
             }
  +
             fireShutdownEvent();
             performShutdownAction();
           }
  -
         };
   
       new Thread(runnable).start();
  @@ -814,9 +843,11 @@
     /**
      * Ensures all the registered ShutdownListeners are notified.
      */
  -  private void fireShutdownEvent()
  -  {
  -    ShutdownListener[] listeners = (ShutdownListener[]) 
shutdownListenerList.getListeners(ShutdownListener.class);
  +  private void fireShutdownEvent() {
  +    ShutdownListener[] listeners =
  +      (ShutdownListener[]) shutdownListenerList.getListeners(
  +        ShutdownListener.class);
  +
       for (int i = 0; i < listeners.length; i++) {
         listeners[i].shuttingDown();
       }
  @@ -827,10 +858,10 @@
      * requests to exit the application, the default action
      * is to exit the VM.
      * This Action is called AFTER all the ShutdownListeners have been notified
  -   * 
  +   *
      * @param shutdownAction
      */
  -  public final void setShutdownAction(Action shutdownAction){
  +  public final void setShutdownAction(Action shutdownAction) {
       this.shutdownAction = shutdownAction;
     }
   
  @@ -839,9 +870,10 @@
      * actionPerformed(...) method.
      *
      */
  -  private void performShutdownAction(){
  +  private void performShutdownAction() {
       LogLog.debug("Calling the shutdown Action. Goodbye!");
  -    shutdownAction.actionPerformed(new ActionEvent(this, 
ActionEvent.ACTION_PERFORMED, "Shutting Down"));          
  +    shutdownAction.actionPerformed(
  +      new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "Shutting Down"));
     }
   
     /**
  @@ -1492,7 +1524,7 @@
         detail.setEditable(false);
   
         detailPaneUpdater =
  -        new DetailPaneUpdater(detail, (EventContainer) tableModel);
  +        new DetailPaneUpdater(this, detail, (EventContainer) tableModel);
   
         upperPanel = new JPanel(new BorderLayout());
         upperPanel.setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 0));
  @@ -2041,7 +2073,7 @@
        *
        */
       void dock() {
  -       setDocked(true);
  +      setDocked(true);
         f.setVisible(false);
         removeAll();
         add(lowerPanel, BorderLayout.CENTER);
  @@ -2058,7 +2090,7 @@
        *
        */
       void undock() {
  -       setDocked(false);
  +      setDocked(false);
         externalPanel.removeAll();
         externalPanel.add(lowerPanel, BorderLayout.CENTER);
         tabbedPane.remove(LogPanel.this);
  @@ -2341,10 +2373,13 @@
       private int lastRow = -1;
       private final JEditorPane pane;
       private final EventContainer model;
  +    private final LogPanel panel;
   
  -    public DetailPaneUpdater(JEditorPane pane, EventContainer model) {
  +    public DetailPaneUpdater(
  +      LogPanel panel, JEditorPane pane, EventContainer model) {
         this.pane = pane;
         this.model = model;
  +      this.panel = panel;
       }
   
       public void setSelectedRow(int row) {
  @@ -2409,8 +2444,10 @@
             public void run() {
               while (true) {
                 //if this tab is active, remove the icon
  -              if ((tabbedPane.getSelectedIndex() > -1) && 
  -                (tabbedPane.getSelectedIndex() == tabbedPane.indexOfTab(ident))) {
  +              if (
  +                (tabbedPane.getSelectedIndex() > -1)
  +                  && (tabbedPane.getSelectedIndex() == tabbedPane.indexOfTab(
  +                    ident))) {
                   tabbedPane.setIconAt(tabbedPane.indexOfTab(ident), null);
   
                   //reset fields so no icon will display 
  
  
  
  1.2       +243 -37   
jakarta-log4j/src/java/org/apache/log4j/chainsaw/NoReceiversWarningPanel.java
  
  Index: NoReceiversWarningPanel.java
  ===================================================================
  RCS file: 
/home/cvs/jakarta-log4j/src/java/org/apache/log4j/chainsaw/NoReceiversWarningPanel.java,v
  retrieving revision 1.1
  retrieving revision 1.2
  diff -u -r1.1 -r1.2
  --- NoReceiversWarningPanel.java      27 Aug 2003 22:48:34 -0000      1.1
  +++ NoReceiversWarningPanel.java      28 Aug 2003 05:39:04 -0000      1.2
  @@ -51,23 +51,38 @@
    */
   package org.apache.log4j.chainsaw;
   
  -import java.awt.FlowLayout;
  +import org.apache.log4j.helpers.LogLog;
  +
  +import java.awt.Dimension;
   import java.awt.GridBagConstraints;
   import java.awt.GridBagLayout;
   import java.awt.GridLayout;
   import java.awt.event.ActionEvent;
   import java.awt.event.ActionListener;
  +import java.awt.event.FocusEvent;
  +import java.awt.event.FocusListener;
  +
  +import java.io.File;
  +
  +import java.net.MalformedURLException;
  +import java.net.URL;
   
   import javax.swing.AbstractAction;
   import javax.swing.BorderFactory;
   import javax.swing.Box;
   import javax.swing.ButtonGroup;
  +import javax.swing.DefaultComboBoxModel;
   import javax.swing.JButton;
   import javax.swing.JComboBox;
  +import javax.swing.JFileChooser;
   import javax.swing.JFrame;
   import javax.swing.JPanel;
   import javax.swing.JRadioButton;
   import javax.swing.JTextArea;
  +import javax.swing.SwingUtilities;
  +import javax.swing.event.ListDataEvent;
  +import javax.swing.event.ListDataListener;
  +import javax.swing.filechooser.FileFilter;
   
   
   /**
  @@ -75,23 +90,51 @@
    * Receiver's defined, and prompting them to either
    * load a Log4j Log file, search for a Log4j configuration file
    * or use the GUI to define the Receivers
  - * 
  + *
    * @author Paul Smith
    */
   class NoReceiversWarningPanel extends JPanel {
  +  private final JComboBox previousConfigs = new JComboBox();
  +  private final JRadioButton justLoadingFile =
  +    new JRadioButton("I'm fine thanks, don't worry");
  +  private final JRadioButton searchOption =
  +    new JRadioButton("Let me search for a configuration file");
  +  private final JRadioButton manualOption =
  +    new JRadioButton("Let me define Receivers manually");
  +  private final JButton okButton = new JButton("Ok");
  +  private final PanelModel model = new PanelModel();
  +  final DefaultComboBoxModel configModel = new DefaultComboBoxModel();
  +
     NoReceiversWarningPanel() {
       initComponents();
     }
   
     /**
  -   *
  +   * Returns the current Model/state of the chosen options by the user.
  +   * @return
  +   */
  +  PanelModel getModel() {
  +    return model;
  +  }
  +
  +  /**
  +   * Clients of this panel can configure the ActionListener to be used
  +   * when the user presses the OK button, so they can read
  +   * back this Panel's model top determine what to do.
  +   * @param actionListener
  +   */
  +  void setOkActionListener(ActionListener actionListener) {
  +    okButton.addActionListener(actionListener);
  +  }
  +
  +  /**
  +   * Sets up all the GUI components for this paenl
      */
     private void initComponents() {
       setLayout(new GridBagLayout());
   
       GridBagConstraints gc = new GridBagConstraints();
   
  -    //    setBackground(Color.white);
       setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
   
       gc.gridx = 1;
  @@ -101,7 +144,7 @@
   
       JTextArea label =
         new JTextArea(
  -        "You have no Receivers defined.\n\nYou will not be able to receive events 
from a Remote source unless you define one in the Log4J configuration file.\n");
  +        "You will not be able to receive events from a Remote source unless you 
define one in the Log4J configuration file.\n");
       label.setWrapStyleWord(true);
       label.setLineWrap(true);
       label.setEditable(false);
  @@ -121,24 +164,21 @@
   
       final ButtonGroup optionGroup = new ButtonGroup();
   
  -    final JRadioButton searchOption =
  -      new JRadioButton("Let me locate a config file", false);
  -
       searchOption.setToolTipText(
         "Allows you to choose a Log4J Configuration file that contains Receiver 
definitions");
   
  -    final JRadioButton manualOption =
  -      new JRadioButton("Let me define Receivers manually");
  +    searchOption.setMnemonic('S');
   
       manualOption.setToolTipText(
         "Opens the Receivers panel so you can define them via a GUI");
   
  -    final JRadioButton justLoadingFile =
  -      new JRadioButton("Let me load a Log4j Log file");
  +    manualOption.setMnemonic('m');
   
       justLoadingFile.setToolTipText(
         "Use this if you just want to view a Log4J Log file stored somewhere");
   
  +    justLoadingFile.setMnemonic('I');
  +
       searchOption.setOpaque(false);
       manualOption.setOpaque(false);
       justLoadingFile.setOpaque(false);
  @@ -149,34 +189,88 @@
   
       gc.gridy = 3;
   
  -    String[] items =
  -      new String[] {
  -        "", "c:\\blah\blah.xml", "file:///var/doobie/blah/blah.xml",
  -      };
  +    configModel.removeAllElements();
   
  -    final JComboBox previousConfigs = new JComboBox(items);
  +    previousConfigs.setModel(configModel);
       previousConfigs.setOpaque(false);
       previousConfigs.setBackground(getBackground());
       previousConfigs.setToolTipText(
         "Previously loaded configurations can be chosen here");
   
  +    previousConfigs.setEditable(true);
  +
  +    previousConfigs.getModel().addListDataListener(
  +      new ListDataListener() {
  +        private void validateUrl() {
  +          okButton.setEnabled(isValidConfigURL());
  +        }
  +
  +        public void contentsChanged(ListDataEvent e) {
  +          validateUrl();
  +        }
  +
  +        public void intervalAdded(ListDataEvent e) {
  +          validateUrl();
  +        }
  +
  +        public void intervalRemoved(ListDataEvent e) {
  +          validateUrl();
  +        }
  +      });
  +
  +    previousConfigs.setMaximumSize(
  +      new Dimension(200, (int) previousConfigs.getPreferredSize().getHeight()));
  +    previousConfigs.setPreferredSize(previousConfigs.getMaximumSize());
  +    previousConfigs.getEditor().getEditorComponent().addFocusListener(
  +      new FocusListener() {
  +        public void focusGained(FocusEvent e) {
  +          selectAll();
  +        }
  +
  +        private void selectAll() {
  +          previousConfigs.getEditor().selectAll();
  +        }
  +
  +        public void focusLost(FocusEvent e) {
  +        }
  +      });
  +
       final JButton searchButton =
         new JButton(
  -        new AbstractAction("...") {
  +        new AbstractAction("Browse...") {
             public void actionPerformed(ActionEvent e) {
  -            
  -//            TODO close this dialog(?) and use the file open action
  +            try {
  +              URL url = browseForConfig();
  +
  +              if (url != null) {
  +                getModel().configUrl = url;
  +                configModel.addElement(url);
  +                previousConfigs.getModel().setSelectedItem(url);
  +              }
  +            } catch (Exception ex) {
  +              LogLog.error("Error browswing for Configuration file", ex);
  +            }
             }
           });
   
       searchButton.setToolTipText(
  -      "Shows a File Open dialog to allow you to find a config file");
  +      "Shows a File Open dialog to allow you to find a configuration file");
   
  +    /**
  +     * This listener activates/deactivates certain controls based on the current
  +     * state of the options
  +     */
       ActionListener al =
         new ActionListener() {
           public void actionPerformed(ActionEvent e) {
             previousConfigs.setEnabled(e.getSource() == searchOption);
             searchButton.setEnabled(e.getSource() == searchOption);
  +
  +          if (optionGroup.isSelected(searchOption.getModel())) {
  +            okButton.setEnabled(isValidConfigURL());
  +          } else {
  +            okButton.setEnabled(true);
  +          }
           }
         };
   
  @@ -186,44 +280,156 @@
   
       justLoadingFile.doClick();
   
  -    JPanel searchOptionPanel =
  -      new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
  +    JPanel searchOptionPanel = new JPanel(new GridBagLayout());
  +
       searchOptionPanel.setOpaque(false);
   
  -    searchOptionPanel.add(searchOption);
  -    searchOptionPanel.add(Box.createHorizontalStrut(5));
  -    searchOptionPanel.add(previousConfigs);
  -    searchOptionPanel.add(Box.createHorizontalStrut(5));
  -    searchOptionPanel.add(searchButton);
  +    GridBagConstraints searchGCC = new GridBagConstraints();
  +
  +    searchGCC.fill = GridBagConstraints.HORIZONTAL;
  +    searchGCC.gridx = 1;
  +
  +    searchOptionPanel.add(searchOption, searchGCC);
  +    searchGCC.gridx = 2;
  +    searchOptionPanel.add(Box.createHorizontalStrut(5), searchGCC);
  +
  +    searchGCC.weightx = 0.0;
  +    searchGCC.gridx = 3;
  +    searchGCC.fill = GridBagConstraints.NONE;
  +    searchOptionPanel.add(previousConfigs, searchGCC);
  +
  +    searchGCC.weightx = 0.0;
  +    searchGCC.gridx = 4;
  +    searchOptionPanel.add(Box.createHorizontalStrut(5), searchGCC);
  +    searchGCC.gridx = 5;
  +    searchOptionPanel.add(searchButton, searchGCC);
   
  -    optionpanel.add(justLoadingFile);
       optionpanel.add(searchOptionPanel);
       optionpanel.add(manualOption);
  +    optionpanel.add(justLoadingFile);
   
       add(optionpanel, gc);
   
  -    final JButton okButton =
  -      new JButton(
  -        new AbstractAction("Ok") {
  -          public void actionPerformed(ActionEvent e) {
  -            // TODO Auto-generated method stub
  -          }
  -        });
  -
       gc.gridy = gc.RELATIVE;
       gc.weightx = 0;
       gc.fill = gc.NONE;
       gc.anchor = gc.SOUTHEAST;
   
       add(Box.createVerticalStrut(20), gc);
  +
  +    okButton.setMnemonic('O');
       add(okButton, gc);
     }
   
  +  /**
  +   * Returns the URL chosen by the user for a Configuration file
  +   * or null if they cancelled.
  +   */
  +  private URL browseForConfig() throws MalformedURLException {
  +    JFileChooser chooser = new JFileChooser();
  +    chooser.setDialogTitle("Search for Log4j configuration...");
  +    chooser.setDialogType(JFileChooser.OPEN_DIALOG);
  +    chooser.setFileFilter(
  +      new FileFilter() {
  +        public boolean accept(File f) {
  +          return f.isDirectory() || f.getName().endsWith(".properties")
  +          || f.getName().endsWith(".xml");
  +        }
  +
  +        public String getDescription() {
  +          return "Log4j Configuration file";
  +        }
  +      });
  +
  +    chooser.showOpenDialog(this);
  +
  +    File selectedFile = chooser.getSelectedFile();
  +
  +    if (selectedFile == null) {
  +      return null;
  +    }
  +
  +    if (!selectedFile.exists() || !selectedFile.canRead()) {
  +      return null;
  +    }
  +
  +    return chooser.getSelectedFile().toURL();
  +  }
  +
  +  /**
  +   * Determions if the Configuration URL is a valid url.
  +   */
  +  private boolean isValidConfigURL() {
  +    if (previousConfigs.getSelectedItem() == null) {
  +      return false;
  +    }
  +
  +    String urlString = previousConfigs.getSelectedItem().toString();
  +
  +    try {
  +      getModel().configUrl = new URL(urlString);
  +
  +      return true;
  +    } catch (Exception ex) {
  +    }
  +
  +    return false;
  +  }
  +
     public static void main(String[] args) {
       JFrame frame = new JFrame();
       frame.getContentPane().add(new NoReceiversWarningPanel());
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.pack();
       frame.show();
  +  }
  +
  +  /**
  +   * This class represents the model of the chosen options the user
  +   * has configured.
  +   *
  +   */
  +  class PanelModel {
  +    private URL fileUrl;
  +    private URL configUrl;
  +
  +    boolean isLoadLogFile() {
  +      return justLoadingFile.isSelected();
  +    }
  +
  +    boolean isLoadConfig() {
  +      return searchOption.isSelected();
  +    }
  +
  +    boolean isManualMode() {
  +      return manualOption.isSelected();
  +    }
  +
  +    public Object[] getRememberedConfigs() {
  +      Object[] urls = new Object[configModel.getSize()];
  +
  +      for (int i = 0; i < configModel.getSize(); i++) {
  +        urls[i] = configModel.getElementAt(i);
  +      }
  +
  +      return urls;
  +    }
  +
  +    public void setRememberedConfigs(final Object[] configs) {
  +      SwingUtilities.invokeLater(
  +        new Runnable() {
  +          public void run() {
  +            configModel.removeAllElements();
  +
  +            for (int i = 0; i < configs.length; i++) {
  +              configModel.addElement(configs[i]);
  +            }
  +          }
  +        });
  +    }
  +
  +    URL getConfigToLoad() {
  +      return configUrl;
  +    }
     }
   }
  
  
  

---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to