KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > editor > options > AbbrevsEditorPanel


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.editor.options;
21
22 import java.awt.Dialog JavaDoc;
23 import java.awt.Font JavaDoc;
24 import java.awt.FontMetrics JavaDoc;
25 import java.awt.Graphics JavaDoc;
26 import java.awt.Window JavaDoc;
27 import java.awt.event.*;
28 import java.util.*;
29 import javax.swing.*;
30 import javax.swing.table.*;
31
32 import org.openide.*;
33 import org.openide.util.NbBundle;
34 import org.openide.util.HelpCtx;
35 import javax.swing.event.ListSelectionEvent JavaDoc;
36 import javax.swing.event.ListSelectionListener JavaDoc;
37
38
39 /**
40  * Component for visual editing of Map of abbreviations. When you enter new
41  * abbreviation with the already used abbrev, it will replace the existing one.
42  * abbreviations with empty expanded form are perfectly valid, but abbreviations
43  * with empty abbrev field are simply ignored.
44  *
45  * @author Petr Nejedly
46  */

47
48 public class AbbrevsEditorPanel extends javax.swing.JPanel JavaDoc {
49
50     PairStringModel model;
51
52     // The master we talk to about changes in map
53
private AbbrevsEditor editor;
54     
55     private FontSizeTable abbrevsTable;
56
57     /** Creates new form AbbrevsEditorPanel */
58     public AbbrevsEditorPanel( AbbrevsEditor editor ) {
59         this.editor = editor;
60         model = new PairStringModel();
61         initComponents ();
62
63         abbrevsTable = new FontSizeTable();
64         abbrevsTable.setBorder(new javax.swing.border.EmptyBorder JavaDoc(new java.awt.Insets JavaDoc(8, 8, 8, 8)));
65         abbrevsTable.setModel(model);
66         abbrevsTable.setShowHorizontalLines(false);
67         abbrevsTable.setShowVerticalLines(false);
68         abbrevsTable.setSelectionMode( DefaultListSelectionModel.SINGLE_SELECTION );
69         // Set the width of columns to 30% and 70%
70
TableColumnModel col = abbrevsTable.getColumnModel();
71         col.getColumn( 0 ).setMaxWidth( 3000 );
72         col.getColumn( 0 ).setPreferredWidth( 30 );
73         col.getColumn( 1 ).setMaxWidth( 7000 );
74         col.getColumn( 1 ).setPreferredWidth( 70 );
75         abbrevsPane.setViewportView(abbrevsTable);
76         
77         
78         getAccessibleContext().setAccessibleDescription(getBundleString("ACSD_AEP")); // NOI18N
79
abbrevsTable.getAccessibleContext().setAccessibleName(getBundleString("ACSN_AEP_Table")); // NOI18N
80
abbrevsTable.getAccessibleContext().setAccessibleDescription(getBundleString("ACSD_AEP_Table")); // NOI18N
81
addButton.getAccessibleContext().setAccessibleDescription(getBundleString("ACSD_AEP_Add")); // NOI18N
82
editButton.getAccessibleContext().setAccessibleDescription(getBundleString("ACSD_AEP_Edit")); // NOI18N
83
removeButton.getAccessibleContext().setAccessibleDescription(getBundleString("ACSD_AEP_Remove")); // NOI18N
84
enableButtons(false);
85         
86         abbrevsTable.registerKeyboardAction(new ActionListener() {
87             public void actionPerformed(ActionEvent evt) {
88                 SwingUtilities.getAncestorOfClass(Window JavaDoc.class, AbbrevsEditorPanel.this).setVisible(false);
89             }},
90             KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
91             JComponent.WHEN_FOCUSED
92         );
93             
94         abbrevsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener JavaDoc() {
95             public void valueChanged(ListSelectionEvent JavaDoc e) {
96                 if (e.getValueIsAdjusting()) return;
97                 
98                 // XXX - hack because of bugparade's 4801274
99
if (abbrevsTable.getRowCount() == 0){
100                     enableButtons(false);
101                     return;
102                 }
103                 
104                 // valid fix of #35096
105
ListSelectionModel lsm = (ListSelectionModel)e.getSource();
106                 enableButtons(!lsm.isSelectionEmpty());
107             }
108         });
109             
110     }
111
112     private void enableButtons(boolean enable){
113         editButton.setEnabled(enable);
114         removeButton.setEnabled(enable);
115     }
116     
117     private String JavaDoc getBundleString(String JavaDoc s) {
118         return NbBundle.getMessage(AbbrevsEditorPanel.class, s);
119     }
120     
121
122     /**
123      * Fill in editor with initial values
124      */

