Friday, May 15, 2009

How to use Form layout

Form layout is basically very flexible layout and used to place controls in a composite when there is no idea about how to layout them ahead. i.e layout controls depend on a single control(X). when the position of control(X) is changed, the dependent controls positions will be changed consequently.

For example:

Composite buttonPanel = new Composite(this, SWT.NONE);
buttonPanel.setLayout(new FormLayout());
final FormData buttonPanelFormData = new FormData();
int m_offset = 10; // border offset.
buttonPanelFormData.top = new FormAttachment(0, m_offset);
buttonPanelFormData.left = new FormAttachment(0, m_offset);
buttonPanelFormData.right = new FormAttachment(100, -m_offset);
buttonPanel.setLayoutData(buttonPanelFormData);

Button m_addButton = new Button(buttonPanel, SWT.PUSH);
m_addButton.setText(BUTTON_ADD_LABEL);
FormData addButtonFormData = new FormData();
addButtonFormData.top = new FormAttachment(0, 0);
addButtonFormData.left = new FormAttachment(0, 0);
addButtonFormData.width = 20; //button width;
m_addButton.setLayoutData(addButtonFormData);

Button m_editButton = new Button(buttonPanel, SWT.PUSH);
m_editButton.setText(BUTTON_EDIT_LABEL);
FormData editButtonFormData = new FormData();
editButtonFormData.top = new FormAttachment(0, 0);
// edit button is placed next to add button with horizontal gap of m_offset
editButtonFormData.left = new FormAttachment(m_addButton, m_offset);
editButtonFormData.width = 20;//button width
m_editButton.setLayoutData(editButtonFormData);

Similarly controls can be placed anywhere with the reference of control(X).

Thursday, May 14, 2009

How to embed Swing control inside SWT Composite?

You need an SWT_AWT bridge to create WEmbeddedFrame which will be used to add Swing Controls.

Here is sample code that adds JLabel to AWT frame.

JLabel label = new JLabel("sample label");


Composite composite = new Composite(shell, SWT.EMBEDDED);

Frame frame = SWT_AWT.new_Frame(composite);

frame.setLayout(new BorderLayout());

frame.add(label,BorderLayout.CENTER);