Java/SWT JFace Eclipse/Event — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 05:55, 1 июня 2010

Demonstrates ControlListeners

//Send questions, comments, bug reports, etc. to the authors:
//Rob Warner (rwarner@interspatial.ru)
//Robert Harris (rbrt_harris@yahoo.ru)
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
/**
 * This class demonstrates ControlListeners
 */
public class ControlListenerExample {
  /**
   * Runs the application
   */
  public void run() {
    Display display = new Display();
    Shell shell = new Shell(display);
    Image image = new Image(display, "jexp.gif");
    createContents(shell, image);
    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) {
        display.sleep();
      }
    }
    if (image != null) image.dispose();
    display.dispose();
  }
  /**
   * Creates the main window"s contents
   * 
   * @param shell the main window
   * @param image the image
   */
  private void createContents(Shell shell, Image image) {
    shell.setLayout(new GridLayout());
    // Create a label to hold the image
    Label label = new Label(shell, SWT.NONE);
    label.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
    label.setImage(image);
    shell.setData(label);
    // Add the listener
    shell.addControlListener(new ControlAdapter() {
      public void controlResized(ControlEvent event) {
        // Get the event source (the shell)
        Shell shell = (Shell) event.getSource();
        // Get the source"s data (the label)
        Label label = (Label) shell.getData();
        // Determine how big the shell should be to fit the image
        Rectangle rect = shell.getClientArea();
        ImageData data = label.getImage().getImageData();
        // If the shell is too small, hide the image
        if (rect.width < data.width || rect.height < data.height) {
          shell.setText("Too small.");
          label.setText("I"m melting!");
        } else {
          // He fits!
          shell.setText("Happy Guy Fits!");
          label.setImage(label.getImage());
        }
      }
    });
  }
  /**
   * Application entry point
   * 
   * @param args the command line arguments
   */
  public static void main(String[] args) {
    new ControlListenerExample().run();
  }
}





Demonstrates FocusListener

//Send questions, comments, bug reports, etc. to the authors:
//Rob Warner (rwarner@interspatial.ru)
//Robert Harris (rbrt_harris@yahoo.ru)
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
/**
 * This class demonstrates FocusListener
 */
public class FocusListenerExample {
  /**
   * The application entry point
   * 
   * @param args the command line arguments
   */
  public static void main(String[] args) {
    // Create the shell
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new GridLayout(3, true));
    shell.setText("One Potato, Two Potato");
    // Create the focus listener
    FocusListener listener = new FocusListener() {
      public void focusGained(FocusEvent event) {
        Button button = (Button) event.getSource();
        button.setText("I"m It!");
      }
      public void focusLost(FocusEvent event) {
        Button button = (Button) event.getSource();
        button.setText("Pick Me!");
      }
    };
    // Create the buttons and add the listener to each one
    for (int i = 0; i < 6; i++) {
      Button button = new Button(shell, SWT.PUSH);
      button.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
      button.setText("Pick Me!");
      button.addFocusListener(listener);
    }
    // Display the window
    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) {
        display.sleep();
      }
    }
    display.dispose();
  }
}





Demonstrates LineBackgroundListeners

//Send questions, comments, bug reports, etc. to the authors:
//Rob Warner (rwarner@interspatial.ru)
//Robert Harris (rbrt_harris@yahoo.ru)

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
/**
 * This class demonstrates LineBackgroundListeners
 */
public class LineBackgroundListenerTest {
  // The color to use for backgrounds
  Color red;
  /**
   * Runs the application
   */
  public void run() {
    Display display = new Display();
    red = display.getSystemColor(SWT.COLOR_RED);
    Shell shell = new Shell(display);
    createContents(shell);
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) {
        display.sleep();
      }
    }
    display.dispose();
  }
  /**
   * Creates the main window"s contents
   * 
   * @param shell the main window
   */
  private void createContents(Shell shell) {
    shell.setLayout(new FillLayout());
    StyledText styledText = new StyledText(shell, SWT.BORDER);
    // Add the line background listener
    styledText.addLineBackgroundListener(new LineBackgroundListener() {
      public void lineGetBackground(LineBackgroundEvent event) {
        if (event.lineText.indexOf("SWT") > -1) {
          event.lineBackground = red;
        }
      }
    });
  }
  /**
   * The application entry point
   * 
   * @param args the command line arguments
   */
  public static void main(String[] args) {
    new LineBackgroundListenerTest().run();
  }
}





