Java/Swing JFC/GlassPane

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

Block mouse and key events in an application

 
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
public class Main extends JFrame {
  JPanel glass = new JPanel(new GridLayout(0, 1));
  JLabel padding = new JLabel();
  JProgressBar waiter = new JProgressBar(0, 100);

  public Main() {
    setSize(300, 300);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    JPanel controlPane = new JPanel(new GridLayout(2, 1));
    controlPane.setOpaque(false);
    controlPane.add(new JLabel("Please wait..."));
    controlPane.add(waiter);
    glass.setOpaque(false);
    glass.add(padding);
    glass.add(new JLabel());
    glass.add(controlPane);
    glass.add(new JLabel());
    glass.add(new JLabel());
    glass.setSize(new Dimension(300,300));
    setGlassPane(glass);

    JButton startB = new JButton("Start!");
    startB.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent A) {
        glass.setVisible(true);
        padding.requestFocus();
      }
    });
    Container contentPane = getContentPane();
    contentPane.add(startB, BorderLayout.SOUTH);
  }
  public static void main(String[] args) {
    Main ge = new Main();
    ge.setVisible(true);
  }
}





Demonstrate use of GlassPane

 
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/*
 * Demonstrate use of GlassPane in JWindow & friends. Buttons enable/disable it.
 * @author Eckstein et al, in the O"Reilly book "Java Swing"
 */
public class GlassExample {
  /** Construct a Splash screen with the given image */
  public static void main(String[] args) {
    JFrame f = new JFrame("GlassPane");
    final JPanel p1 = new JPanel();
    p1.add(new JLabel("GlassPane Example"));
    JButton show = new JButton("Show");
    p1.add(show);
    p1.add(new JButton("No-op"));
    f.getContentPane().add(p1);
    final JPanel glass = (JPanel) f.getGlassPane();
    glass.setVisible(true);
    glass.setLayout(new GridBagLayout());
    JButton glassButton = new JButton("Hide");
    glass.add(glassButton);
    f.setSize(150, 80);
    f.setVisible(true);
    boolean debug = false;
    if (debug) {
      System.out.println("Button is " + glassButton);
      System.out.println("GlassPane is " + glass);
    }
    // Add actions to the buttons...
    // show button (re-)shows the glass pane.
    show.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        glass.setVisible(true);
        p1.repaint();
      }
    });
    // hide button hides the Glass Pane to show what"s under.
    glassButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        glass.setVisible(false);
        p1.repaint();
      }
    });
  }
}





Paint on glass pane

 
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class Main extends JComponent {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    final JButton activate = new JButton("Show");
    frame.add(activate);
    frame.pack();
    frame.setVisible(true);
    final Main glass = new Main(frame);
    frame.setGlassPane(glass);
    activate.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        glass.setVisible(true);
      }
    });
  }
  JFrame frame;
  Point cursor;
  public Main(JFrame frame) {
    this.frame = frame;
    cursor = new Point();
    this.addMouseMotionListener(new MouseMotionAdapter() {
      public void mouseMoved(MouseEvent evt) {
        cursor = new Point(evt.getPoint());
        Main.this.repaint();
      }
    });
    this.addMouseListener(new MouseAdapter() {
      public void mouseClicked(MouseEvent evt) {
        Main.this.setVisible(false);
      }
    });
  }
  public void paint(Graphics g) {
    Container root = frame.getContentPane();
    myPaint(root, g);
  }
  private void myPaint(Component comp, Graphics g) {
    int x = comp.getX();
    int y = comp.getY();
    g.translate(x, y);
    cursor.translate(-x, -y);
    if (comp.contains(cursor)) {
      String cls_name = comp.getClass().getName();
      g.setColor(Color.black);
      g.drawString(cls_name, 0, 10);
    }
    if (comp instanceof Container) {
      Container cont = (Container) comp;
      for (int i = 0; i < cont.getComponentCount(); i++) {
        Component child = cont.getComponent(i);
        myPaint(child, g);
      }
    }
    cursor.translate(x, y);
    g.translate(-x, -y);
  }
}





