Focus Event Demo : Various Event Listener « Event « Java






Focus Event Demo

Focus Event Demo
  
/* From http://java.sun.com/docs/books/tutorial/index.html */
/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
/*
 * FocusEventDemo.java is a 1.4 example that requires no other files.
 */

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class FocusEventDemo extends JPanel implements FocusListener {
  final static String newline = "\n";

  JTextArea display;

  public FocusEventDemo() {
    super(new GridBagLayout());
    GridBagLayout gridbag = (GridBagLayout) getLayout();
    GridBagConstraints c = new GridBagConstraints();

    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 1.0; //Make column as wide as possible.
    JTextField textField = new JTextField("A TextField");
    textField.setMargin(new Insets(0, 2, 0, 2));
    textField.addFocusListener(this);
    gridbag.setConstraints(textField, c);
    add(textField);

    c.weightx = 0.1; //Widen every other column a bit, when possible.
    c.fill = GridBagConstraints.NONE;
    JLabel label = new JLabel("A Label");
    label.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
    label.addFocusListener(this);
    gridbag.setConstraints(label, c);
    add(label);

    String comboPrefix = "ComboBox Item #";
    final int numItems = 15;
    Vector vector = new Vector(numItems);
    for (int i = 0; i < numItems; i++) {
      vector.addElement(comboPrefix + i);
    }
    JComboBox comboBox = new JComboBox(vector);
    comboBox.addFocusListener(this);
    gridbag.setConstraints(comboBox, c);
    add(comboBox);

    c.gridwidth = GridBagConstraints.REMAINDER;
    JButton button = new JButton("A Button");
    button.addFocusListener(this);
    gridbag.setConstraints(button, c);
    add(button);

    c.weightx = 0.0;
    c.weighty = 0.1;
    c.fill = GridBagConstraints.BOTH;
    String listPrefix = "List Item #";
    Vector listVector = new Vector(numItems);
    for (int i = 0; i < numItems; i++) {
      listVector.addElement(listPrefix + i);
    }
    JList list = new JList(listVector);
    list.setSelectedIndex(1); //It's easier to see the focus change
    //if an item is selected.
    list.addFocusListener(this);
    JScrollPane listScrollPane = new JScrollPane(list);
    //We want to prevent the list's scroll bars
    //from getting the focus - even with the keyboard.
    //Note that in general we prefer setRequestFocusable
    //over setFocusable for reasons of accessibility,
    //but this is to work around bug #4866958.
    listScrollPane.getVerticalScrollBar().setFocusable(false);
    listScrollPane.getHorizontalScrollBar().setFocusable(false);
    gridbag.setConstraints(listScrollPane, c);
    add(listScrollPane);

    c.weighty = 1.0; //Make this row as tall as possible.
    c.gridheight = GridBagConstraints.REMAINDER;
    //Set up the area that reports focus-gained and focus-lost events.
    display = new JTextArea();
    display.setEditable(false);
    //The method setRequestFocusEnabled prevents a
    //component from being clickable, but it can still
    //get the focus through the keyboard - this ensures
    //user accessibility.
    display.setRequestFocusEnabled(false);
    display.addFocusListener(this);
    JScrollPane displayScrollPane = new JScrollPane(display);

    //Work around for bug #4866958.
    displayScrollPane.getHorizontalScrollBar().setFocusable(false);
    displayScrollPane.getVerticalScrollBar().setFocusable(false);
    gridbag.setConstraints(displayScrollPane, c);
    add(displayScrollPane);

    setPreferredSize(new Dimension(450, 450));
    setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
  }

  public void focusGained(FocusEvent e) {
    displayMessage("Focus gained", e);
  }

  public void focusLost(FocusEvent e) {
    displayMessage("Focus lost", e);
  }

  void displayMessage(String prefix, FocusEvent e) {
    display.append(prefix
        + (e.isTemporary() ? " (temporary):" : ":")
        + e.getComponent().getClass().getName()
        + "; Opposite component: "
        + (e.getOppositeComponent() != null ? e.getOppositeComponent()
            .getClass().getName() : "null") + newline);
    display.setCaretPosition(display.getDocument().getLength());
  }

  /**
   * Create the GUI and show it. For thread safety, this method should be
   * invoked from the event-dispatching thread.
   */
  private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);

    //Create and set up the window.
    JFrame frame = new JFrame("FocusEventDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Create and set up the content pane.
    JComponent newContentPane = new FocusEventDemo();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);

    //Display the window.
    frame.pack();
    frame.setVisible(true);
  }

  public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI();
      }
    });
  }
}
           
         
    
  