125     public void setValue( Map m ) {
126         // Our model is the one and only holding data
127
if (m != null)
128             model.setData( new TreeMap( m ) );
129         else
130             model.setData( new TreeMap() );
131
132         // select first item, just to have something selected
133
if( model.getRowCount() > 0 ) abbrevsTable.setRowSelectionInterval( 0, 0 );
134     }
135
136     /**
137      * Take the result of users modifications
138      */

139     public Map getValue() {
140         return model.getData();
141     }
142
143     /**
144      * Tell the editor (and in round the system), that user've changed
145      * abbrevs mapping.
146      */

147     private void notifyEditor() {
148         if( editor != null ) editor.customEditorChange();
149     }
150
151
152     private void initComponents() {//GEN-BEGIN:initComponents
153
java.awt.GridBagConstraints JavaDoc gridBagConstraints;
154
155         abbrevsPane = new javax.swing.JScrollPane JavaDoc();
156         addButton = new javax.swing.JButton JavaDoc();
157         editButton = new javax.swing.JButton JavaDoc();
158         removeButton = new javax.swing.JButton JavaDoc();
159
160         setLayout(new java.awt.GridBagLayout JavaDoc());
161
162         setBorder(new javax.swing.border.EmptyBorder JavaDoc(new java.awt.Insets JavaDoc(12, 12, 11, 11)));
163         gridBagConstraints = new java.awt.GridBagConstraints JavaDoc();
164         gridBagConstraints.gridheight = 4;
165         gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
166         gridBagConstraints.weightx = 1.0;
167         gridBagConstraints.weighty = 1.0;
168         gridBagConstraints.insets = new java.awt.Insets JavaDoc(0, 0, 0, 12);
169         add(abbrevsPane, gridBagConstraints);
170
171         addButton.setMnemonic(getBundleString("AEP_Add_Mnemonic").charAt (0));
172         addButton.setText(getBundleString( "AEP_Add" ));
173         addButton.addActionListener(new java.awt.event.ActionListener JavaDoc() {
174             public void actionPerformed(java.awt.event.ActionEvent JavaDoc evt) {
175                 addButtonActionPerformed(evt);
176             }
177         });
178
179         gridBagConstraints = new java.awt.GridBagConstraints JavaDoc();
180         gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
181         gridBagConstraints.insets = new java.awt.Insets JavaDoc(0, 0, 5, 0);
182         add(addButton, gridBagConstraints);
183
184         editButton.setMnemonic(getBundleString("AEP_Edit_Mnemonic").charAt (0));
185         editButton.setText(getBundleString( "AEP_Edit" ));
186         editButton.addActionListener(new java.awt.event.ActionListener JavaDoc() {
187             public void actionPerformed(java.awt.event.ActionEvent JavaDoc evt) {
188                 editButtonActionPerformed(evt);
189             }
190         });
191
192         gridBagConstraints = new java.awt.GridBagConstraints JavaDoc();
193         gridBagConstraints.gridx = 1;
194         gridBagConstraints.gridy = 1;
195         gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
196         gridBagConstraints.insets = new java.awt.Insets JavaDoc(0, 0, 5, 0);
197         add(editButton, gridBagConstraints);
198
199         removeButton.setMnemonic(getBundleString("AEP_Remove_Mnemonic").charAt (0));
200         removeButton.setText(getBundleString( "AEP_Remove" ));
201         removeButton.addActionListener(new java.awt.event.ActionListener JavaDoc() {
202             public void actionPerformed(java.awt.event.ActionEvent JavaDoc evt) {
203                 removeButtonActionPerformed(evt);
204             }
205         });
206
207         gridBagConstraints = new java.awt.GridBagConstraints JavaDoc();
208         gridBagConstraints.gridx = 1;
209         gridBagConstraints.gridy = 2;
210         gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
211         add(removeButton, gridBagConstraints);
212
213     }//GEN-END:initComponents
214