Replace existing GlassPane

 
/*
 * Copyright (c) 1995 - 2008 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:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions 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 nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.SwingUtilities;
import javax.swing.event.MouseInputAdapter;
/** An application that requires no other files. */
public class GlassPaneDemo {
  static private MyGlassPane myGlassPane;
  /**
   * Create the GUI and show it. For thread safety, this method should be
   * invoked from the event-dispatching thread.
   */
  private static void createAndShowGUI() {
    // Create and set up the window.
    JFrame frame = new JFrame("GlassPaneDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Start creating and adding components.
    JCheckBox changeButton = new JCheckBox("Glass pane \"visible\"");
    changeButton.setSelected(false);
    // Set up the content pane, where the "main GUI" lives.
    Container contentPane = frame.getContentPane();
    contentPane.setLayout(new FlowLayout());
    contentPane.add(changeButton);
    contentPane.add(new JButton("Button 1"));
    contentPane.add(new JButton("Button 2"));
    // Set up the menu bar, which appears above the content pane.
    JMenuBar menuBar = new JMenuBar();
    JMenu menu = new JMenu("Menu");
    menu.add(new JMenuItem("Do nothing"));
    menuBar.add(menu);
    frame.setJMenuBar(menuBar);
    // Set up the glass pane, which appears over both menu bar
    // and content pane and is an item listener on the change
    // button.
    myGlassPane = new MyGlassPane(changeButton, menuBar, frame.getContentPane());
    changeButton.addItemListener(myGlassPane);
    frame.setGlassPane(myGlassPane);
    // Show 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();
      }
    });
  }
}
/**
 * We have to provide our own glass pane so that it can paint.
 */
class MyGlassPane extends JComponent implements ItemListener {
  Point point;
  // React to change button clicks.
  public void itemStateChanged(ItemEvent e) {
    setVisible(e.getStateChange() == ItemEvent.SELECTED);
  }
  protected void paintComponent(Graphics g) {
    if (point != null) {
      g.setColor(Color.red);
      g.fillOval(point.x - 10, point.y - 10, 20, 20);
    }
  }
  public void setPoint(Point p) {
    point = p;
  }
  public MyGlassPane(AbstractButton aButton, JMenuBar menuBar,
      Container contentPane) {
    CBListener listener = new CBListener(aButton, menuBar, this, contentPane);
    addMouseListener(listener);
    addMouseMotionListener(listener);
  }
}
/**
 * Listen for all events that our check box is likely to be interested in.
 * Redispatch them to the check box.
 */
class CBListener extends MouseInputAdapter {
  Toolkit toolkit;
  Component liveButton;
  JMenuBar menuBar;
  MyGlassPane glassPane;
  Container contentPane;
  public CBListener(Component liveButton, JMenuBar menuBar,
      MyGlassPane glassPane, Container contentPane) {
    toolkit = Toolkit.getDefaultToolkit();
    this.liveButton = liveButton;
    this.menuBar = menuBar;
    this.glassPane = glassPane;
    this.contentPane = contentPane;
  }
  public void mouseMoved(MouseEvent e) {
    redispatchMouseEvent(e, false);
  }
  public void mouseDragged(MouseEvent e) {
    redispatchMouseEvent(e, false);
  }
  public void mouseClicked(MouseEvent e) {
    redispatchMouseEvent(e, false);
  }
  public void mouseEntered(MouseEvent e) {
    redispatchMouseEvent(e, false);
  }
  public void mouseExited(MouseEvent e) {
    redispatchMouseEvent(e, false);
  }
  public void mousePressed(MouseEvent e) {
    redispatchMouseEvent(e, false);
  }
  public void mouseReleased(MouseEvent e) {
    redispatchMouseEvent(e, true);
  }
  // A basic implementation of redispatching events.
  private void redispatchMouseEvent(MouseEvent e, boolean repaint) {
    Point glassPanePoint = e.getPoint();
    Container container = contentPane;
    Point containerPoint = SwingUtilities.convertPoint(glassPane,
        glassPanePoint, contentPane);
    if (containerPoint.y < 0) { // we"re not in the content pane
      if (containerPoint.y + menuBar.getHeight() >= 0) {
        // The mouse event is over the menu bar.
        // Could handle specially.
      } else {
        // The mouse event is over non-system window
        // decorations, such as the ones provided by
        // the Java look and feel.
        // Could handle specially.
      }
    } else {
      // The mouse event is probably over the content pane.
      // Find out exactly which component it"s over.
      Component component = SwingUtilities.getDeepestComponentAt(container,
          containerPoint.x, containerPoint.y);
      if ((component != null) && (component.equals(liveButton))) {
        // Forward events over the check box.
        Point componentPoint = SwingUtilities.convertPoint(glassPane,
            glassPanePoint, component);
        component.dispatchEvent(new MouseEvent(component, e.getID(), e
            .getWhen(), e.getModifiers(), componentPoint.x, componentPoint.y, e
            .getClickCount(), e.isPopupTrigger()));
      }
    }
    // Update the glass pane if requested.
    if (repaint) {
      glassPane.setPoint(glassPanePoint);
      glassPane.repaint();
    }
  }
}