Demonstrates mouse events

//Send questions, comments, bug reports, etc. to the authors:
//Rob Warner (rwarner@interspatial.ru)
//Robert Harris (rbrt_harris@yahoo.ru)
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
/**
 * This class demonstrates mouse events
 */
public class MouseEventExample implements MouseListener, MouseMoveListener,
    MouseTrackListener {
  // The label to hold the messages from mouse events
  Label myLabel = null;
  /**
   * MouseEventExample constructor
   * 
   * @param shell the shell
   */
  public MouseEventExample(Shell shell) {
    myLabel = new Label(shell, SWT.BORDER);
    myLabel.setText("I ain"t afraid of any old mouse");
    shell.addMouseListener(this);
    shell.addMouseMoveListener(this);
    shell.addMouseTrackListener(this);
  }
  /**
   * The application entry point
   * 
   * @param args the command line arguments
   */
  public static void main(String[] args) {
    // Create the window
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new GridLayout());
    shell.setSize(450, 200);
    shell.setText("Mouse Event Example");
    // Create the listener
    MouseEventExample myMouseEventExample = new MouseEventExample(shell);
    // Display the window
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) {
        display.sleep();
      }
    }
    display.dispose();
  }
  /**
   * Called when user double-clicks the mouse
   */
  public void mouseDoubleClick(MouseEvent e) {
    myLabel.setText("Double Click " + e.button + " at: " + e.x + "," + e.y);
  }
  /**
   * Called when user clicks the mouse
   */
  public void mouseDown(MouseEvent e) {
    myLabel.setText("Button " + e.button + " Down at: " + e.x + "," + e.y);
  }
  /**
   * Called when user releases the mouse after clicking
   */
  public void mouseUp(MouseEvent e) {
    myLabel.setText("Button " + e.button + " Up at: " + e.x + "," + e.y);
  }
  /**
   * Called when user moves the mouse
   */
  public void mouseMove(MouseEvent e) {
    myLabel.setText("Mouse Move at: " + e.x + "," + e.y);
  }
  /**
   * Called when user enters the shell with the mouse
   */
  public void mouseEnter(MouseEvent e) {
    myLabel.setText("Mouse Enter at: " + e.x + "," + e.y);
  }
  /**
   * Called when user exits the shell with the mouse
   */
  public void mouseExit(MouseEvent e) {
    myLabel.setText("Mouse Exit at: " + e.x + "," + e.y);
  }
  /**
   * Called when user hovers the mouse
   */
  public void mouseHover(MouseEvent e) {
    myLabel.setText("Mouse Hover at: " + e.x + "," + e.y);
  }
}





Demonstrates various listeners

//Send questions, comments, bug reports, etc. to the authors:
//Rob Warner (rwarner@interspatial.ru)
//Robert Harris (rbrt_harris@yahoo.ru)
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
/**
 * This class demonstrates various listeners
 */