215     private void addButtonActionPerformed (java.awt.event.ActionEvent JavaDoc evt) {//GEN-FIRST:event_addButtonActionPerformed
216
String JavaDoc[] abbrev = getAbbrev( null );
217         // If user canceled entering, do noting
218
if( abbrev == null ) return;
219         int index = model.putPair( abbrev ); // can silently replace existing mapping
220
abbrevsTable.setRowSelectionInterval( index, index );
221         notifyEditor();
222     }//GEN-LAST:event_addButtonActionPerformed
223

224     private void editButtonActionPerformed (java.awt.event.ActionEvent JavaDoc evt) {//GEN-FIRST:event_editButtonActionPerformed
225
int index = abbrevsTable.getSelectedRow();
226         if( index != -1 ) { // is something selected?
227
String JavaDoc[] pair = model.getPair( index );
228             pair = getAbbrev( pair );
229             if( pair != null ) {
230                 model.removePair( index );
231                 index = model.putPair( pair );
232                 abbrevsTable.setRowSelectionInterval( index, index );
233                 notifyEditor();
234             }
235         }
236     }//GEN-LAST:event_editButtonActionPerformed
237

238     private void removeButtonActionPerformed (java.awt.event.ActionEvent JavaDoc evt) {//GEN-FIRST:event_removeButtonActionPerformed
239
int index = abbrevsTable.getSelectedRow();
240         if( index != -1 ) { // is something selected?
241
model.removePair( index );
242             if( index >= model.getRowCount() ) index--;
243             if( index >= 0 ) abbrevsTable.setRowSelectionInterval( index, index );
244             notifyEditor();
245         }
246     }//GEN-LAST:event_removeButtonActionPerformed
247

248     /**
249      * Creates a dialog asking user for pair of Strings.
250      * @param abbrev value to be preset in dialog, or <CODE>null</CODE>
251      * @return String[2] filled with {abbrev, expand}
252      * or <CODE>null</CODE> if canceled.
253      */

254     private String JavaDoc[] getAbbrev( String JavaDoc[] abbrev ) {
255         AbbrevInputPanel input = new AbbrevInputPanel();
256         // set HELP_ID of parent
257
HelpCtx.setHelpIDString( input, (HelpCtx.findHelp(this) != null ? HelpCtx.findHelp(this).getHelpID() : null) );
258         if( abbrev != null ) input.setAbbrev( abbrev ); // preset value
259

260         DialogDescriptor dd = new DialogDescriptor ( input, getBundleString("AEP_EnterAbbrev" ) ); // NOI18N
261
Dialog JavaDoc dial = org.openide.DialogDisplayer.getDefault().createDialog(dd);
262         input.requestFocus(); // Place caret in it, hopefully
263
dial.setVisible(true); // let the user tell us their wish
264

265         if( dd.getValue() == DialogDescriptor.OK_OPTION ) {
266             String JavaDoc[] retVal = input.getAbbrev();
267             if( ! "".equals( retVal[0] ) ){ // NOI18N don't allow empty abbrev
268
int existingKeyPosition = model.containsKey(retVal[0]);
269                 
270                 if (existingKeyPosition >= 0){
271                     // ignore if user edits value and doesn't change the key
272
if ( abbrev!=null && abbrev[0].equals(retVal[0]) ) return retVal;
273                     
274                     String JavaDoc[] existingPair = model.getPair(existingKeyPosition);
275                     NotifyDescriptor NDConfirm = new NotifyDescriptor.Confirmation(
276                     NbBundle.getMessage(AbbrevsEditorPanel.class, "AEP_Overwrite", new Object JavaDoc[] {retVal[0], existingPair[1], retVal[1]}),
277                     NotifyDescriptor.YES_NO_OPTION,
278                     NotifyDescriptor.WARNING_MESSAGE
279                     );
280                     
281                     org.openide.DialogDisplayer.getDefault().notify(NDConfirm);
282                     if (NDConfirm.getValue()!=NDConfirm.YES_OPTION){
283                         return null;
284                     }
285                 }
286                 return retVal;
287             }
288         }
289         return null; // cancel or empty
290
}
291     
292     
293     // Variables declaration - do not modify//GEN-BEGIN:variables
294
private javax.swing.JScrollPane JavaDoc abbrevsPane;
295     private javax.swing.JButton JavaDoc addButton;
296     private javax.swing.JButton JavaDoc editButton;
297     private javax.swing.JButton JavaDoc removeButton;
298     // End of variables declaration//GEN-END:variables
299

