OpenOffice.org Forum at OOoForum.orgThe OpenOffice.org Forum
 
 [Home]   [FAQ]   [Search]   [Memberlist]   [Usergroups]   [Register
 [Profile]   [Log in to check your private messages]   [Log in

how to create a toolbar with a combobox from java at runtime
Goto page 1, 2  Next
 
Post new topic   Reply to topic    OOoForum.org Forum Index -> OpenOffice.org Macros and API
View previous topic :: View next topic  
Author Message
emorel
General User
General User


Joined: 17 Jan 2006
Posts: 18
Location: France

PostPosted: Fri Nov 10, 2006 2:04 pm    Post subject: how to create a toolbar with a combobox from java at runtime Reply with quote

Hi,

I know how to create a toolbar with a button from java at runtime but a combo box ? Is it possible ? when I change the value type, it's always a button.

Here is a part of the code (http://java.sun.com/developer/technicalArticles/J2SE/Desktop/menus_toolbars/) :

Code:
 

       PropertyValue[] itemProperty = new PropertyValue[3];

        itemProperty[0] = new PropertyValue();
        itemProperty[0].Name = "CommandURL";
        itemProperty[0].Value = "macro:///Standard.Module1.myMacro()";
        itemProperty[1] = new PropertyValue();
        itemProperty[1].Name = "Label";
        itemProperty[1].Value = "myMacro";
        itemProperty[2] = new PropertyValue();
        itemProperty[2].Name = "Type";
        itemProperty[2].Value = new Integer(0);//1 or 2 always a button...

        xCfgMgr.insertSettings( toolbarURL,  itemProperty );



Thanks for your help.

Eric
Back to top
View user's profile Send private message
emorel
General User
General User


Joined: 17 Jan 2006
Posts: 18
Location: France

PostPosted: Tue Nov 14, 2006 1:29 am    Post subject: Reply with quote

I have read this thread before :
http://www.openoffice.org/servlets/ReadMsg?list=dev&msgNo=14719
and this sample :
http://codesnippets.services.openoffice.org/Office/Office.AddingACombo_boxToAToolbar.snip

But that needs unopkg and modifications of OOo XML files I don't want. Perhaps this could be made at runtime the first time or removed at the end. I'll try.

Eric
Back to top
View user's profile Send private message
ms777
Super User
Super User


Joined: 07 Feb 2004
Posts: 1355

PostPosted: Tue Nov 14, 2006 11:04 am    Post subject: Reply with quote

emorel wrote:
... and this sample :
http://codesnippets.services.openoffice.org/Office/Office.AddingACombo_boxToAToolbar.snip

But that needs unopkg and modifications of OOo XML files I don't want. Perhaps this could be made at runtime the first time or removed at the end. I'll try.

Eric


If you want to implement that without unopkg and XML modification, you may want to have a look at http://www.oooforum.org/forum/viewtopic.phtml?t=47161 . The technique should be applicable to your problem.

Good luck, and ask for help, if necessary ...

ms777
Back to top
View user's profile Send private message
emorel
General User
General User


Joined: 17 Jan 2006
Posts: 18
Location: France

PostPosted: Tue Nov 14, 2006 3:14 pm    Post subject: Reply with quote

Yes ! I have read this thread one time but I wasn't where I am now and I didn't remember it. Thank you.

Here is what I understand :

1 Your BeanShell code that creates a Base64simple service should be my Toolbar with the combobox. Don't know BeanSchell. BeanSchell seems like Java, I need to learn... This service should be in a document and should run in that context or not ?
2 I need to translate the basic to Java to call my new toolbar service.

is this OK ?

Eric
Back to top
View user's profile Send private message
ms777
Super User
Super User


Joined: 07 Feb 2004
Posts: 1355

PostPosted: Thu Nov 16, 2006 11:22 am    Post subject: Reply with quote

I played around a bit ...

Run the beanshell code (only once), then run the basic ...

The Toolbar generated is not peristant at all. You have to run the beanshell code once per OO session, and the Basic, when you want to show the toolbar.

If you want to stay with beanshell alone, it should be straightforward to translate the Basic to java.

If have not yet thought about how to communicate with the toolbar ...

Good luck,

ms777

Edit June 7, 2008: Somewhere between OO 2.3 and OO 2.4 the OO programmers screw up the class loading of beanshell http://qa.openoffice.org/issues/show_bug.cgi?id=89978 . This code no longer works. A work around for OO 2.4 you can find in a later post in this thread

The beanshell code:
Code:

/* original taken from
http://codesnippets.services.openoffice.org/Office/Office.AddingACombo_boxToAToolbar.snip
with modifications for beanshell by ms777
*/

package ms777;

import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.Property;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XInitialization;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.lang.XSingleComponentFactory;
import com.sun.star.lang.XServiceInfo;
import com.sun.star.lib.uno.helper.Factory;
import com.sun.star.lib.uno.helper.WeakBase;
import com.sun.star.lib.uno.helper.ComponentBase;
import com.sun.star.registry.XRegistryKey;
import com.sun.star.uno.XComponentContext;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XInterface;
import com.sun.star.uno.Type;
import com.sun.star.xml.sax.*;
import com.sun.star.frame.XToolbarController;
import com.sun.star.frame.XStatusListener;
import com.sun.star.util.XUpdatable;
import com.sun.star.frame.FeatureStateEvent;
import com.sun.star.awt.XWindow;
import com.sun.star.awt.XWindowPeer;
import com.sun.star.awt.WindowDescriptor;
import com.sun.star.awt.WindowClass;
import com.sun.star.awt.Rectangle;
import com.sun.star.awt.WindowAttribute;
import com.sun.star.awt.VclWindowPeerAttribute;
import com.sun.star.awt.XComboBox;
import com.sun.star.awt.XTextComponent;
import com.sun.star.awt.XFixedText;
import com.sun.star.awt.XToolkit;
import com.sun.star.lang.EventObject;
import com.sun.star.awt.XKeyListener;
import com.sun.star.awt.KeyEvent;

import com.sun.star.container.XSet;


public static class Toolbar_06 extends ComponentBase
implements XInitialization, XStatusListener, XUpdatable, XKeyListener, XServiceInfo, XToolbarController  {
//
  public static final String[] msServiceNames = { "ms777.testtoolbar06" };

  private XComponentContext mxContext;
  private XMultiComponentFactory mxMCF;
  private XMultiServiceFactory mxMSF;
  private String msInternalName;
  private XComponent mxDocument;
  private XTextComponent fixedText;
  private XComboBox cBox_xComboBox;

  public Toolbar_06(XComponentContext xContext ){

System.out.println("constructor called");

    try {
      mxContext = xContext;
      mxMCF = mxContext.getServiceManager();
      mxMSF = (XMultiServiceFactory) UnoRuntime.queryInterface(XMultiServiceFactory.class, mxMCF);
System.out.println("constructor try o.k.");
      }
    catch( Exception e ){ }

    msInternalName = new String();
    mxDocument = null;
System.out.println("constructor left");
    }

  public void initialize( Object[] args ) throws com.sun.star.uno.Exception {
System.out.println("initialize: args.len: "+args.length);
    for (k=0;k<args.length;k++) {
      arg = args[k];
System.out.println("initialize: arg "+k+": "+arg.Name + ": " + arg.Value);
      }
    }

  public String getName() {
   synchronized(this) {
     return msInternalName;
     }
  }

  public void setName( String sName ) { }

  public void execute ( short nKeyModifier ) {
System.out.println("execute: ");
    }

  public void click () { }

  public void doubleClick() { }

  public XWindow createPopupWindow () {return null; }

  public XWindow createItemWindow(XWindow xWindow) {
System.out.println("createItemWindow called");

// xMSF is set by initialize(Object[])
    try {
// get XWindowPeer
      XWindowPeer xWinPeer = (XWindowPeer) UnoRuntime.queryInterface(XWindowPeer.class, xWindow);
      Object o = mxMSF.createInstance("com.sun.star.awt.Toolkit");
      XToolkit xToolkit = (XToolkit) UnoRuntime.queryInterface(XToolkit.class, o);
// create WindowDescriptor
      WindowDescriptor wd = new WindowDescriptor();
      wd.Type = WindowClass.SIMPLE;
      wd.Parent = xWinPeer;
      wd.Bounds = new Rectangle(0, 0, 230, 23);
      wd.ParentIndex = (short) -1;
      wd.WindowAttributes = WindowAttribute.SHOW |VclWindowPeerAttribute .DROPDOWN;
      wd.WindowServiceName = "combobox";
// create ComboBox
System.out.println("createItemWindow combobox");
      XWindowPeer cBox_xWinPeer = xToolkit.createWindow(wd);
      cBox_xComboBox = (XComboBox) UnoRuntime.queryInterface(XComboBox.class, cBox_xWinPeer);
// Get Interface for manipulating the text in the combobox
      fixedText = (XTextComponent)UnoRuntime.queryInterface(XTextComponent.class,cBox_xComboBox);
      fixedText.setText("Enter Command Here");
      XWindow cBox_xWindow = (XWindow) UnoRuntime.queryInterface(XWindow.class, cBox_xWinPeer);
 // add some elements
      cBox_xComboBox.addItems(new String[] { "test", "foo", "bar", "test2", "foo2", "bar2" }, (short) 0);
// cBox_xComboBox.addItems(new String[] {""}, (short) 4);
      cBox_xComboBox.setDropDownLineCount((short) 6);
      cBox_xWindow.addKeyListener(this);

System.out.println("createItemWindow left o.k.");

      return cBox_xWindow;

    } catch (com.sun.star.uno.Exception e) {
System.out.println("createItemWindow left not o.k.");
    return null; }
  }

  public void statusChanged ( FeatureStateEvent aState ){
System.out.println("statusChanged: ");
    }

  public void disposing ( EventObject aSource ) { }

  public void update ( ) {
System.out.println("update: ");
    }

  public void keyPressed(KeyEvent event) { }

  public void keyReleased(KeyEvent event) { }
 
  public String[] getSupportedServiceNames() { return msServiceNames; }

  public boolean supportsService( String sService ) { return ( sService.equals( msServiceNames[0] )); }

  public String getImplementationName() { return this.getClass().getName(); }
  }
//
//--------------------   create and register a factory for your class
//
System.out.println( "create and register factories start");

XComponentContext Context = XSCRIPTCONTEXT.getComponentContext();

xFactory = Factory.createComponentFactory(Toolbar_06.class,   Toolbar_06.msServiceNames);

xDum = Context.getValueByName("/singletons/com.sun.star.lang.theServiceManager");
_SM = UnoRuntime.queryInterface(XSet.class, xDum);
_SM.insert(xFactory);
System.out.println( "create and register factories end");
return;


Here the Basic code:
Code:
const ResourceURL = "private:resource/toolbar/ms777_23"
const sUnoUrl = ".uno:CommandLineToolbar"
const sService = "ms777.testtoolbar06"
const sToolbarUIName = "ms777_23"

Sub Main

oo = createUnoService("com.sun.star.frame.ToolBarControllerFactory")
'xray oo
if oo.hasController( sUnoUrl, "") then oo.deregisterController( sUnoUrl, "")
oo.registerController( sUnoUrl, "", sService)

oLM = ThisComponent.CurrentController.Frame.Layoutmanager
if not IsNull(oLM.getElement(ResourceURL)) then oLM.destroyElement(ResourceURL)

oLM.createElement(ResourceURL)
oEL = oLM.getElement(ResourceURL)

oToolbarSettings = oEL.getSettings(true)
Dim aToolbarItem(1) as new com.sun.star.beans.PropertyValue
aToolbarItem(0).Name = "CommandURL"
aToolbarItem(0).Value = sUnoUrl
aToolbarItem(1).Name = "Label"
aToolbarItem(1).Value = "Test"

oToolbarSettings.insertByIndex( 0, aToolbarItem )
oToolbarSettings.UIName = sToolbarUIName
oEL.setSettings(oToolbarSettings)

oLM.showElement(ResourceURL)

end sub


Last edited by ms777 on Sat Jun 07, 2008 5:57 am; edited 1 time in total
Back to top
View user's profile Send private message
emorel
General User
General User


Joined: 17 Jan 2006
Posts: 18
Location: France

PostPosted: Fri Nov 17, 2006 8:24 am    Post subject: Reply with quote

Your answer helps me a lot. Thank you.

Before your answer, I was able to create the toolbar from java but without the combobox... I didn't see how to call createItemWindow. I was looking for the XComponentContext interface to get Xindow and trying to call createItemWindow in constructor... before ask you a better way.

Now I have translated the code to Java. It's OK ! :
* It's possible to cast XUIElement to XUIElementSetting. It seems logical but where is the link in the documentation ??? No interface or properties to indicate that could be made.
* Error if we set UIName after toolbarIndexContainer.insertByIndex like the basic code. Why ?

Eric

Here is my complete java code (Windows XP & OOo 2.0.3 & JDK 1.4.2). You need to add OOo path in the classpath :
Code:

package ms777;

/* original taken from
 http://codesnippets.services.openoffice.org/Office/Office.AddingACombo_boxToAToolbar.snip
 with modifications for beanshell by ms777
 */

import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.Property;
import com.sun.star.beans.PropertyVetoException;
import com.sun.star.beans.UnknownPropertyException;
import com.sun.star.beans.XPropertySet;
import com.sun.star.lang.IllegalArgumentException;
import com.sun.star.lang.IndexOutOfBoundsException;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XInitialization;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.lang.XSingleComponentFactory;
import com.sun.star.lang.XServiceInfo;
import com.sun.star.lib.uno.helper.Factory;
import com.sun.star.lib.uno.helper.WeakBase;
import com.sun.star.lib.uno.helper.ComponentBase;
import com.sun.star.registry.XRegistryKey;
import com.sun.star.ui.XModuleUIConfigurationManagerSupplier;
import com.sun.star.ui.XUIConfigurationManager;
import com.sun.star.ui.XUIElement;
import com.sun.star.ui.XUIElementSettings;
import com.sun.star.uno.XComponentContext;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XInterface;
import com.sun.star.uno.Type;
import com.sun.star.xml.sax.*;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.frame.XDesktop;
import com.sun.star.frame.XFrame;
import com.sun.star.frame.XLayoutManager;
import com.sun.star.frame.XLayoutManagerListener;
import com.sun.star.frame.XToolbarController;
import com.sun.star.frame.XStatusListener;
import com.sun.star.frame.XUIControllerRegistration;
import com.sun.star.util.XUpdatable;
import com.sun.star.frame.FeatureStateEvent;
import com.sun.star.awt.XWindow;
import com.sun.star.awt.XWindowPeer;
import com.sun.star.awt.WindowDescriptor;
import com.sun.star.awt.WindowClass;
import com.sun.star.awt.Rectangle;
import com.sun.star.awt.WindowAttribute;
import com.sun.star.awt.VclWindowPeerAttribute;
import com.sun.star.awt.XComboBox;
import com.sun.star.awt.XTextComponent;
import com.sun.star.awt.XFixedText;
import com.sun.star.awt.XToolkit;
import com.sun.star.lang.EventObject;
import com.sun.star.awt.XKeyListener;
import com.sun.star.awt.KeyEvent;

import com.sun.star.comp.helper.Bootstrap;
import com.sun.star.comp.helper.BootstrapException;
import com.sun.star.container.ElementExistException;
import com.sun.star.container.XIndexAccess;
import com.sun.star.container.XIndexContainer;
import com.sun.star.container.XSet;

/**
 * ToolBar controller component registration wrapper
 * <p>
 * This wrapper is used by the unopkg registration application, to register the
 * component name with the OpenOffice component Database.
 */
public class Toolbar_05 {

   /**
   * An com.sun.star.frame.XToolbarController implementation, for extending
   * the default operation and view of a Openoffice Toolbar.
   */
   public static class Toolbar_06 extends ComponentBase implements
         XInitialization, XStatusListener, XUpdatable, XKeyListener,
         XServiceInfo, XToolbarController {

       // the supported service names, the first one being the service name of the component itself
       /**
        * The Services supported by this component
        */
      public static final String[] msServiceNames = { "ms777.testtoolbar06" };

      private XComponentContext mxContext;

      private XMultiComponentFactory mxMCF;

      private XMultiServiceFactory mxMSF;

      private String msInternalName;

      private XComponent mxDocument;

      private XTextComponent fixedText;

      private XComboBox cBox_xComboBox;

      public Toolbar_06(XComponentContext xContext) {

         System.out.println("constructor called");

         try {
            mxContext = xContext;
            mxMCF = mxContext.getServiceManager();
            mxMSF = (XMultiServiceFactory) UnoRuntime.queryInterface(
                  XMultiServiceFactory.class, mxMCF);
            System.out.println("constructor try o.k.");
         } catch (Exception e) {
         }

         msInternalName = new String();
         mxDocument = null;
         System.out.println("constructor left");
      }

         /**
           * Component Initialization.
           */
      public void initialize(Object[] args) throws com.sun.star.uno.Exception {
         System.out.println("initialize: args.len: " + args.length);
         for (int k = 0; k < args.length; k++) {
            PropertyValue arg = (PropertyValue) args[k];
            System.out.println("initialize: arg " + k + ": " + arg.Name+ ": " + arg.Value);
         }
      }

       /**
        * Retunrns the internal name of this component
        *
        * @return String Name
        */
      public String getName() {
         synchronized (this) {
            return msInternalName;
         }
      }

       /**
        * Sets the internal name of this component
        *
        * @param sName The name to be set.
        */
      public void setName(String sName) {
      }

      public void execute(short nKeyModifier) {
         System.out.println("execute: ");
      }

       /**
        * Single Click Mouse event handler
        *
        */
      public void click() {
      }

       /**
        * Double Click Mouse event handler
        *
        */
      public void doubleClick() {
      }

       /**
        * Pop-up window creator. Not Implemented
        *
        */
      public XWindow createPopupWindow() {
         return null;
      }

       /**
        * Creates the command line combo box which will be embedded in the supplied com.sun.star.awt.XWindow.
        *
        * @param xWindow The XWindow instance which will contain the combo box
        * @return  XWindow
        * @see     XWindow       
        */
      public XWindow createItemWindow(XWindow xWindow) {

         // xMSF is set by initialize(Object[])
         try {
            // get XWindowPeer
            XWindowPeer xWinPeer = (XWindowPeer) UnoRuntime.queryInterface(
                  XWindowPeer.class, xWindow);
            Object o = mxMSF.createInstance("com.sun.star.awt.Toolkit");
            XToolkit xToolkit = (XToolkit) UnoRuntime.queryInterface(
                  XToolkit.class, o);
            // create WindowDescriptor
            WindowDescriptor wd = new WindowDescriptor();
            wd.Type = WindowClass.SIMPLE;
            wd.Parent = xWinPeer;
            wd.Bounds = new Rectangle(0, 0, 230, 23);
            wd.ParentIndex = (short) -1;
            wd.WindowAttributes = WindowAttribute.SHOW | VclWindowPeerAttribute.DROPDOWN;
            wd.WindowServiceName = "combobox";
            // create ComboBox
            XWindowPeer cBox_xWinPeer = xToolkit.createWindow(wd);
            cBox_xComboBox = (XComboBox) UnoRuntime.queryInterface(XComboBox.class, cBox_xWinPeer);
            // Get Interface for manipulating the text in the combobox
            fixedText = (XTextComponent) UnoRuntime.queryInterface(XTextComponent.class, cBox_xComboBox);
            fixedText.setText("Enter Command Here");
            XWindow cBox_xWindow = (XWindow) UnoRuntime.queryInterface(XWindow.class, cBox_xWinPeer);
            // add some elements
            cBox_xComboBox.addItems(new String[] { "test", "foo", "bar",
                  "test2", "foo2", "bar2" }, (short) 0);
            // cBox_xComboBox.addItems(new String[] {""}, (short) 4);
            cBox_xComboBox.setDropDownLineCount((short) 6);
            cBox_xWindow.addKeyListener(this);

            return cBox_xWindow;

         } catch (com.sun.star.uno.Exception e) {
            System.out.println("createItemWindow left not o.k.");
            return null;
         }
      }

         /**
          * Status Changed Event Listener
          * @param aState the com.sun.star.frame.FeatureStateEvent status
          */
      public void statusChanged(FeatureStateEvent aState) {
         System.out.println("statusChanged: ");
      }

        /**
         * Disposing event handler
         */
      public void disposing(EventObject aSource) {
      }

        /**
         * Toolbarcontroller com.sun.star.util.XUpdatable implementation update controller.
         *
         */
      public void update() {
         System.out.println("update: ");
      }

        /**
         * KeyPress event handler. This method is used to intercept the
         * Key press events
         *
         * @param event The com.sun.star.awt.KeyEvent that has occured
         * @see  KeyEvent
         */
      public void keyPressed(KeyEvent event) {
      }

        /**
         * @param event The com.sun.star.awt.KeyEvent that has occured
         * @see KeyEvent
         */
      public void keyReleased(KeyEvent event) {
      }

        /**
         * Returns the Service names supported by this component
         *
         * @return String[] ServiceNames
         */
      public String[] getSupportedServiceNames() {
         return msServiceNames;
      }

      public boolean supportsService(String sService) {
         return (sService.equals(msServiceNames[0]));
      }

        /**
         * Provides the implementation name of the service implementation
         *
         * @return The Implementation Name
         */
      public String getImplementationName() {
         return this.getClass().getName();
      }
   }

    // Retrieves the MultiServiceFactory of StarOffice

    public XMultiServiceFactory getMultiServiceFactory ( XComponentContext xComponentContext )
    throws java.lang.Exception {

        // Retrieve its
        // property DefaultContext and get the
        // remote service manager

        XMultiComponentFactory xRemoteServiceManager =
                xComponentContext.getServiceManager();

        // Instantiate the MultiServiceFactory service

        Object oMSF =
                xRemoteServiceManager.createInstanceWithContext(
                "com.sun.star.lang.MultiServiceFactory",
                xComponentContext);

        return (XMultiServiceFactory) UnoRuntime.queryInterface ( XMultiServiceFactory.class, oMSF);

    }

    public static void main(String[] args) {

      try {

         // -------------------- create and register a factory for your class
         XComponentContext xContext = Bootstrap.bootstrap();

         XSingleComponentFactory xFactory = Factory.createComponentFactory(Toolbar_06.class,
               Toolbar_06.msServiceNames);

         Object xDum = xContext.getValueByName("/singletons/com.sun.star.lang.theServiceManager");
         XSet _SM = (XSet) UnoRuntime.queryInterface(XSet.class, xDum);
         _SM.insert(xFactory);
         

         //--------------------   use the toolbar
         final String resourceURL = "private:resource/toolbar/ms777_23";
         final String sUnoUrl = ".uno:CommandLineToolbar";
         final String sService = "ms777.testtoolbar06";
         final String sToolbarUIName = "ms777_23";

         //--------------------   create the service
         //oo = createUnoService("com.sun.star.frame.ToolBarControllerFactory");
         Toolbar_05 tool05 = new Toolbar_05();
            XMultiServiceFactory xMSF = tool05.getMultiServiceFactory ( xContext );
            Object ooToolbar = xMSF.createInstance("com.sun.star.frame.ToolBarControllerFactory");
            XUIControllerRegistration oo = (XUIControllerRegistration) UnoRuntime.queryInterface ( XUIControllerRegistration.class, ooToolbar);
         if (oo.hasController( sUnoUrl, "")) oo.deregisterController( sUnoUrl, "");
         else oo.registerController( sUnoUrl, "", sService);

         //--------------------   get the layout manager
           Object desktop = xContext.getServiceManager().createInstanceWithContext(
                   "com.sun.star.frame.Desktop", xContext);
          
           XComponentLoader xCompLoader = (XComponentLoader) UnoRuntime.queryInterface(
               XComponentLoader.class, desktop);

         // Load a Writer document, which will be automaticly displayed
           xCompLoader.loadComponentFromURL("private:factory/swriter",
               "_blank", 0, new PropertyValue[0]);

          
           XDesktop xDesktop = (XDesktop) UnoRuntime.queryInterface(XDesktop.class, desktop);
           XFrame xFrame = xDesktop.getCurrentFrame();
           XPropertySet xPropSet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, xFrame);
           XLayoutManager oLM = (XLayoutManager) UnoRuntime.queryInterface(
                 XLayoutManager.class, xPropSet.getPropertyValue("LayoutManager"));
          

         //--------------------   get my toolbar
           if (oLM.getElement(resourceURL) != null) oLM.destroyElement(resourceURL);
         oLM.createElement(resourceURL);
         XUIElement toolbarUIElement = oLM.getElement(resourceURL);

         //oUIElement has this interface too... Not really clear with the documentation...
         XUIElementSettings toolbarUIElementSettings = (XUIElementSettings) UnoRuntime.queryInterface(
               XUIElementSettings.class, toolbarUIElement);

         XIndexAccess toolbarIndexAccess = toolbarUIElementSettings.getSettings(true);
            XPropertySet toolbarUIElementSettingsPropertySet = (XPropertySet)UnoRuntime.queryInterface( XPropertySet.class, toolbarIndexAccess );
            toolbarUIElementSettingsPropertySet.setPropertyValue("UIName", sToolbarUIName );
           
         PropertyValue [] aToolbarItem = new PropertyValue[2];
         aToolbarItem[0] = new PropertyValue();
         aToolbarItem[0].Name = "CommandURL";
         aToolbarItem[0].Value = sUnoUrl;
         aToolbarItem[1] = new PropertyValue();
         aToolbarItem[1].Name = "Label";
         aToolbarItem[1].Value = "Test";

         XIndexContainer toolbarIndexContainer = (XIndexContainer)
            UnoRuntime.queryInterface( XIndexContainer.class,toolbarIndexAccess );
         toolbarIndexContainer.insertByIndex( 0, aToolbarItem );
                    
            toolbarUIElementSettings.setSettings(toolbarIndexAccess);
         oLM.showElement(resourceURL);

      } catch (BootstrapException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      } catch (IllegalArgumentException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      } catch (ElementExistException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      } catch (IndexOutOfBoundsException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      } catch (WrappedTargetException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      } catch (UnknownPropertyException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      } catch (PropertyVetoException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      } catch (Exception e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }
}
Back to top
View user's profile Send private message
ms777
Super User
Super User


Joined: 07 Feb 2004
Posts: 1355

PostPosted: Sun Nov 19, 2006 3:38 am    Post subject: Reply with quote

emorel wrote:

* It's possible to cast XUIElement to XUIElementSetting. It seems logical but where is the link in the documentation ???


I believe that not all XUIElements have a XUIElementSetting. Rather than the documentation, I pretty much work with OO Basic and the XRay tool. XRaying on the predefined toolbars showed the Settings ...

ms777
Back to top
View user's profile Send private message
emorel
General User
General User


Joined: 17 Jan 2006
Posts: 18
Location: France

PostPosted: Fri Nov 24, 2006 2:57 am    Post subject: Reply with quote

Hi,

I would like to add a button in the toolbar with my own event. I have tried two ways but I have two pbs... :
* Use a macro in OOo basic but that needs a basic library installed before I don't want (see code below). I read that it's not possible to add a basic library from java (tried to translate this code http://www.oooforum.org/forum/viewtopic.phtml?t=18781) because the XLibraryContainer interface could not be get (no service instantiate this interface) : http://www.oooforum.org/forum/viewtopic.phtml?t=760
Here is the code to add a button :
Code:

        PropertyValue[] itemProperty = new PropertyValue[3];
        itemProperty[0] = new PropertyValue();
        itemProperty[0].Name = "CommandURL";
        itemProperty[0].Value = "macro:///Standard.Module1.myMacro()";
        itemProperty[1] = new PropertyValue();
        itemProperty[1].Name = "Label";
        itemProperty[1].Value = "myMacro";
        itemProperty[2] = new PropertyValue();
        itemProperty[2].Name = "Type";
        itemProperty[2].Value = new Integer(0);


* Create my own buttonToolbar implementation and put my code in the keyListener event but that doesn't work. I can't create the button :
Code:
   public XWindow createItemWindow(XWindow xWindow) {

      // xMSF is set by initialize(Object[])
      try {
         // get XWindowPeer
         XWindowPeer xWinPeer = (XWindowPeer) UnoRuntime.queryInterface(
               XWindowPeer.class, xWindow);
         Object o = mxMSF.createInstance("com.sun.star.awt.Toolkit");
         XToolkit xToolkit = (XToolkit) UnoRuntime.queryInterface(
               XToolkit.class, o);
         // create WindowDescriptor
         WindowDescriptor wd = new WindowDescriptor();
         wd.Type = WindowClass.SIMPLE;
         wd.Parent = xWinPeer;
         wd.Bounds = new Rectangle(0, 0, 20, 23);
         wd.ParentIndex = (short) -1;
         wd.WindowAttributes = WindowAttribute.SHOW;
         wd.WindowServiceName = "button";
         // create Button
         XWindowPeer cBox_xWinPeer = xToolkit.createWindow(wd);// null here
         xButton = (XButton) UnoRuntime.queryInterface(XButton.class, cBox_xWinPeer);
         xButton.setLabel("My Texte");
         XWindow cBox_xWindow = (XWindow) UnoRuntime.queryInterface(XWindow.class, cBox_xWinPeer);
         cBox_xWindow.addKeyListener(this);

         return cBox_xWindow;

      } catch (com.sun.star.uno.Exception e) {
         System.out.println("createItemWindow left not o.k.");
         return null;
      }
   }


The second way is the best for me. Do you understand where is the error ?

Eric
Back to top
View user's profile Send private message
ms777
Super User
Super User


Joined: 07 Feb 2004
Posts: 1355

PostPosted: Fri Nov 24, 2006 7:52 pm    Post subject: Reply with quote

emorel wrote:

The second way is the best for me. Do you understand where is the error ?
Eric


I believe it is the WindowServiceName. If you have a look at the source code (/source/gsl/toolkit/source/awt/vclxtoolkit.cxx), you find the below ServiceNames. 'button' is not listed. You probably have to use 'pushbutton'

Good luck,

ms777
Code:
337 static ComponentInfo __FAR_DATA aComponentInfos [] =
338 {
339         { "buttondialog",               WINDOW_BUTTONDIALOG },
340         { "cancelbutton",               WINDOW_CANCELBUTTON },
341         { "checkbox",                   WINDOW_CHECKBOX },
342         { "combobox",                   WINDOW_COMBOBOX },
343         { "control",                    WINDOW_CONTROL },
344         { "currencybox",                WINDOW_CURRENCYBOX },
345         { "currencyfield",              WINDOW_CURRENCYFIELD },
346         { "datebox",                    WINDOW_DATEBOX },
347         { "datefield",                  WINDOW_DATEFIELD },
348         { "dialog",                             WINDOW_DIALOG },
349         { "dockingarea",                WINDOW_DOCKINGAREA },
350         { "dockingwindow",              WINDOW_DOCKINGWINDOW },
351         { "edit",                               WINDOW_EDIT },
352         { "errorbox",                   WINDOW_ERRORBOX },
353         { "fixedbitmap",                WINDOW_FIXEDBITMAP },
354         { "fixedimage",                 WINDOW_FIXEDIMAGE },
355         { "fixedline",                  WINDOW_FIXEDLINE },
356         { "fixedtext",                  WINDOW_FIXEDTEXT },
357         { "floatingwindow",             WINDOW_FLOATINGWINDOW },
358         { "framewindow",                VCLWINDOW_FRAMEWINDOW },
359         { "groupbox",                   WINDOW_GROUPBOX },
360         { "helpbutton",                 WINDOW_HELPBUTTON },
361         { "imagebutton",                WINDOW_IMAGEBUTTON },
362         { "imageradiobutton",   WINDOW_IMAGERADIOBUTTON },
363         { "infobox",                    WINDOW_INFOBOX },
364         { "listbox",                    WINDOW_LISTBOX },
365         { "longcurrencybox",    WINDOW_LONGCURRENCYBOX },
366         { "longcurrencyfield",  WINDOW_LONGCURRENCYFIELD },
367         { "menubutton",                 WINDOW_MENUBUTTON },
368         { "messbox",                    WINDOW_MESSBOX },
369         { "metricbox",                  WINDOW_METRICBOX },
370         { "metricfield",                WINDOW_METRICFIELD },
371         { "modaldialog",                WINDOW_MODALDIALOG },
372         { "modelessdialog",             WINDOW_MODELESSDIALOG },
373         { "morebutton",                 WINDOW_MOREBUTTON },
374         { "multilistbox",               WINDOW_MULTILISTBOX },
375         { "numericbox",                 WINDOW_NUMERICBOX },
376         { "numericfield",               WINDOW_NUMERICFIELD },
377         { "okbutton",                   WINDOW_OKBUTTON },
378         { "patternbox",                 WINDOW_PATTERNBOX },
379         { "patternfield",               WINDOW_PATTERNFIELD },
380         { "pushbutton",                 WINDOW_PUSHBUTTON },
381         { "querybox",                   WINDOW_QUERYBOX },
382         { "radiobutton",                WINDOW_RADIOBUTTON },
383         { "scrollbar",                  WINDOW_SCROLLBAR },
384         { "scrollbarbox",               WINDOW_SCROLLBARBOX },
385         { "spinbutton",                 WINDOW_SPINBUTTON },
386         { "spinfield",                  WINDOW_SPINFIELD },
387         { "splitter",                   WINDOW_SPLITTER },
388         { "splitwindow",                WINDOW_SPLITWINDOW },
389         { "statusbar",                  WINDOW_STATUSBAR },
390         { "systemchildwindow",  VCLWINDOW_SYSTEMCHILDWINDOW },
391         { "tabcontrol",                 WINDOW_TABCONTROL },
392         { "tabdialog",                  WINDOW_TABDIALOG },
393         { "tabpage",                    WINDOW_TABPAGE },
394         { "timebox",                    WINDOW_TIMEBOX },
395         { "timefield",                  WINDOW_TIMEFIELD },
396         { "toolbox",                    WINDOW_TOOLBOX },
397         { "tristatebox",                WINDOW_TRISTATEBOX },
398         { "warningbox",                 WINDOW_WARNINGBOX },
399         { "window",                             WINDOW_WINDOW },
400         { "workwindow",                 WINDOW_WORKWINDOW }
401 };
Back to top
View user's profile Send private message
emorel
General User
General User


Joined: 17 Jan 2006
Posts: 18
Location: France

PostPosted: Fri Dec 01, 2006 10:55 am    Post subject: Reply with quote

Thanks a lot. Smile

Of course, I search informations on WindowServiceName on the documentation that seemed to be the pb for me too but I found only "specifies the name of the component service." Well, I know that a complete documentation is not easy... but that's short !

With "pushbutton" the code works perfectly. Thanks again.

Eric
Back to top
View user's profile Send private message
emorel
General User
General User


Joined: 17 Jan 2006
Posts: 18
Location: France

PostPosted: Wed Dec 13, 2006 3:18 am    Post subject: Reply with quote

Hi,

One last problem : the propertyName "Label" doesn't work. In fact when I use the following code, that sets the button helptext (when the mouse stays on the button) instead of the button Label :

Code:

      PropertyValue[] aToolbarItem = new PropertyValue[2];
      aToolbarItem = new PropertyValue[2];
      aToolbarItem[0] = new PropertyValue();
      aToolbarItem[0].Name = "CommandURL";
      aToolbarItem[0].Value = ButtonToolbarElement.UNO_URL;
      aToolbarItem[1] = new PropertyValue();
      aToolbarItem[1].Name = "Label";
      aToolbarItem[1].Value = label;


Why ? For XButton, there is the setLabel method so the name should be "Label" ?

So I can't have one class (easily) for all my buttons in my toolbar because I need to put the label name with the setText method in createItemWindow.

Thanks for your help.

Eric
Back to top
View user's profile Send private message
Peter
OOo Enthusiast
OOo Enthusiast


Joined: 28 May 2004
Posts: 105
Location: Berlin / Germany

PostPosted: Wed Dec 13, 2006 7:02 am    Post subject: How to insert a toolbar with icons and shortcuts in BASIC Reply with quote

Hi ms777,

you helped us a lot with your code examples.
The Basic code above shows the non-persistent inserting of a label and works without running the beanshell too.
But how to additionally inserting an icon and a shortcut for the macro to this object?
And how to change the position of the toolbar (it should start in a new line)? Any ideas?

Sincerely

Peter
Back to top
View user's profile Send private message
ms777
Super User
Super User


Joined: 07 Feb 2004
Posts: 1355

PostPosted: Wed Dec 13, 2006 2:18 pm    Post subject: Re: How to insert a toolbar with icons and shortcuts in BASI Reply with quote

Peter wrote:

But how to additionally inserting an icon and a shortcut for the macro to this object?
And how to change the position of the toolbar (it should start in a new line)? Any ideas?


Hi,

I have successfully managed to insert a 16x16 pic into the selection for toolbar items. I failed to generate the toolbar item with the pic included. Without pic, it is o.k.. I believe there is something still wrong with OO ...
To dock the toolbar, you should get the Toolbar by the LayoutManager and call the dockWindow on the selected toolbar's RealInterface

Good luck,

ms777
Back to top
View user's profile Send private message
ms777
Super User
Super User


Joined: 07 Feb 2004
Posts: 1355

PostPosted: Wed Dec 13, 2006 4:23 pm    Post subject: Reply with quote

I gave it a second try. Try this ...

Good luck,

ms777


Code:
Sub Main
sUrl = "vnd.sun.star.script:Standard.Module1.Test?language=Basic&location=document"


'use this if you want to store the menu globally
oModMan = createUnoService("com.sun.star.frame.ModuleManager")
sModuleIndentifyer = oModMan.identify(ThisComponent)
oModuleCfgMgrSupplier = createUnoService("com.sun.star.ui.ModuleUIConfigurationManagerSupplier")
oModuleCfgMgr = oModuleCfgMgrSupplier.getUIConfigurationManager(sModuleIndentifyer )
'use this if you want to store the menu only with the document
oModuleCfgMgr = ThisComponent.getUIConfigurationManager
'xray oModuleCfgMgr


oIm = oModuleCfgMgr.ImageManager
'xray oIm
if not oIm.hasImage(com.sun.star.ui.ImageType.SIZE_DEFAULT, sUrl) then
  oGraph = GetGraphFromHexString(GetPicHexString())
  oIm.insertImages( com.sun.star.ui.ImageType.SIZE_DEFAULT, Array(sUrl), Array(oGraph)) 
  oIm.store()
  endif

'The code below is mainly from Carsten Driesner ( http://api.openoffice.org/servlets/ReadMsg?list=dev&msgNo=16882 )
REM *** Creates a new custom toolbar persistently for the Basic IDE

REM *** The name of our new custom toolbar. A custom toolbar name MUST
REM *** start with "custom_"!
sToolbar = "private:resource/toolbar/custom_toolbar"
   

   
REM *** Create a settings container which will define the structure of our new
REM *** custom toolbar.
oToolbarSettings = oModuleCfgMgr.createSettings()
   
REM *** Set a title for our new custom toolbar
oToolbarSettings.UIName = "My little custom toolbar"
   
REM *** Create a button for our new custom toolbar
oToolbarItem = CreateToolbarItem( sUrl, "press here now" )
oToolbarSettings.insertByIndex( 0, oToolbarItem )
   
REM *** Set the settings for our new custom toolbar. (replace/insert)
if ( oModuleCfgMgr.hasSettings( sToolbar )) then
  oModuleCfgMgr.replaceSettings( sToolbar, oToolbarSettings )
  else
  oModuleCfgMgr.insertSettings( sToolbar, oToolbarSettings )
  endif
oModuleCfgMgr.store
End Sub

Function CreateToolbarItem( Command as String, Label as String ) as Variant
Dim aToolbarItem(3) as new com.sun.star.beans.PropertyValue

aToolbarItem(0).Name = "CommandURL"
aToolbarItem(0).Value = Command
aToolbarItem(1).Name = "Label"
aToolbarItem(1).Value = Label
aToolbarItem(2).Name = "Type"
aToolbarItem(2).Value = 0
aToolbarItem(3).Name = "Visible"
aToolbarItem(3).Value = true

CreateToolbarItem = aToolbarItem()
End Function


function GetGraphFromHexString(sHex as String) as Any 
oStorageFac = createUnoService("com.sun.star.embed.StorageFactory")
oStorage    = oStorageFac.createInstance
oStream     = oStorage.openStreamElement("ms777", com.sun.star.embed.ElementModes.READWRITE)

oDataOutputStream = createUNOService ("com.sun.star.io.DataOutputStream")
oDataOutputStream.setOutputStream(oStream)
for k=0 to len(sHex)/2-1
  i = CInt("&H" & Mid(sHex, 2*k+1,2))
  if i >=128 then i = i-256
  oDataOutputStream.writeByte(i)
  next k

oDataOutputStream.flush
oDataOutputStream.closeOutput 
 
oProvider = createUnoService("com.sun.star.graphic.GraphicProvider")
Dim oProps(0)as new com.sun.star.beans.PropertyValue
oProps(0).Name  = "InputStream"
oProps(0).Value = oStream
GetGraphFromHexString = oProvider.queryGraphic(oProps())
end function


function GetPicHexString() as String
s =     "47494638396110001000B30000FBFDFB0301EB03DDFBFBCDFB"
s = s & "030103FFFFFFFFFFFFFFFFFFA75120237725EAFF2EFFFF889F"
s = s & "9FFF2317FFEAEDFFFFFFFF21F90401000000002C0000000010"
s = s & "00100003043E10C829EABC93E8BCB1FEC0D771121196E6D599"
s = s & "E90804E10683B014D4EF3DE9F9EDFF3E1B705823107F28E371"
s = s & "265AE22ECEA0307A192C07188075889D4400003B"
GetPicHexString = s
end function



Sub Test
   MsgBox "Test"
End Sub
Back to top
View user's profile Send private message
Peter
OOo Enthusiast
OOo Enthusiast


Joined: 28 May 2004
Posts: 105
Location: Berlin / Germany

PostPosted: Fri Dec 22, 2006 9:45 am    Post subject: Reply with quote

ms777 wrote:

'The code below is mainly from Carsten Driesner ( http://api.openoffice.org/servlets/ReadMsg?list=dev&msgNo=16882 )


Oh, I miss your postings there Wink

Btw I filed a summarizing example into the codesnippets
Back to top
View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic    OOoForum.org Forum Index -> OpenOffice.org Macros and API All times are GMT - 8 Hours
Goto page 1, 2  Next
Page 1 of 2

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group