DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

CSpinner For SWT

09.07.2006
| 3485 views |
  • submit to reddit
        This is a simple Spinner component for SWT
It's not complete and it's -for sure- not very eye-pleasing.

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Slider;
import org.eclipse.swt.widgets.Text;

public class CSpinner extends Composite {
    private Text text;
    private Slider slider;
    private int value = 119;
    
    public CSpinner(Composite parent, int style) {
        super(parent, SWT.BORDER | style);

        GridLayout thisLayout = new GridLayout();
        thisLayout.horizontalSpacing = 0;
        thisLayout.numColumns = 2;
        thisLayout.marginHeight = 0;
        thisLayout.marginWidth = 0;
        thisLayout.verticalSpacing = 0;
        setLayout(thisLayout);
        setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        
        text = new Text(this, SWT.NONE);
        text.setText("" + value);
        text.addKeyListener(new KeyAdapter() {
            public void keyReleased(KeyEvent e) {
                try {
                    value = Integer.parseInt(text.getText());
                    slider.setSelection(value);
                    text.setBackground(new Color(getDisplay(), 255, 255, 255));
                    text.setToolTipText("");
                } catch(NumberFormatException e1) {
                    text.setBackground(new Color(getDisplay(), 255, 192, 192));
                    text.setToolTipText("Only integer values are accepted.");
                }
            }
        });
        text.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL));
        slider = new Slider(this, SWT.VERTICAL);
        slider.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {
                text.setText("" + slider.getSelection());
            }
        });
        slider.setValues(value, 0, 65535, 1, 1, 10);
        GridData sliderLData = new GridData();
        sliderLData.widthHint = 14;
        sliderLData.heightHint = 21;
        slider.setLayoutData(sliderLData);
    }
    
    public String getText() {
        return text.getText();
    }
}