OSDN Git Service

2013.10.24
[uclinux-h8/uClinux-dist.git] / lib / classpath / examples / gnu / classpath / examples / swing / DocumentFilterDemo.java
1 /* DpocumentFilterDemo.java -- An example for the DocumentFilter class.
2    Copyright (C) 2006  Free Software Foundation, Inc.
3
4 This file is part of GNU Classpath examples.
5
6 GNU Classpath is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
10
11 GNU Classpath is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GNU Classpath; see the file COPYING.  If not, write to the
18 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 02110-1301 USA.
20 */
21
22
23 package gnu.classpath.examples.swing;
24
25 import java.awt.BorderLayout;
26 import java.awt.Color;
27 import java.awt.GridLayout;
28 import java.awt.Toolkit;
29 import java.awt.datatransfer.Clipboard;
30 import java.awt.datatransfer.StringSelection;
31 import java.awt.event.ActionEvent;
32 import java.awt.event.ActionListener;
33
34 import javax.swing.JButton;
35 import javax.swing.JComboBox;
36 import javax.swing.JComponent;
37 import javax.swing.JFrame;
38 import javax.swing.JLabel;
39 import javax.swing.JOptionPane;
40 import javax.swing.JPanel;
41 import javax.swing.JTextField;
42 import javax.swing.SwingUtilities;
43 import javax.swing.text.AbstractDocument;
44 import javax.swing.text.AttributeSet;
45 import javax.swing.text.BadLocationException;
46 import javax.swing.text.DocumentFilter;
47
48 /**
49  * A demonstration of the <code>javax.swing.text.DocumentFilter</code> class.
50  * 
51  * <p>Similar to a dialog in a popular programming IDE the user can insert
52  * a CVS URL into a textfield and the filter will split the components apart
53  * and will put them into the right textfields saving the user a lot of
54  * typing time.</p>
55  * 
56  * @author Robert Schuster
57  */
58 public class DocumentFilterDemo 
59   extends JPanel 
60   implements ActionListener 
61 {
62   JTextField target;
63   
64   JTextField host;
65   JTextField repositoryPath;
66   JTextField user;
67   JTextField password;
68   JComboBox connectionType;
69
70   /**
71    * Creates a new demo instance.
72    */
73   public DocumentFilterDemo() 
74   {
75     createContent();
76     // initFrameContent() is only called (from main) when running this app 
77     // standalone
78   }
79   
80   /**
81    * When the demo is run independently, the frame is displayed, so we should
82    * initialise the content panel (including the demo content and a close 
83    * button).  But when the demo is run as part of the Swing activity board,
84    * only the demo content panel is used, the frame itself is never displayed,
85    * so we can avoid this step.
86    */
87   void initFrameContent()
88   {
89     JPanel closePanel = new JPanel();
90     JButton closeButton = new JButton("Close");
91     closeButton.setActionCommand("CLOSE");
92     closeButton.addActionListener(this);
93     closePanel.add(closeButton);
94     add(closePanel, BorderLayout.SOUTH);
95   }
96
97   private void createContent()
98   {
99     setLayout(new BorderLayout());
100     
101     JPanel panel = new JPanel(new GridLayout(7, 2));
102     panel.add(new JLabel("CVS URL:"));
103     panel.add(target = new JTextField(20));
104     target.setBackground(Color.RED);
105     
106     panel.add(new JLabel("Host:"));
107     panel.add(host = new JTextField(20));
108     
109     panel.add(new JLabel("Repository Path:"));
110     panel.add(repositoryPath = new JTextField(20));
111     
112     panel.add(new JLabel("Username:"));
113     panel.add(user = new JTextField(20));
114     
115     panel.add(new JLabel("Password:"));
116     panel.add(password = new JTextField(20));
117     
118     panel.add(new JLabel("Connection Type:"));
119     panel.add(connectionType = new JComboBox());
120     
121     JButton helpButton = new JButton("Help");
122     panel.add(helpButton);
123     
124     helpButton.addActionListener(new ActionListener()
125       {
126         public void actionPerformed(ActionEvent ae)
127         {
128           JOptionPane.showMessageDialog(DocumentFilterDemo.this,
129                                         "Paste a CVS URL into the red " +
130                                         "textfield.\nIf you do not want to " +
131                                         "look up a CVS URL yourself click " +
132                                         "on the 'provide me an example' " +
133                                         "button.\nThis will paste a proper " +
134                                         "string into your clipboard.");
135         }
136       });
137     
138     JButton exampleButton = new JButton("Provide me an example!");
139     panel.add(exampleButton);
140     exampleButton.addActionListener(new ActionListener()
141       {
142         public void actionPerformed(ActionEvent ae)
143         {
144          try
145            {
146              Toolkit tk = Toolkit.getDefaultToolkit();
147              Clipboard cb = tk.getSystemSelection();
148              StringSelection selection
149                = new StringSelection(":extssh:gnu@cvs.savannah.gnu.org:" +
150                         "/cvs/example/project");
151              
152              cb.setContents(selection, selection);
153              
154              // Confirm success with a beep.
155              tk.beep();
156            }
157          catch (IllegalStateException ise)
158            {
159              JOptionPane.showMessageDialog(DocumentFilterDemo.this,
160                                            "Clipboard is currently" +
161                                            " unavailable.",
162                                            "Error",
163                                            JOptionPane.ERROR_MESSAGE);
164            }
165         }
166       });
167     
168     connectionType.addItem("pserver");
169     connectionType.addItem("ext");
170     connectionType.addItem("extssh");
171     
172     add(panel);
173     
174     AbstractDocument doc = (AbstractDocument) target.getDocument();
175     doc.setDocumentFilter(new CVSFilter());
176   }
177   
178   public void actionPerformed(ActionEvent e) 
179   {
180     if (e.getActionCommand().equals("CLOSE"))
181       System.exit(0);
182     
183   } 
184
185   public static void main(String[] args) 
186   {
187     SwingUtilities.invokeLater
188     (new Runnable()
189      {
190        public void run()
191        {
192          DocumentFilterDemo app = new DocumentFilterDemo();
193          app.initFrameContent();
194          JFrame frame = new JFrame("DocumentFilterDemo");
195          frame.getContentPane().add(app);
196          frame.pack();
197          frame.setVisible(true);
198          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
199        }
200      });
201   }
202
203   /**
204    * Returns a DemoFactory that creates a DocumentFilterDemo.
205    *
206    * @return a DemoFactory that creates a DocumentFilterDemo
207    */
208   public static DemoFactory createDemoFactory()
209   {
210     return new DemoFactory()
211     {
212       public JComponent createDemo()
213       {
214         return new DocumentFilterDemo();
215       }
216     };
217   }
218   
219   class CVSFilter extends DocumentFilter
220   {
221     // example: pserver:anonymous@cvs.sourceforge.net:/cvsroot/fmj
222     String cvsPattern = ":?(pserver|ext|extssh):(\\w)+(:(\\w)+)?@(\\w|\\.)+:/(\\w|/)*";
223
224     public void insertString(DocumentFilter.FilterBypass fb,
225                              int offset, String string,
226                              AttributeSet attr)
227     throws BadLocationException
228     {
229       filterString(fb, offset, 0, string, attr, true);
230     }
231     
232     public void replace(DocumentFilter.FilterBypass fb,
233                               int offset, int length,
234                               String string,
235                               AttributeSet attr)
236     throws BadLocationException
237     {
238       filterString(fb, offset, length, string, attr, false);
239     }
240     
241     public void filterString(DocumentFilter.FilterBypass fb,
242                              int offset, int length, String string,
243                              AttributeSet attr, boolean insertion)
244     throws BadLocationException
245     {
246       if(string.matches(cvsPattern))
247         {
248           // Split off the connection type part.
249           String[] result = string.split(":", 2);
250
251           // If the string contained a leading colon, result[0]
252           // will be empty at that point. We simply repeat the split
253           // operation on the remaining string and continue.
254           if(result[0].equals(""))
255             result = result[1].split(":", 2);
256                 
257           connectionType.setSelectedItem(result[0]);
258               
259           // Split off the username and password part
260           result = result[1].split("@", 2);
261               
262           // Break username and password in half
263           String[] userCredentials = result[0].split(":");
264           user.setText(userCredentials[0]);
265
266           // If the result has two entries the second one will
267           // be the password.
268           if (userCredentials.length == 2)
269             password.setText(userCredentials[1]);
270               
271           // Now break the host part apart.
272           result = result[1].split(":");
273               
274           host.setText(result[0]);
275               
276           repositoryPath.setText(result[1]);
277         }
278           
279       // The unmodified string is put into the document.
280       if (insertion)
281         fb.insertString(offset, string, attr);
282       else
283         fb.replace(offset, length, string, attr);
284     }
285     
286   }
287   
288 }