public class MultipleListenersExample implements HelpListener, VerifyListener,
    ModifyListener {
  // Constants used for conversions
  private static final double FIVE_NINTHS = 5.0 / 9.0;
  private static final double NINE_FIFTHS = 9.0 / 5.0;
  // Widgets used in the window
  private Text fahrenheit;
  private Text celsius;
  private Label help;
  /**
   * Runs the application
   */
  public void run() {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Temperatures");
    createContents(shell);
    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) {
        display.sleep();
      }
    }
    display.dispose();
  }
  /**
   * Create the main window"s contents
   * @param shell the main window
   */
  private void createContents(Shell shell) {
    shell.setLayout(new GridLayout(3, true));
    // Create the label and input box for Fahrenheit
    new Label(shell, SWT.LEFT).setText("Fahrenheit:");
    fahrenheit = new Text(shell, SWT.BORDER);
    GridData data = new GridData(GridData.FILL_HORIZONTAL);
    data.horizontalSpan = 2;
    fahrenheit.setLayoutData(data);
    // Set the context-sensitive help
    fahrenheit.setData("Type a temperature in Fahrenheit");
    // Add the listeners
    fahrenheit.addHelpListener(this);
    fahrenheit.addVerifyListener(this);
    fahrenheit.addModifyListener(this);
    // Create the label and input box for Celsius
    new Label(shell, SWT.LEFT).setText("Celsius:");
    celsius = new Text(shell, SWT.BORDER);
    data = new GridData(GridData.FILL_HORIZONTAL);
    data.horizontalSpan = 2;
    celsius.setLayoutData(data);
    // Set the context-sensitive help
    celsius.setData("Type a temperature in Celsius");
    // Add the listeners
    celsius.addHelpListener(this);
    celsius.addVerifyListener(this);
    celsius.addModifyListener(this);
    // Create the area for help
    help = new Label(shell, SWT.LEFT | SWT.BORDER);
    data = new GridData(GridData.FILL_HORIZONTAL);
    data.horizontalSpan = 3;
    help.setLayoutData(data);
  }
  /**
   * Called when user requests help
   */
  public void helpRequested(HelpEvent event) {
    // Get the help text from the widget and set it into the help label
    help.setText((String) event.widget.getData());
  }
  /**
   * Called when the user types into a text box, but before the text box gets
   * what the user typed
   */
  public void verifyText(VerifyEvent event) {
    // Assume we don"t allow it
    event.doit = false;
    // Get the character typed
    char myChar = event.character;
    String text = ((Text) event.widget).getText();
    // Allow "-" if first character
    if (myChar == "-" && text.length() == 0) event.doit = true;
    // Allow 0-9
    if (Character.isDigit(myChar)) event.doit = true;
    // Allow backspace
    if (myChar == "\b") event.doit = true;
  }
  /**
   * Called when the user modifies the text in a text box
   */
  public void modifyText(ModifyEvent event) {
    // Remove all the listeners, so we don"t enter any infinite loops
    celsius.removeVerifyListener(this);
    celsius.removeModifyListener(this);
    fahrenheit.removeVerifyListener(this);
    fahrenheit.removeModifyListener(this);
    // Get the widget whose text was modified
    Text text = (Text) event.widget;
    try {
      // Get the modified text
      int temp = Integer.parseInt(text.getText());
      // If they modified fahrenheit, convert to Celsius
      if (text == fahrenheit) {
        celsius.setText(String.valueOf((int) (FIVE_NINTHS * (temp - 32))));
      } else {
        // Convert to fahrenheit
        fahrenheit.setText(String.valueOf((int) (NINE_FIFTHS * temp + 32)));
      }
    } catch (NumberFormatException e) { /* Ignore */ }
    // Add the listeners back
    celsius.addVerifyListener(this);
    celsius.addModifyListener(this);
    fahrenheit.addVerifyListener(this);
    fahrenheit.addModifyListener(this);
  }
  /**
   * The application entry point
   * @param args the command line arguments
   */
  public static void main(String[] args) {
    new MultipleListenersExample().run();
  }
}





Key Listener Example

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.rubo;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class KeyListenerExample {
  Display d;
  Shell s;
  KeyListenerExample() {
    d = new Display();
    s = new Shell(d);
    s.setSize(250, 200);
    
    s.setText("A KeyListener Example");
    s.setLayout(new RowLayout());
    final Combo c = new Combo(s, SWT.DROP_DOWN | SWT.BORDER);
    c.add("Lions");
    c.add("Tigers");
    c.add("Bears");
    c.add("Oh My!");
    c.addKeyListener(new KeyListener() {
      String selectedItem = "";
      public void keyPressed(KeyEvent e) {
        if (c.getText().length() > 0) {
          return;
        }
        String key = Character.toString(e.character);
        String[] items = c.getItems();
        for (int i = 0; i < items.length; i++) {
          if (items[i].toLowerCase().startsWith(key.toLowerCase())) {
            c.select(i);
            selectedItem = items[i];
            return;
          }
        }
      }
      public void keyReleased(KeyEvent e) {
        if (selectedItem.length() > 0)
          c.setText(selectedItem);
        selectedItem = "";
      }
    });
    s.open();
    while (!s.isDisposed()) {
      if (!d.readAndDispatch())
        d.sleep();
    }
    d.dispose();
  }
  public static void main() {
    new KeyListenerExample();
  }
}





ModifyEvent: Temperature Converter JFace

