1//Provides a word count of the selected text in A Writer document. 2import com.sun.star.uno.UnoRuntime; 3import com.sun.star.frame.XModel; 4import com.sun.star.view.XSelectionSupplier; 5import com.sun.star.container.XIndexAccess; 6import com.sun.star.text.XText; 7import com.sun.star.text.XTextRange; 8import com.sun.star.script.provider.XScriptContext; 9 10// display the count in a Swing dialog 11void doDisplay(numWords) { 12 wordsLabel = new JLabel("Word count = " + numWords); 13 closeButton = new JButton("Close"); 14 frame = new JFrame("Word Count"); 15 closeButton.addActionListener(new ActionListener() { 16 actionPerformed(ActionEvent e) { 17 frame.setVisible(false); 18 } 19 }); 20 frame.getContentPane().setLayout(new BorderLayout()); 21 frame.getContentPane().add(wordsLabel, BorderLayout.CENTER); 22 frame.getContentPane().add(closeButton, BorderLayout.SOUTH); 23 frame.pack(); 24 frame.setSize(190,90); 25 frame.setLocation(430,430); 26 frame.setVisible(true); 27} 28 29int wordcount() { 30 31 result = 0; 32 33 // iterate through each of the selections 34 count = xIndexAccess.getCount(); 35 for(i=0;i<count;i++) { 36 // get the XTextRange of the selection 37 xTextRange = (XTextRange) 38 UnoRuntime.queryInterface(XTextRange.class, xIndexAccess.getByIndex(i)); 39 //System.out.println("string: "+xTextRange.getString()); 40 // use the standard J2SE delimiters to tokenize the string 41 // obtained from the XTextRange 42 strTok = new StringTokenizer(xTextRange.getString()); 43 result += strTok.countTokens(); 44 } 45 46 doDisplay(result); 47 return result; 48} 49 50// The XSCRIPTCONTEXT variable is of type XScriptContext and is available to 51// all BeanShell scripts executed by the Script Framework 52xModel = (XModel) 53 UnoRuntime.queryInterface(XModel.class, XSCRIPTCONTEXT.getDocument()); 54//the writer controller impl supports the css.view.XSelectionSupplier interface 55xSelectionSupplier = (XSelectionSupplier) 56 UnoRuntime.queryInterface(XSelectionSupplier.class, xModel.getCurrentController()); 57//see section 7.5.1 of developers' guide 58// the getSelection provides an XIndexAccess to the one or more selections 59xIndexAccess = (XIndexAccess) 60 UnoRuntime.queryInterface(XIndexAccess.class, xSelectionSupplier.getSelection()); 61 62count = wordcount(); 63System.out.println("count = "+count); 64return 0; 65