300
301     /**
302      * TableModel of sorted map of string pairs, provides additional functions
303      * for setting, getting and modifying it's content.
304      */

305     private class PairStringModel extends javax.swing.table.AbstractTableModel JavaDoc {
306
307         String JavaDoc[] columns = { getBundleString( "AEP_AbbrevTitle" ), // NOI18N
308
getBundleString( "AEP_ExpandTitle" ) }; // NOI18N
309

310         TreeMap data;
311         String JavaDoc[] keys;
312
313         public PairStringModel() {
314             data = new TreeMap();
315             keys = new String JavaDoc[0];
316         }
317
318         public void setData( TreeMap data ) {
319             this.data = data;
320             updateKeys();
321         }
322
323         private void updateKeys() {
324             keys = (String JavaDoc[])data.keySet().toArray( new String JavaDoc[0] );
325             fireTableDataChanged(); // we make general changes to table, invalidate whole
326
}
327
328         public TreeMap getData() {
329             return data;
330         }
331
332         public int getRowCount() {
333             return keys.length;
334         }
335
336         public int getColumnCount() {
337             return 2;
338         }
339
340         public String JavaDoc getColumnName(int column) {
341             return columns[column];
342         }
343
344         public Object JavaDoc getValueAt(int row, int column) {
345             if( column == 0 ) return keys[row];
346             else return data.get( keys[row] );
347         }
348
349         public int putPair( String JavaDoc[] pair ) {
350             data.put( pair[0], pair[1] );
351             updateKeys();
352             return Arrays.binarySearch( keys, pair[0] ); // it should always find
353
}
354
355         public void removePair( int row ) {
356             data.remove( getValueAt( row, 0 ) );
357             updateKeys();
358         }
359
360         public String JavaDoc[] getPair( int row ) {
361             String JavaDoc key = (String JavaDoc)getValueAt( row, 0 );
362             String JavaDoc[] retVal = { key, (String JavaDoc)data.get( key ) };
363             return retVal;
364         }
365         
366         public int containsKey( String JavaDoc key ){
367             return Arrays.binarySearch( keys, key );
368         }
369     }
370
371     
372      private final class FontSizeTable extends JTable{
373  
374          private boolean needCalcRowHeight = true;
375          
376          public FontSizeTable () {}
377          
378          public void updateUI() {
379              super.updateUI();
380              needCalcRowHeight = true;
381          }
382          
383          public void paint(Graphics JavaDoc g) {
384              if (needCalcRowHeight) {
385                  calcRowHeight(g);
386              }
387              super.paint(g);
388          }
389          
390          /** Calculate the height of rows based on the current font. This is
391           * done when the first paint occurs, to ensure that a valid Graphics
392           * object is available.
393           */

394          private void calcRowHeight(Graphics JavaDoc g) {
395              Font JavaDoc f = getFont();
396              FontMetrics JavaDoc fm = g.getFontMetrics(f);
397              int rowHeight = fm.getHeight();
398              needCalcRowHeight = false;
399              setRowHeight(rowHeight);
400          }
401          
402      }
403     
404 }
405
Popular Tags