Show Font Dialog and Color Dialog

In this section, you will learn creating color dialog box and font dialog in Java.

Show Font Dialog and Color Dialog

Show Font Dialog and Color Dialog

     

In this section, you will learn creating color dialog box and font dialog in Java.

SWT allows to show Color Dialog and Font Dialog by providing the classes FontDialog and ColorDialog. The FontDialog class provides the font dialog and allow the user to select a font from the available fonts. The ColorDialog class provides the color dialog and allows the user to select the color from the set of available colors.

The method dialog.open() makes the font dialog and color dialog visible. The method setFontData() sets the fontData describing the font to be selected by default in the dialog. The method text.setFont() sets the selected font. The method setForeground() sets the foreground color. The method setRGB() sets the selected color.

 Here is the code of ShowDialogExample.java

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.*;

public class ShowDialogExample {
  Display display;
  Shell shell;

  ShowDialogExample() {
  display = new Display();
  shell = new Shell(display);
  shell.setSize(200150);
  shell.setText("A FontDialog Example");
  
  shell.setLayout(new FillLayout(SWT.VERTICAL));
  final Text text = new Text(shell, SWT.BORDER | SWT.MULTI);
  text.setText("Change Font and Color");
  final Button button1 = new Button(shell, SWT.PUSH | SWT.HORIZONTAL);
  button1.setText("Font Dialog");
  button1.addSelectionListener(new SelectionAdapter() {
  public void widgetSelected(SelectionEvent e) {
  FontDialog dialog = new FontDialog(shell, SWT.NONE);
  dialog.setRGB(new RGB(00255));
  FontData defaultFont = new FontData("Arial"15, SWT.BOLD);
  dialog.setFontData(defaultFont);
  FontData newFont = dialog.open();
  if (newFont == null)
  return;
  text.setFont(new Font(display, newFont));
 text.setForeground(new Color(display, dialog.getRGB()));
  }
  });
  final Button button2 = new Button(shell, SWT.PUSH | SWT.HORIZONTAL);
  button2.setText("Color Dialog");
  button2.addSelectionListener(new SelectionAdapter() {
  public void widgetSelected(SelectionEvent e) {
  ColorDialog dialog = new ColorDialog(shell);
  dialog.setRGB(new RGB(255255255));
  RGB newColor = dialog.open();
  if (newColor == null) {
  return;
  }
  text.setBackground(new Color(display, newColor));
  }
  });
  shell.open();
  while (!shell.isDisposed()) {
  if (!display.readAndDispatch())
  display.sleep();
  }
  display.dispose();
  }
  public static void main(String[] argv) {
  new ShowDialogExample();
  }
}

Output will be displayed as:

On clicking Font Dialog button, the font dialog is displayed:

On clicking Color Dialog button, the color dialog is displayed:

Download Source Code