Related examples in the same category

1.Display the addXXXListener methods of any Swing classDisplay the addXXXListener methods of any Swing class
2.Show events as they happenShow events as they happen
3.A demonstration of the ChangeEvents generated by the BoundedRangeModelA demonstration of the ChangeEvents generated by the BoundedRangeModel
4.An application that shows the Action class in, well, actionAn application that shows the Action class in, well, action
5.Showing how to add Actions for KeyStrokesShowing how to add Actions for KeyStrokes
6.SketchSketch
7.EventListenerList enabled Secret LabelEventListenerList enabled Secret Label
8.TextAction exampleTextAction example
9.StateChange ListenerStateChange Listener
10.CheckBox Item ListenerCheckBox Item Listener
11.AncestorListener DemoAncestorListener Demo
12.KeyStroke SampleKeyStroke Sample
13.Focus Next Component SampleFocus Next Component Sample
14.PropertyChangeListener SamplePropertyChangeListener Sample
15.Timer SampleTimer Sample
16.KeyListener, ActionListener Demo 1KeyListener, ActionListener Demo 1
17.KeyListener, ActionListener Demo 2KeyListener, ActionListener Demo 2
18.Action, Mouse FocusAction, Mouse Focus
19.Swing Action DemoSwing Action Demo
20.Load Save ActionLoad Save Action
21.Demonstrating the WindowListener with a WindowAdapterDemonstrating the WindowListener with a WindowAdapter
22.Demonstrating the ActionListenerDemonstrating the ActionListener
23.Demonstrating the AdjustmentListenerDemonstrating the AdjustmentListener
24.Demonstrating the AncestorListener
25.Demonstrating the ComponentListenerDemonstrating the ComponentListener
26.A ComponentAdapter.
27.JAR Archives: Pack Progress Monitor
28.A position of a window on the screen.
29.Using ComponentListener to catch the JFrame Maximization event
30.Demonstrating the ContainerListenerDemonstrating the ContainerListener
31.Demonstrating the FocusListenerDemonstrating the FocusListener
32.Demonstrating the HyperlinkListenerDemonstrating the HyperlinkListener
33.Demonstrating the InternalFrameListenerDemonstrating the InternalFrameListener
34.Demonstrating the ItemListenerDemonstrating the ItemListener
35.Implement a graphical list selection monitorImplement a graphical list selection monitor
36.ItemListener for JRadioButton
37.Demonstrating the KeyListenerDemonstrating the KeyListener
38.Demonstrating the MenuListenerDemonstrating the MenuListener
39.Demonstrating the MouseListener and MouseMotionListenerDemonstrating the MouseListener and MouseMotionListener
40.Demonstrating the MouseWheelListenerDemonstrating the MouseWheelListener
41.Demonstrating the PopupMenuListenerDemonstrating the PopupMenuListener
42.Demonstrating the WindowListener
43.implements VetoableChangeListener to block focus change events
44.Responding to KeystrokesResponding to Keystrokes
45.Container Event DemoContainer Event Demo
46.Component Event DemoComponent Event Demo
47.Window Event DemoWindow Event Demo
48.Handle a window closing event
49.Installs/resets a ComponentListener to resize the given window to minWidth/Height if needed