Coding Tips (JavaScript/CSS/VBA/Win32)
Adding Controls
Let's add three controls to the dialog: a label, a text-box and a button that will display a File Open Dialog when it is clicked. SWT controls are placed on the screen using one of the four layouts:
- FillLayout – lays out equal-sized controls in a single row or column
- RowLayout – lays out controls in a row or rows, with fill, wrap, and spacing options
- GridLayout – lays out controls in a grid
- FormLayout – lays out comtrols by creating attachments for each of their sides
We are going to use the GridLayout for our controls.
GridLayout gridLayout = new GridLayout (); gridLayout.numColumns = 3; gridLayout.marginWidth=10; shell.setLayout (gridLayout);
Basically, the code says that we want three controls on each row with a margin of 10 pixels on each side of the row.
final Label label1 = new Label(shell, SWT.NULL); label1.setText("File"); final Text text1 = new Text(shell, SWT.BORDER); text1.setText(""); Button button1 = new Button(shell,SWT.PUSH); button1.setText("Browse..."); button1.setToolTipText("Locate file");
Now, the screen should look like this:
This a big step forward. We displayed controls on the dialog, and they have been given their default size.
However, we'd like the text box to be wider:
GridData data = new GridData (); data.widthHint = 400; data.grabExcessHorizontalSpace = true; text1.setLayoutData (data);
A layout class in SWT may have a corresponding layout data class that contains layout data for a specific control. In this case, we created an instance of GridData class that specified the width of 400 pixels, and that a control should shrink if there is not enough space for it.
The screen looks like this now:
Right now, the Browse... button does not do anything useful when you click on it. Let's write code that will open a File Dialog and put the selected file name to the text box.
button1.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { int style = SWT.NONE; FileDialog dialog = new FileDialog (shell, style); dialog.setText ("Find a File"); String result = dialog.open(); if(result!=null){ text1.setText(result); } } });
Check back for more later.