Search code examples
swingmatlabjscrollpanematlab-gui

Jscrollpane in matlab


I am trying to use some java gui in my matlab code. I want to create a Jpanel containing lots of buttons , and add this Jpanel to a JscrollPane to be able to scroll up and down, right and left through the Jpanel. I tried using JavaComponent() function as described in : http://undocumentedmatlab.com/blog/javacomponent

here is my code:

[jpanel1, hpanel1] = javacomponent('javax.swing.JPanel');
[jButton1, hButton1] = javacomponent('javax.swing.JButton');
[jscroll, hscroll] = javacomponent('javax.swing.JScrollPane');

jButton1.setText('Click again!'); 
set(hButton1,'position',[5 5 50 50])
set(hpanel1,'position',[50 50 500 500],'BackgroundColor','white');
jpanel1.add(jButton1);
jscroll.add(jpanel1);

The panel and button are created but I can't find the scrollpane, tried setting the jscroll to visible with no results. WHat am I missing out??


Solution

  • You only need to use javacomponent once, to display the outer-most java container, i.e. JScrollPane in your case. Just assemble your components inside JPanel container and then pass that to JScrollPane constructor.

    Note that it is safer to create your objects with javaObjectEDT so that subsequent method calls run on EDT - otherwise you could face a deadlock / race condition.

    Finally, note how you can use getpixelposition and 'normalized' units for the container created by javacomponent to make your JScrollPane fill the entire parent drawing area, and behave better on resizing.

    jButton1 = javaObjectEDT('javax.swing.JButton', 'Button 1');
    jButton2 = javaObjectEDT('javax.swing.JButton', 'Button 2');
    jPanel = javax.swing.JPanel();
    jPanel.add(jButton1);
    jPanel.add(jButton2);
    jScrollPane = javax.swing.JScrollPane(jPanel);
    
    hFig = figure();
    hParent = uicontainer('Parent',hFig);
    parentPixelPos = getpixelposition(hParent);
    pos = [1,1,parentPixelPos(3),parentPixelPos(4)]; % fill the parent uicontainer completely
    [~, hContainer] = javacomponent(jScrollPane, pos, hParent);
    set(hContainer, 'Units', 'normalized');  % better behavior on resizing