Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement Auto-Hide Scrollbar in SWT Text Component

Tags:

scrollbar

swt

I have a SWT Text component, for which I set SWT.MULTI, SWT.V_SCROLL and SWT.H_SCROLL to show the scrollbar when required. I found that even content is smaller than the text component then also scrollbar are visible in disable state.

Is there is any way through which I can auto hide the scrollbar? Like java Swing has JScrollPane.horizontal_scrollbar_as_needed

like image 516
Shashwat Avatar asked Dec 17 '11 19:12

Shashwat


3 Answers

You can use StyledText instead of Text. StyledText has method setAlwaysShowScrollBars which can be set to false.

like image 57
Kumar Avatar answered Nov 05 '22 18:11

Kumar


That works on all cases:

Text text = new Text(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);

Listener scrollBarListener = new Listener () {
  @Override
  public void handleEvent(Event event) {
    Text t = (Text)event.widget;
    Rectangle r1 = t.getClientArea();
    Rectangle r2 = t.computeTrim(r1.x, r1.y, r1.width, r1.height);
    Point p = t.computeSize(SWT.DEFAULT,  SWT.DEFAULT,  true);
    t.getHorizontalBar().setVisible(r2.width <= p.x);
    t.getVerticalBar().setVisible(r2.height <= p.y);
    if (event.type == SWT.Modify) {
      t.getParent().layout(true);
      t.showSelection();
    }
  }
};
text.addListener(SWT.Resize, scrollBarListener);
text.addListener(SWT.Modify, scrollBarListener);
like image 7
Plamen Avatar answered Nov 05 '22 20:11

Plamen


@Plamen: great solution thanks. I had the same problem but for a multiline-text with style SWT.WRAP without a horizontal scrollbar.

I had to change a few things in order to make this work properly:

Text text = new Text(parent, SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);

Listener scrollBarListener = new Listener (){
    @Override
    public void handleEvent(Event event) {
        Text t = (Text)event.widget;
        Rectangle r1 = t.getClientArea();
        // use r1.x as wHint instead of SWT.DEFAULT
        Rectangle r2 = t.computeTrim(r1.x, r1.y, r1.width, r1.height); 
        Point p = t.computeSize(r1.x,  SWT.DEFAULT,  true); 
        t.getVerticalBar().setVisible(r2.height <= p.y);
        if (event.type == SWT.Modify){
           t.getParent().layout(true);
        t.showSelection();
    }
}};
text.addListener(SWT.Resize, scrollBarListener);
text.addListener(SWT.Modify, scrollBarListener);
like image 6
Dieter Rehbein Avatar answered Nov 05 '22 19:11

Dieter Rehbein