Show how a glass pane can be used to block mouse (and key!) events

 
/*
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O"Reilly 
*/
/*
This directory contains a fixed GlassPane example.  
This fixes two bugs:
  1) Key events were not supressed in the original example, they are now
  2) On 1.2 and 1.3 systems, firHtmlLabelst mouse click after removing glass pane
     would not be sent to the component under the mouse.  This was a bug
     in the way JRootPane handled the glass pane component that has been
     fixed in the 1.4 release.  FixedGlassPane.java (see below) provides
     a workaround for 1.2 and 1.3, but is still safe to use with 1.4.
The updated files are:
SwingGlassExample.java       Updated to use (and control) the new glass pane
FixedGlassPane.java    Extension of JPanel that allows for redispatching
                                      erroneous events to their rightful owners
*/
// SwingGlassExample.java
//Show how a glass pane can be used to block mouse (and key!) events.
//Updated in response to discussions with Mark Hansen at Unify.
//
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class SwingGlassExample extends JFrame {
  // We"ll use a custom glass pane rather than a generic JPanel.
  FixedGlassPane glass;
  JProgressBar waiter = new JProgressBar(0, 100);
  Timer timer;
  public SwingGlassExample() {
    super("GlassPane Demo");
    setSize(500, 300);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    // Now set up a few buttons & images for the main application
    JPanel mainPane = new JPanel();
    mainPane.setBackground(Color.white);
    JButton redB = new JButton("Red");
    JButton blueB = new JButton("Blue");
    JButton greenB = new JButton("Green");
    mainPane.add(redB);
    mainPane.add(greenB);
    mainPane.add(blueB);
    mainPane.add(new JLabel(new ImageIcon("oreilly.gif")));
    // Attach the popup debugger to the main app buttons so you
    // see the effect of making a glass pane visible
    PopupDebugger pd = new PopupDebugger(this);
    redB.addActionListener(pd);
    greenB.addActionListener(pd);
    blueB.addActionListener(pd);
    // And last but not least, our button to launch the glass pane
    JButton startB = new JButton("Start the big operation!");
    startB.addActionListener(new ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent A) {
        // manually control the 1.2/1.3 bug work-around
        glass.setNeedToRedispatch(false);
        glass.setVisible(true);
        startTimer();
      }
    });
    Container contentPane = getContentPane();
    contentPane.add(mainPane, BorderLayout.CENTER);
    contentPane.add(startB, BorderLayout.SOUTH);
    // Set up the glass pane with a little message and a progress bar...
    JPanel controlPane = new JPanel(new GridLayout(2, 1));
    controlPane.setOpaque(false);
    controlPane.add(new JLabel("Please wait..."));
    controlPane.add(waiter);
    glass = new FixedGlassPane(getJMenuBar(), getContentPane());
    glass.setLayout(new GridLayout(0, 1));
    glass.setOpaque(false);
    glass.add(new JLabel()); // padding...
    glass.add(new JLabel());
    glass.add(controlPane);
    glass.add(new JLabel());
    glass.add(new JLabel());
    setGlassPane(glass);
  }
  // A quick method to start up a 10 second timer and update the
  // progress bar
  public void startTimer() {
    if (timer == null) {
      timer = new Timer(1000, new ActionListener() {
        int progress = 0;
        public void actionPerformed(ActionEvent A) {
          progress += 10;
          waiter.setValue(progress);
          // Once we hit 100%, remove the glass pane and reset the
          // progress bar stuff
          if (progress >= 100) {
            progress = 0;
            timer.stop();
            glass.setVisible(false);
            // Again, manually control our 1.2/1.3 bug workaround
            glass.setNeedToRedispatch(true);
            waiter.setValue(0);
          }
        }
      });
    }
    if (timer.isRunning()) {
      timer.stop();
    }
    timer.start();
  }
  // A graphical debugger that pops up anytime a button is pressed
  public class PopupDebugger implements ActionListener {
    private JFrame parent;
    public PopupDebugger(JFrame f) {
      parent = f;
    }
    public void actionPerformed(ActionEvent ae) {
      JOptionPane.showMessageDialog(parent, ae.getActionCommand());
    }
  }
  public static void main(String[] args) {
    SwingGlassExample ge = new SwingGlassExample();
    ge.setVisible(true);
  }
}
// Based in part on code from the Java Tutorial for glass panes (java.sun.ru).
// This version handles both mouse events and focus events.  The focus is
// held on the panel so that key events are also effectively ignored.  (But
// a KeyListener could still be attached by the program activating this pane.)
//

