How to implement an Auto-Hide scrollbar in a SWT text component

I have a SWT Text component for which I set SWT.MULTI , SWT.V_SCROLL and SWT.H_SCROLL to display the scroll bar as needed. I found that even the content is smaller than the text component, and also the scroll bars are displayed in the off state.

Is there any way that I can automatically hide the scroll bar? How java Swing has JScrollPane.horizontal_scrollbar_as_needed

+7
source share
4 answers

This works in 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 <= px); t.getVerticalBar().setVisible(r2.height <= py); if (event.type == SWT.Modify) { t.getParent().layout(true); t.showSelection(); } } }; text.addListener(SWT.Resize, scrollBarListener); text.addListener(SWT.Modify, scrollBarListener); 
+7
source

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

+8
source

@Plamen: great solution. I had the same problem, but for multi-line text with SWT.WRAP style without horizontal scrollbar.

I had to change a few things to do it right:

 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 <= py); if (event.type == SWT.Modify){ t.getParent().layout(true); t.showSelection(); } }}; text.addListener(SWT.Resize, scrollBarListener); text.addListener(SWT.Modify, scrollBarListener); 
+6
source

According to this, you cannot hide the vertical scroll bar, it is the OS (Windows) defined by L & F. You can get rid of the horizontal bar using SWT.WRAP without SWT.H_SCROLL .

+1
source

Source: https://habr.com/ru/post/1386855/


All Articles