Skip to content

Calculator

greipadmin edited this page Jan 31, 2017 · 18 revisions

Introduction

A simple calculator, displayed as a whole widget or inside a tool window.

Example 1 (whole widget)

final Calculator calculator = new Calculator(parent);
calculator.setDecimalFormat(new DecimalFormat("#,##0.## €"));

Example 2 (popup)

package org.greip.demos;

import java.math.BigDecimal;
import java.text.DecimalFormat;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.greip.calculator.CalculatorTextAdapter;

public class CalculatorPopupDemo {

	public static void main(final String[] args) {
		final Display display = new Display();
		final Shell shell = new Shell(display);

		shell.setText("Greip - Calculator Popup Demo");
		shell.setLayout(new GridLayout(2, false));

		new Label(shell, SWT.NONE).setText("Enter a number:");

		final Text txt = new Text(shell, SWT.RIGHT | SWT.BORDER);
		txt.setLayoutData(new GridData(100, SWT.DEFAULT));

		final Label lbl = new Label(shell, SWT.NONE);
		lbl.setText("Press Ctrl+Enter to open calculator popup.");
		lbl.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));

		final CalculatorTextAdapter adapter = new CalculatorTextAdapter(txt);

		// optional: define your own decimal format (default is
		// "#,##0.##########")
		final DecimalFormat format = new DecimalFormat("#,##0.00 €");
		format.setMaximumIntegerDigits(6);

		adapter.setDecimalFormat(format);

		// optional: press SHIFT+CR to open calculator (default is '=')
		adapter.openCalculatorWhen(event -> {
			return event.keyCode == SWT.CR && event.stateMask == SWT.SHIFT;
		});

		// optional: initialize calculator properties (default is use default
		// properties)
		adapter.setCalculatorConfigurer(calculator -> {
			calculator.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_GRAY));
		});

		// optional: define your own result consumer (default is set formatted
		// value to text field)
		adapter.setResultConsumer(value -> {
			final char groupingSeparator = format.getDecimalFormatSymbols().getGroupingSeparator();

			txt.setText(format.format(value).replace(String.valueOf(groupingSeparator), ""));
			txt.setSelection(0, txt.getText().length() - 2);
		});

		// optional: define your own value initializer (default is text field
		// content)
		adapter.setValueInitializer(() -> BigDecimal.TEN);

		// initialize text widget with ten
		txt.setText(format.format(10));
		txt.setSelection(0, 5);

		shell.pack();
		shell.open();

		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
		display.dispose();
	}
}
Clone this wiki locally