Skip to content

FontButton

greipadmin edited this page Dec 29, 2018 · 7 revisions

Introduction

The FontButton widget allow the user to select a font from all available fonts in the system.

Constructor

  • FontButton(Composite parent, int style)
    • parent a widget which will be the parent of the new widget.
    • style the style of widget to construct.

Methods

  • FontData getFontData() returns the selected font data object or null if no font is selected.
  • void setFontData(final FontData fontData) sets the initial font data. If no font data is set the system font is used.
  • RGB getFontColor() gets the selected font color or null if no font is selected or no color chooser factory is set.
  • void setFontColor(final RGB fontColor) sets the initial font color. The font color is only used when a color chooser factory is defined.
  • void setColorChooserFactory(final IColorChooserFactory factory) sets the factory for creating the color chooser.

Example

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

  // configure the shell
  shell.setLayout(new GridLayout());
  shell.setText("Greip - FontButton Example");
  shell.setSize(450, 300);

  // create color and font registry
  final FontRegistry fontRegistry = new FontRegistry(display, true);
  final ColorRegistry colorRegistry = new ColorRegistry(display, true);

  // create the font button
  final FontButton button = new FontButton(shell, SWT.NONE);
  button.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false));
  button.setText("  Select Font...  ");

  // create a label to display the selected font
  final Label lblFontName = new Label(shell, SWT.CENTER);
  lblFontName.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
  lblFontName.setBackground(display.getSystemColor(SWT.COLOR_WHITE));

  // sets the initial font
  button.setFontData(lblFontName.getFont().getFontData()[0]);

  // define color chooser factory and initial color (optional)
  button.setColorChooserFactory(new ColorChooserHSB.Factory(ColorResolution.Maximal, true, true));
  button.setFontColor(lblFontName.getForeground().getRGB());

  // add selection listener
  button.addListener(SWT.Selection, e -> {
    // get selected font and color
    final FontData fd = button.getFontData();
    final RGB rgb = button.getFontColor();

    // apply the selected font
    fontRegistry.put(fd.toString(), new FontData[] { fd });
    lblFontName.setFont(fontRegistry.get(fd.toString()));
    lblFontName.setText(fd.getName());

    // apply the selected color
    colorRegistry.put(rgb.toString(), rgb);
    lblFontName.setForeground(colorRegistry.get(rgb.toString()));
  });

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