Share this Page URL
Help

Chapter 9. SWT Layouts > Controlling Widget Sizing and Alignment - Pg. 145

What just happened? Creating column headings is just a matter of adding Label widgets to the first row of the grid and setting their text property to that desired for the heading: final Label l1 = new Label(s, SWT.BORDER); l1.setText("Column One"); final Label l2 = new Label(s, SWT.BORDER); l2.setText("Column Two"); final Label l3 = new Label(s, SWT.BORDER); l3.setText("Column Three"); Text widgets are then used to complete each row of the grid, to enable the user to interact with data in a tabular form: final final final final final final Text Text Text Text Text Text t1 t2 t3 t4 t5 t6 = = = = = = new new new new new new Text(s, Text(s, Text(s, Text(s, Text(s, Text(s, SWT.SINGLE SWT.SINGLE SWT.SINGLE SWT.SINGLE SWT.SINGLE SWT.SINGLE | | | | | | SWT.BORDER); SWT.BORDER); SWT.BORDER); SWT.BORDER); SWT.BORDER); SWT.BORDER); Since the example creates a three-column grid, every three widgets added comprise a single row. To keep the table effect, the number of Text widgets must be a multiple of three; otherwise, one row is not fully populated , and the table effect is spoiled. Controlling Widget Sizing and Alignment If you examine the executing GridLayoutExample , you discover several problems with the default GridLayout settings. First, the widgets are given a default size, which leads to alignment problems if there are widgets of differing types (as with Label and Text widgets). Second, you see that resizing the window does not result in resizing the widg- ets, which is one of the basic reasons for using a layout in the first place. The use of additional GridLayout settings and another class called GridData helps solve these issues. How do I do that? GridData is the class that provides GridLayout with the ability to handle size and position of widgets. Each widget can have a data layout associated with it using the widget's setDataLayout() method. To accomplish this, you must create an instance of the GridData class, then call setLayoutData() on the widget which you are adding to the grid: GridData gd = new GridData( ); gd.horizontalAlignment = GridData.CENTER; l1.setLayoutData(gd); gd = new GridData( ); gd.horizontalAlignment = GridData.CENTER; l2.setLayoutData(gd); Controlling Widget Sizing and Alignment | 145