Reputation: 567
I tried adding a number for each row in my tree. The tree and its numbering is working but not that great so is there any other best way to implement this? because if the tree node expanded I have to get all the expanded tree node and increase its numbering. I also used the TreeViewer to create the tree.
// base container
Composite composite = new Composite( (Composite) parent, SWT.NONE );
composite.setLayout( new GridLayout( 2, false ) );
composite.setLayoutData( new GridData( SWT.FILL, SWT.FILL, true, true ) );
// The container for numbering in the tree
Composite numComposite = new Composite( composite, SWT.NONE );
numComposite.setLayout( new FillLayout( SWT.VERTICAL ) );
numComposite.setLayoutData( new GridData( GridData.VERTICAL_ALIGN_BEGINNING ) );
// the tree container
MyTree tree = new MyTree( composite );
tree.setContentProvider( new ContentProvider() );
Label test = new Label( numComposite, SWT.NONE );
test.setText( "1" );
test = new Label( numComposite, SWT.NONE );
test.setText( "2" );
test = new Label( numComposite, SWT.NONE );
test.setText( "3" );
test = new Label( numComposite, SWT.NONE );
test.setText( "4" );
test = new Label( numComposite, SWT.NONE );
test.setText( "5" );
Upvotes: 2
Views: 391
Reputation: 21025
I suggest to start with a custom Canvas
control that has the same height as the Tree
widget.
Whenever the vertical scroll position of the tree is changed the Canvas need to be redrawn (canvas.redraw()
). To track such changes, several listeners need to be added
tree.getVerticalBar().addSelectionListener()
) on the scroll bar tree.addKeyListener()
) that updates the Canvas when navigation keys such as Up/Down, PgUp/PgDn, etc. are pressedtree.addControlListener()
) that updates the size and content of the Canvas when the tree is resizedThe paint listener of the custom Canvas could draw the row numbers. The first row number could be derived from the top index (tree.getTopIndex()
). Subsequent row numbers would use the tree's item height (tree.getItemHeight()
) to align themselves with the rows.
I have uploaded a draft of the above-sketched solution here:
https://gist.github.com/rherrmann/fc248fb01a00fb4fa73187cbbdaf441f
A main
method is included that that demonstrates the row number ruler with a small SWT application.
The preferred width is currently derived from the width of the string "9999" in the current font. But since the maximum row number can always be computed with getVisibleItemCount()
it shouldn't be hard to adjust the preferred width provide enough room for the row numbers currently being displayed.
The tricky part will probably be to determine when to relayout the parent of Tree and TreeRule after the preferred width changed.
There may be minor glitches here and there that need to be addressed, but overall, the code shows the feasibility of this approach.
The code in getVisibleItemCount()
is copied from an SWT Snippet and then adjusted.
Upvotes: 5