/******************************************************************************
 * Copyright (c) 1998, 2004 Jackwind Li Guojie
 * All right reserved. 
 * 
 * Created on Jan 16, 2004 8:05:36 PM by JACK
 * $Id$
 * 
 * visit: http://www.asprise.ru/swt
 *****************************************************************************/
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.ruposite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
public class TemperatureConverterJFace extends ApplicationWindow {
  Label fahrenheitLabel;
  Label celsiusLabel;
  Text fahrenheitValue;
  Text celsiusValue;  
  
  public TemperatureConverterJFace() {
    super(null);
    
    addStatusLine();
  }
  /* (non-Javadoc)
   * @see org.eclipse.jface.window.Window#createContents(org.eclipse.swt.widgets.ruposite)
   */
  protected Control createContents(Composite parent) {
    getShell().setText("JFace Temperature Converter");
    
    Composite converterComposite = new Composite(parent, SWT.NULL);
    
    converterComposite.setLayout(new GridLayout(4, false));
    fahrenheitLabel = new Label(converterComposite, SWT.NULL);
    fahrenheitLabel.setText("Fahrenheit: ");
    fahrenheitValue = new Text(converterComposite, SWT.SINGLE | SWT.BORDER);
    celsiusLabel = new Label(converterComposite, SWT.NULL);
    celsiusLabel.setText("Celsius: ");
    celsiusValue = new Text(converterComposite, SWT.SINGLE | SWT.BORDER);
    ModifyListener listener = new ModifyListener() {
      public void modifyText(ModifyEvent e) {
        valueChanged((Text) e.widget);
      }
    };
    fahrenheitValue.addModifyListener(listener);
    celsiusValue.addModifyListener(listener);
  
    return converterComposite;
  }
  /**
   * Performs conversion when one of the text fields changes.
   * 
   * @param text
   *            the event source
   */
  public void valueChanged(Text text) {
    if (!text.isFocusControl())
      return;
    if (text == fahrenheitValue) {
      try {
        double fValue = Double.parseDouble(text.getText());
        double cValue = (fValue - 32) / 1.8;
        celsiusValue.setText(Double.toString(cValue));
        System.out.println("F -> C: " + cValue);
        setStatus("Conversion performed successfully.");
      } catch (NumberFormatException e) {
        celsiusValue.setText("");
        setStatus("Invalid number format: " + text.getText());
      }
    } else {
      try {
        double cValue = Double.parseDouble(text.getText());
        double fValue = cValue * 1.8 + 32;
        fahrenheitValue.setText(Double.toString(fValue));
        System.out.println("C -> F: " + fValue);
        setStatus("Conversion performed successfully.");
      } catch (NumberFormatException e) {
        fahrenheitValue.setText("");
        setStatus("Invalid number format: " + text.getText());
      }
    }
  }
  
  public static void main(String[] args) {
    TemperatureConverterJFace converter = new TemperatureConverterJFace();
    converter.setBlockOnOpen(true);
    converter.open();
    Display.getCurrent().dispose();
  }
  
}





Mouse Event Listener

/******************************************************************************
 * Copyright (c) 1998, 2004 Jackwind Li Guojie
 * All right reserved. 
 * 
 * Created on Oct 27, 2003 10:38:29 PM by JACK
 * $Id: ListenerTest.java,v 1.1 2003/12/22 12:07:54 jackwind Exp $
 * 
 * visit: http://www.asprise.ru/swt
 *****************************************************************************/
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
public class ListenerTest {
  public ListenerTest() {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Left click your mouse");
    shell.setSize(200, 100);
    shell.open();    
    
    shell.addListener(SWT.MouseDown, new SimpleListener("Shell mouse down listener"));
    
    display.addFilter(SWT.MouseDown, new SimpleListener("Display mouse down Listener"));
    display.addFilter(SWT.MouseUp, new SimpleListener("Display mouse up Listener"));
    
    while(! shell.isDisposed()) {
      if(! display.readAndDispatch()) {// If no more entries in event queue
        display.sleep();
      }
    }
    
    display.dispose();
  }
  
  class SimpleListener implements Listener{
    String name;
    
    public SimpleListener(String name) {
      this.name = name;
    }
    public void handleEvent(Event e) {
      System.out.println("Event: [" + EventUtil.getEventName(e.type) + "] from " + name + ". \tCurrent Time (in ms):  " + System.currentTimeMillis());
    }
  }
  public static void main(String[] args) {
    new ListenerTest();
  }
}