class FixedGlassPane extends JPanel implements MouseListener,
    MouseMotionListener, FocusListener {
  // helpers for redispatch logic
  Toolkit toolkit;
  JMenuBar menuBar;
  Container contentPane;
  boolean inDrag = false;
  // trigger for redispatching (allows external control)
  boolean needToRedispatch = false;
  public FixedGlassPane(JMenuBar mb, Container cp) {
    toolkit = Toolkit.getDefaultToolkit();
    menuBar = mb;
    contentPane = cp;
    addMouseListener(this);
    addMouseMotionListener(this);
    addFocusListener(this);
  }
  public void setVisible(boolean v) {
    // Make sure we grab the focus so that key events don"t go astray.
    if (v)
      requestFocus();
    super.setVisible(v);
  }
  // Once we have focus, keep it if we"re visible
  public void focusLost(FocusEvent fe) {
    if (isVisible())
      requestFocus();
  }
  public void focusGained(FocusEvent fe) {
  }
  // We only need to redispatch if we"re not visible, but having full control
  // over this might prove handy.
  public void setNeedToRedispatch(boolean need) {
    needToRedispatch = need;
  }
  /*
   * (Based on code from the Java Tutorial) We must forward at least the mouse
   * drags that started with mouse presses over the check box. Otherwise, when
   * the user presses the check box then drags off, the check box isn"t
   * disarmed -- it keeps its dark gray background or whatever its L&F uses to
   * indicate that the button is currently being pressed.
   */
  public void mouseDragged(MouseEvent e) {
    if (needToRedispatch)
      redispatchMouseEvent(e);
  }
  public void mouseMoved(MouseEvent e) {
    if (needToRedispatch)
      redispatchMouseEvent(e);
  }
  public void mouseClicked(MouseEvent e) {
    if (needToRedispatch)
      redispatchMouseEvent(e);
  }
  public void mouseEntered(MouseEvent e) {
    if (needToRedispatch)
      redispatchMouseEvent(e);
  }
  public void mouseExited(MouseEvent e) {
    if (needToRedispatch)
      redispatchMouseEvent(e);
  }
  public void mousePressed(MouseEvent e) {
    if (needToRedispatch)
      redispatchMouseEvent(e);
  }
  public void mouseReleased(MouseEvent e) {
    if (needToRedispatch) {
      redispatchMouseEvent(e);
      inDrag = false;
    }
  }
  private void redispatchMouseEvent(MouseEvent e) {
    boolean inButton = false;
    boolean inMenuBar = false;
    Point glassPanePoint = e.getPoint();
    Component component = null;
    Container container = contentPane;
    Point containerPoint = SwingUtilities.convertPoint(this,
        glassPanePoint, contentPane);
    int eventID = e.getID();
    if (containerPoint.y < 0) {
      inMenuBar = true;
      container = menuBar;
      containerPoint = SwingUtilities.convertPoint(this, glassPanePoint,
          menuBar);
      testForDrag(eventID);
    }
    //XXX: If the event is from a component in a popped-up menu,
    //XXX: then the container should probably be the menu"s
    //XXX: JPopupMenu, and containerPoint should be adjusted
    //XXX: accordingly.
    component = SwingUtilities.getDeepestComponentAt(container,
        containerPoint.x, containerPoint.y);
    if (component == null) {
      return;
    } else {
      inButton = true;
      testForDrag(eventID);
    }
    if (inMenuBar || inButton || inDrag) {
      Point componentPoint = SwingUtilities.convertPoint(this,
          glassPanePoint, component);
      component.dispatchEvent(new MouseEvent(component, eventID, e
          .getWhen(), e.getModifiers(), componentPoint.x,
          componentPoint.y, e.getClickCount(), e.isPopupTrigger()));
    }
  }
  private void testForDrag(int eventID) {
    if (eventID == MouseEvent.MOUSE_PRESSED) {
      inDrag = true;
    }
  }
}