SelectionListener and DisposeListener

//Send questions, comments, bug reports, etc. to the authors:
//Rob Warner (rwarner@interspatial.ru)
//Robert Harris (rbrt_harris@yahoo.ru)
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
/**
 * This class demonstrates SelectionListener and DisposeListener
 */
public class DisposeListenerExample {
  /**
   * The application entry point
   * 
   * @param args the command line arguments
   */
  public static void main(String[] args) {
    Display display = new Display();
    // Create the main window
    Shell mainShell = new Shell(display);
    mainShell.setLayout(new FillLayout());
    mainShell.setText("Big Brother");
    final Label mainMessage = new Label(mainShell, SWT.LEFT);
    mainMessage.setText("Don"t even think about it");
    // Create the child shell and the dispose listener
    final Shell childShell = new Shell(mainShell);
    childShell.addDisposeListener(new DisposeListener() {
      public void widgetDisposed(DisposeEvent event) {
        // When the child shell is disposed, change the message on the main shell
        mainMessage.setText("Gotcha");
      }
    });
    childShell.setLayout(new FillLayout());
    childShell.setText("little brother");
    // Put a message on the child shell
    new Label(childShell, SWT.LEFT)
        .setText("If you dispose me, my big brother"s gonna get you!");
    // Add a button and a listener to the child shell
    Button button = new Button(childShell, SWT.PUSH);
    button.setText("Close Me!");
    button.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent event) {
        // When the button is pressed, close the child shell
        childShell.close();
      }
    });
    // Open the shells
    mainShell.open();
    childShell.open();
    while (!mainShell.isDisposed()) {
      if (!display.readAndDispatch()) {
        display.sleep();
      }
    }
    display.dispose();
  }
}





Utility class for event handling

/******************************************************************************
 * Copyright (c) 1998, 2004 Jackwind Li Guojie
 * All right reserved. 
 * 
 * Created on Oct 28, 2003 12:29:41 AM by JACK
 * $Id: EventUtil.java,v 1.1 2003/12/22 12:07:54 jackwind Exp $
 * 
 * visit: http://www.asprise.ru/swt
 *****************************************************************************/
import org.eclipse.swt.SWT;
/**
 * Utility class for event handling.
 */
public class EventUtil {
  
  public static String getEventName(int eventType) {
    switch(eventType) {
      case SWT.None:
        return "null";
      case SWT.KeyDown:
        return "key down";
      case SWT.KeyUp:
        return "key up";
      case SWT.MouseDown:
        return "mouse down";
      case SWT.MouseUp:
        return "mouse up";
      case SWT.MouseMove:
        return "mouse move";
      case SWT.MouseEnter:
        return "mouse enter";
      case SWT.MouseExit:
        return "mouse exit";
      case SWT.MouseDoubleClick:
        return "mouse double click";
      case SWT.Paint:
        return "paint";
      case SWT.Move:
        return "move";
      case SWT.Resize:
        return "resize";
      case SWT.Dispose:
        return "dispose";
      case SWT.Selection:
        return "selection";
      case SWT.DefaultSelection:
        return "default selection";
      case SWT.FocusIn:
        return "focus in";
      case SWT.FocusOut:
        return "focus out";
      case SWT.Expand:
        return "expand";
      case SWT.Collapse:
        return "collapse";
      case SWT.Iconify:
        return "iconify";
      case SWT.Deiconify:
        return "deiconify";
      case SWT.Close:
        return "close";
      case SWT.Show:
        return "show";
      case SWT.Hide:
        return "hide";
      case SWT.Modify:
        return "modify";
      case SWT.Verify:
        return "verify";
      case SWT.Activate:
        return "activate";
      case SWT.Deactivate:
        return "deactivate";
      case SWT.Help:
        return "help";
      case SWT.DragDetect:
        return "drag detect";
      case SWT.Arm:
        return "arm";
      case SWT.Traverse:
        return "traverse";
      case SWT.MouseHover:
        return "mouse hover";
      case SWT.HardKeyDown:
        return "hard key down";
      case SWT.HardKeyUp:
        return "hard key up";
      case SWT.MenuDetect:
        return "menu detect";
    }
    
    return "unkown ???";
  }
  public static void main(String[] args) {
  }
}