Java/Swing JFC/Container

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

Container Event Demo

   <source lang="java">
 

/* From http://java.sun.ru/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.
*/

/*

* ContainerEventDemo.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.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ContainerEvent; import java.awt.event.ContainerListener; import java.util.Vector; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class ContainerEventDemo extends JPanel implements ContainerListener,

   ActionListener {
 JTextArea display;
 JPanel buttonPanel;
 JButton addButton, removeButton, clearButton;
 Vector buttonList;
 static final String ADD = "add";
 static final String REMOVE = "remove";
 static final String CLEAR = "clear";
 static final String newline = "\n";
 public ContainerEventDemo() {
   super(new GridBagLayout());
   GridBagLayout gridbag = (GridBagLayout) getLayout();
   GridBagConstraints c = new GridBagConstraints();
   //Initialize an empty list of buttons.
   buttonList = new Vector(10, 10);
   //Create all the components.
   addButton = new JButton("Add a button");
   addButton.setActionCommand(ADD);
   addButton.addActionListener(this);
   removeButton = new JButton("Remove a button");
   removeButton.setActionCommand(REMOVE);
   removeButton.addActionListener(this);
   buttonPanel = new JPanel(new GridLayout(1, 1));
   buttonPanel.setPreferredSize(new Dimension(200, 75));
   buttonPanel.addContainerListener(this);
   display = new JTextArea();
   display.setEditable(false);
   JScrollPane scrollPane = new JScrollPane(display);
   scrollPane.setPreferredSize(new Dimension(200, 75));
   clearButton = new JButton("Clear text area");
   clearButton.setActionCommand(CLEAR);
   clearButton.addActionListener(this);
   c.fill = GridBagConstraints.BOTH; //Fill entire cell.
   c.weighty = 1.0; //Button area and message area have equal height.
   c.gridwidth = GridBagConstraints.REMAINDER; //end of row
   gridbag.setConstraints(scrollPane, c);
   add(scrollPane);
   c.weighty = 0.0;
   gridbag.setConstraints(clearButton, c);
   add(clearButton);
   c.weightx = 1.0; //Add/remove buttons have equal width.
   c.gridwidth = 1; //NOT end of row
   gridbag.setConstraints(addButton, c);
   add(addButton);
   c.gridwidth = GridBagConstraints.REMAINDER; //end of row
   gridbag.setConstraints(removeButton, c);
   add(removeButton);
   c.weighty = 1.0; //Button area and message area have equal height.
   gridbag.setConstraints(buttonPanel, c);
   add(buttonPanel);
   setPreferredSize(new Dimension(400, 400));
   setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
 }
 public void componentAdded(ContainerEvent e) {
   displayMessage(" added to ", e);
 }
 public void componentRemoved(ContainerEvent e) {
   displayMessage(" removed from ", e);
 }
 void displayMessage(String action, ContainerEvent e) {
   display.append(((JButton) e.getChild()).getText() + " was" + action
       + e.getContainer().getClass().getName() + newline);
   display.setCaretPosition(display.getDocument().getLength());
 }
 /*
  * This could have been implemented as two or three classes or objects, for
  * clarity.
  */
 public void actionPerformed(ActionEvent e) {
   String command = e.getActionCommand();
   if (ADD.equals(command)) {
     JButton newButton = new JButton("JButton #"
         + (buttonList.size() + 1));
     buttonList.addElement(newButton);
     buttonPanel.add(newButton);
     buttonPanel.revalidate(); //Make the button show up.
   } else if (REMOVE.equals(command)) {
     int lastIndex = buttonList.size() - 1;
     try {
       JButton nixedButton = (JButton) buttonList.elementAt(lastIndex);
       buttonPanel.remove(nixedButton);
       buttonList.removeElementAt(lastIndex);
       buttonPanel.revalidate(); //Make the button disappear.
       buttonPanel.repaint(); //Make the button disappear.
     } catch (ArrayIndexOutOfBoundsException exc) {
     }
   } else if (CLEAR.equals(command)) {
     display.setText("");
   }
 }
 /**
  * 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("ContainerEventDemo");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   //Create and set up the content pane.
   JComponent newContentPane = new ContainerEventDemo();
   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();
     }
   });
 }

}


 </source>
   
  
 
  



Containers

   <source lang="java">
 

/*

* Copyright (c) 2000 David Flanagan.  All rights reserved.
* This code is from the book Java Examples in a Nutshell, 2nd Edition.
* It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
* You may study, use, and modify it for any non-commercial purpose.
* You may distribute it non-commercially as long as you retain this notice.
* For a commercial use license, or to purchase the book (recommended),
* visit http://www.davidflanagan.ru/javaexamples2.
*/

import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; /**

* A component subclass that demonstrates nested containers and components. It
* creates the hierarchy shown below, and uses different colors to distinguish
* the different nesting levels of the containers
* 
* Containers---panel1----button1 | |---panel2----button2 | |
* |----panel3----button3 | |------panel4----button4 | |----button5 |---button6
*/

public class Containers extends JPanel {

 public Containers() {
   this.setBackground(Color.white); // This component is white
   this.setFont(new Font("Dialog", Font.BOLD, 24));
   JPanel p1 = new JPanel();
   p1.setBackground(new Color(200, 200, 200)); // Panel1 is darker
   this.add(p1); // p1 is contained by this component
   p1.add(new JButton("#1")); // Button 1 is contained in p1
   JPanel p2 = new JPanel();
   p2.setBackground(new Color(150, 150, 150)); // p2 is darker than p2
   p1.add(p2); // p2 is contained in p1
   p2.add(new JButton("#2")); // Button 2 is contained in p2
   JPanel p3 = new JPanel();
   p3.setBackground(new Color(100, 100, 100)); // p3 is darker than p2
   p2.add(p3); // p3 is contained in p2
   p3.add(new JButton("#3")); // Button 3 is contained in p3
   JPanel p4 = new JPanel();
   p4.setBackground(new Color(150, 150, 150)); // p4 is darker than p1
   p1.add(p4); // p4 is contained in p1
   p4.add(new JButton("#4")); // Button4 is contained in p4
   p4.add(new JButton("#5")); // Button5 is also contained in p4
   this.add(new JButton("#6")); // Button6 is contained in this component
 }
 public static void main(String[] args) {
   JFrame frame = new JFrame();
   frame.addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   });
   frame.getContentPane().add(new Containers(), BorderLayout.CENTER);
   // Finally, set the size of the main window, and pop it up.
   frame.setSize(600, 400);
   frame.setVisible(true);
 }

}


 </source>
   
  
 
  



Container which can transform its children

   <source lang="java">

/*

* Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle,
* Santa Clara, California 95054, U.S.A. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.geom.AffineTransform; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.Point2D; import java.util.Map; import java.util.HashMap; /**

* Container which can transform its children, for example:
*
 * JButton button = new JButton("Hello");
 * JXTransformer t = new JXTransformer(button);
 * t.rotate(Math.PI/2);
* 
* Note:
* This component was designed to transform simple components 
* like JButton, JLabel etc.   
* 
* @author Alexander Potochkin
* 
* https://swinghelper.dev.java.net/
* http://weblogs.java.net/blog/alexfromsun/ 
*/

public class JXTransformer extends JPanel {

   private Component glassPane = new MagicGlassPane();
   private Component view;
   private Rectangle visibleRect;
   private Map<?,?> renderingHints;
   private AffineTransform at;
   public JXTransformer() {
       this(null);
   }
   public JXTransformer(JComponent view) {
       this(view, new AffineTransform());
   }
   public JXTransformer(JComponent view, AffineTransform at) {
       super(null);
       setTransform(at);
       super.addImpl(glassPane, null, 0);
       setView(view);
       Handler handler = new Handler();
       addHierarchyBoundsListener(handler);
       addComponentListener(handler);        
   }
   public Component getView() {
       return view;
   }
   public void setView(Component view) {
       if (getView() != null) {
           super.remove(getView());
       }
       if (view != null) {
           super.addImpl(view, null, 1);
       }
       this.view = view;
       doLayout();
       revalidate();
       repaint();
   }
   public Map<?,?> getRenderingHints() {
       if (renderingHints == null) {
           return null;
       }
       return new HashMap<Object,Object>(renderingHints);
   }
   public void setRenderingHints(Map<?,?> renderingHints) {
       if (renderingHints == null) {
           this.renderingHints = null;
       } else {
           this.renderingHints = new HashMap<Object,Object>(renderingHints);
       }
       repaint();
   }
   protected void addImpl(Component comp, Object constraints, int index) {
       setView(comp);
   }
   public void remove(int index) {
       Component c = getComponent(index);
       if (c == view) {
           view = null;
           super.remove(index);
       } else if (c == glassPane) {
           throw new IllegalArgumentException("GlassPane can"t be removed");
       } else {
           throw new AssertionError("Unknown component with index " + index);
       }
   }
   public void removeAll() {
       remove(view);
   }
   //This is important
   public boolean isOptimizedDrawingEnabled() {
       return false;
   }
   public void setLayout(LayoutManager mgr) {
       if (mgr != null) {
           throw new IllegalArgumentException("Only null layout is supported");
       }
       super.setLayout(mgr);
   }
   public void doLayout() {
       if (view != null) {
           view.setSize(view.getPreferredSize());
           visibleRect = getVisibleRect();
           view.setLocation(visibleRect.x, visibleRect.y);
       }
       glassPane.setLocation(0, 0);
       glassPane.setSize(getWidth(), getHeight());
   }
   public Dimension getPreferredSize() {
       if (isPreferredSizeSet()) {
           return super.getPreferredSize();
       }
       Dimension size = getTransformedSize().getSize();
       Insets insets = getInsets();
       size.width += insets.left + insets.right;
       size.height += insets.top + insets.bottom;
       return size;
   }
   private Rectangle getTransformedSize() {
       if (view != null) {
           Dimension viewSize = view.getSize();
           Rectangle viewRect = new Rectangle(viewSize);
           return at.createTransformedShape(viewRect).getBounds();
       }
       return new Rectangle(super.getPreferredSize());
   }
   public void paint(Graphics g) {
       //repaint the whole transformer in case the view component was repainted
       Rectangle clipBounds = g.getClipBounds();        
       if (clipBounds != null && !clipBounds.equals(visibleRect)) {
           repaint();
       }
       //clear the background
       g.setColor(getBackground());
       g.fillRect(0, 0, getWidth(), getHeight());
       if (view != null && at.getDeterminant() != 0) {
           Graphics2D g2 = (Graphics2D) g.create();
           Insets insets = getInsets();
           Rectangle bounds = getBounds();
           
           //don"t forget about insets
           bounds.x += insets.left;
           bounds.y += insets.top;
           bounds.width -= insets.left + insets.right;
           bounds.height -= insets.top + insets.bottom;
           double centerX1 = bounds.getCenterX();
           double centerY1 = bounds.getCenterY();
           Rectangle tb = getTransformedSize();
           double centerX2 = tb.getCenterX();
           double centerY2 = tb.getCenterY();
           //set antialiasing by default
           g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
           if (renderingHints != null) {
               g2.addRenderingHints(renderingHints);
           }
           //translate it to the center of the view component again
           double tx = centerX1 - centerX2 - getX();
           double ty = centerY1 - centerY2 - getY();
           g2.translate((int) tx, (int) ty);
           g2.transform(at);
           view.paint(g2);
           g2.dispose();
       }
       //paint the border
       paintBorder(g);
   }
   private class MagicGlassPane extends JPanel {
       private Component mouseEnteredComponent;
       private Component mouseDraggedComponent;
       private Component mouseCurrentComponent;
       public MagicGlassPane() {
           super(null);
           setOpaque(false);
           enableEvents(AWTEvent.MOUSE_EVENT_MASK);
           enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK);
           enableEvents(AWTEvent.MOUSE_WHEEL_EVENT_MASK);
           ToolTipManager.sharedInstance().registerComponent(this);
       }
       private MouseEvent transformMouseEvent(MouseEvent event) {
           if (event == null) {
               throw new IllegalArgumentException("MouseEvent is null");
           }
           MouseEvent newEvent;
           if (event instanceof MouseWheelEvent) {
               MouseWheelEvent mouseWheelEvent = (MouseWheelEvent) event;
               newEvent = new MouseWheelEvent(mouseWheelEvent.getComponent(), mouseWheelEvent.getID(),
                       mouseWheelEvent.getWhen(), mouseWheelEvent.getModifiers(),
                       mouseWheelEvent.getX(), mouseWheelEvent.getY(),
                       mouseWheelEvent.getClickCount(), mouseWheelEvent.isPopupTrigger(),
                       mouseWheelEvent.getScrollType(), mouseWheelEvent.getScrollAmount(),
                       mouseWheelEvent.getWheelRotation());
           } else {
               newEvent = new MouseEvent(event.getComponent(), event.getID(),
                       event.getWhen(), event.getModifiers(),
                       event.getX(), event.getY(),
                       event.getClickCount(), event.isPopupTrigger(), event.getButton());
           }
           if (view != null && at.getDeterminant() != 0) {
               Rectangle viewBounds = getTransformedSize();
               Insets insets = JXTransformer.this.getInsets();
               int xgap = (getWidth() - (viewBounds.width + insets.left + insets.right)) / 2;
               int ygap = (getHeight() - (viewBounds.height + insets.top + insets.bottom)) / 2;
               
               double x = newEvent.getX() + viewBounds.getX() - insets.left;
               double y = newEvent.getY() + viewBounds.getY() - insets.top;
               Point2D p = new Point2D.Double(x - xgap, y - ygap);
               Point2D tp;
               try {
                   tp = at.inverseTransform(p, null);
               } catch (NoninvertibleTransformException ex) {
                   //can"t happen, we check it before
                   throw new AssertionError("NoninvertibleTransformException");
               }
               //Use transformed coordinates to get the current component
               mouseCurrentComponent =
                       SwingUtilities.getDeepestComponentAt(view, (int) tp.getX(), (int) tp.getY());
               if (mouseCurrentComponent == null) {
                   mouseCurrentComponent = JXTransformer.this;
               }
               Component tempComponent = mouseCurrentComponent;
               if (mouseDraggedComponent != null) {
                   tempComponent = mouseDraggedComponent;
               }
               Point point = SwingUtilities.convertPoint(view, (int) tp.getX(), (int) tp.getY(), tempComponent);
               newEvent.setSource(tempComponent);
               newEvent.translatePoint(point.x - event.getX(), point.y - event.getY());
           }
           return newEvent;
       }
       protected void processMouseEvent(MouseEvent e) {
           MouseEvent transformedEvent = transformMouseEvent(e);
           switch (e.getID()) {
               case MouseEvent.MOUSE_ENTERED:
                   if (mouseDraggedComponent == null || mouseCurrentComponent == mouseDraggedComponent) {
                       dispatchMouseEvent(transformedEvent);
                   }
                   break;
               case MouseEvent.MOUSE_EXITED:
                   if (mouseEnteredComponent != null) {
                       dispatchMouseEvent(createEnterExitEvent(mouseEnteredComponent, MouseEvent.MOUSE_EXITED, e));
                       mouseEnteredComponent = null;
                   }
                   break;
               case MouseEvent.MOUSE_RELEASED:
                   if (mouseDraggedComponent != null && e.getButton() == MouseEvent.BUTTON1) {
                       transformedEvent.setSource(mouseDraggedComponent);
                       mouseDraggedComponent = null;
                   }
                   dispatchMouseEvent(transformedEvent);
                   break;
               default:
                   dispatchMouseEvent(transformedEvent);
           }
           super.processMouseEvent(e);
       }
       private void dispatchMouseEvent(MouseEvent event) {
           MouseListener[] mouseListeners =
                   event.getComponent().getMouseListeners();
           for (MouseListener listener : mouseListeners) {
               //skip all ToolTipManager"s related listeners
               if (!listener.getClass().getName().startsWith("javax.swing.ToolTipManager")) {
                   switch (event.getID()) {
                       case MouseEvent.MOUSE_PRESSED:
                           listener.mousePressed(event);
                           break;
                       case MouseEvent.MOUSE_RELEASED:
                           listener.mouseReleased(event);
                           break;
                       case MouseEvent.MOUSE_CLICKED:
                           listener.mouseClicked(event);
                           break;
                       case MouseEvent.MOUSE_EXITED:
                           listener.mouseExited(event);
                           break;
                       case MouseEvent.MOUSE_ENTERED:
                           listener.mouseEntered(event);
                           break;
                       default:
                           throw new AssertionError();
                   }
               }
           }
       }
       protected void processMouseMotionEvent(MouseEvent e) {
           MouseEvent transformedEvent = transformMouseEvent(e);
           if (mouseEnteredComponent == null) {
               mouseEnteredComponent = mouseCurrentComponent;
           }
           switch (e.getID()) {
               case MouseEvent.MOUSE_MOVED:
                   if (mouseCurrentComponent != mouseEnteredComponent) {
                       dispatchMouseEvent(createEnterExitEvent(mouseEnteredComponent, MouseEvent.MOUSE_EXITED, e));
                       dispatchMouseEvent(createEnterExitEvent(mouseCurrentComponent, MouseEvent.MOUSE_ENTERED, e));
                   }
                   break;
               case MouseEvent.MOUSE_DRAGGED:
                   if (mouseDraggedComponent == null) {
                       mouseDraggedComponent = mouseEnteredComponent;
                   }
                   if (mouseEnteredComponent == mouseDraggedComponent && mouseCurrentComponent != mouseDraggedComponent) {
                       dispatchMouseEvent(createEnterExitEvent(mouseDraggedComponent, MouseEvent.MOUSE_EXITED, e));
                   } else if (mouseEnteredComponent != mouseDraggedComponent && mouseCurrentComponent == mouseDraggedComponent) {
                       dispatchMouseEvent(createEnterExitEvent(mouseDraggedComponent, MouseEvent.MOUSE_ENTERED, e));
                   }
                   if (mouseDraggedComponent != null) {
                       transformedEvent.setSource(mouseDraggedComponent);
                   }
                   break;
           }
           mouseEnteredComponent = mouseCurrentComponent;
           //dispatch MouseMotionEvent
           MouseMotionListener[] mouseMotionListeners =
                   transformedEvent.getComponent().getMouseMotionListeners();
           for (MouseMotionListener listener : mouseMotionListeners) {
               //skip all ToolTipManager"s related listeners
               if (!listener.getClass().getName().startsWith("javax.swing.ToolTipManager")) {
                   switch (transformedEvent.getID()) {
                       case MouseEvent.MOUSE_MOVED:
                           listener.mouseMoved(transformedEvent);
                           break;
                       case MouseEvent.MOUSE_DRAGGED:
                           listener.mouseDragged(transformedEvent);
                           break;
                       default:
                           throw new AssertionError();
                   }
               }
           }
           super.processMouseMotionEvent(e);
       }
       protected void processMouseWheelEvent(MouseWheelEvent e) {
           MouseWheelEvent transformedEvent = (MouseWheelEvent) transformMouseEvent(e);
           MouseWheelListener[] mouseWheelListeners =
                   transformedEvent.getComponent().getMouseWheelListeners();
           for (MouseWheelListener listener : mouseWheelListeners) {
               listener.mouseWheelMoved(transformedEvent);
           }
           super.processMouseWheelEvent(e);
       }
       public String getToolTipText(MouseEvent event) {
           if (mouseEnteredComponent instanceof JComponent) {
               return ((JComponent) mouseEnteredComponent).getToolTipText();
           }
           return null;
       }
       private MouseEvent createEnterExitEvent(Component c, int eventId, MouseEvent mouseEvent) {
           return new MouseEvent(c, eventId, mouseEvent.getWhen(), 0,
                   mouseEvent.getX(), mouseEvent.getY(), 0,
                   false, MouseEvent.NOBUTTON);
       }
       public String toString() {
           return "GlassPane";
       }
   }
   /**
    * This class helps view component to be in the visible area;
    * this is important when transformer is inside JScrollPane 
    */     
   private class Handler extends ComponentAdapter implements HierarchyBoundsListener {
       public void componentMoved(ComponentEvent e) {
           update();
       }
       public void ancestorMoved(HierarchyEvent e) {
           update();
       }
       public void ancestorResized(HierarchyEvent e) {
           update();
       }
       private void update() {
           if (!getVisibleRect().equals(visibleRect)) {
               revalidate();
           }
       }
   }
   /**
    * Never returns null
    */
   public AffineTransform getTransform() {
       return new AffineTransform(at);
   }
   public void setTransform(AffineTransform at) {
       if (at == null) {
           throw new IllegalArgumentException("AffineTransform is null");
       }
       this.at = new AffineTransform(at);
       revalidate();
       repaint();
   }
   public void rotate(double theta) {
       AffineTransform transform = getTransform();
       transform.rotate(theta);
       setTransform(transform);
   }
   public void scale(double sx, double sy) {
       AffineTransform transform = getTransform();
       transform.scale(sx, sy);
       setTransform(transform);
   }
   public void shear(double sx, double sy) {
       AffineTransform transform = getTransform();
       transform.shear(sx, sy);
       setTransform(transform);
   }

} ///////////// /*

* Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle,
* Santa Clara, California 95054, U.S.A. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

import javax.swing.*; import javax.swing.border.TitledBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.*; import java.awt.event.*; import java.awt.geom.AffineTransform; import java.util.ArrayList; import java.util.List; import java.util.Vector; /*

* @author Alexander Potochkin
* 
* https://swinghelper.dev.java.net/
* http://weblogs.java.net/blog/alexfromsun/ 
*/

class TransformerDemo extends JFrame implements ChangeListener {

   private List<JXTransformer> transformers = new ArrayList<JXTransformer>();
   private JSlider rotationSlider;
   private JSlider scalingSlider;
   private JSlider shearingSlider;
   public TransformerDemo() {
       super("Transformer demo");
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       JMenuBar bar = new JMenuBar();
       JMenu lafMenu = new JMenu("LaF");
       JMenuItem winLaf = new JMenuItem("Windows LaF");
       lafMenu.add(winLaf);
       winLaf.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) {
               setLaf("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
           }
       });
       JMenuItem motifLaf = new JMenuItem("Motif LaF");
       lafMenu.add(motifLaf);
       motifLaf.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) {
               setLaf("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
           }
       });
       bar.add(lafMenu);
       JMenuItem metalLaf = new JMenuItem("Metal LaF");
       lafMenu.add(metalLaf);
       metalLaf.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) {
               setLaf("javax.swing.plaf.metal.MetalLookAndFeel");
           }
       });
       JMenu settingsMenu = new JMenu("Settings");
       settingsMenu.setMnemonic(KeyEvent.VK_S);
       JMenuItem item = new JMenuItem("Reset sliders", KeyEvent.VK_R);
       item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, InputEvent.ALT_MASK));
       item.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) {
               rotationSlider.setValue(0);
               scalingSlider.setValue(100);
               shearingSlider.setValue(0);
           }
       });
       settingsMenu.add(item);
       bar.add(settingsMenu);
       setJMenuBar(bar);
       JPanel panel = new JPanel(new BorderLayout());
       panel.add(createDemoPanel());
       panel.add(createStressTestPanel(), BorderLayout.EAST);
       add(new JScrollPane(panel));
       add(new JScrollPane(createToolPanel()), BorderLayout.SOUTH);
       pack();
   }
   private void setLaf(String laf) {
       try {
           UIManager.setLookAndFeel(laf);
           SwingUtilities.updateComponentTreeUI(this);
       } catch (Exception e) {
           e.printStackTrace();
       }
       for (JXTransformer t : transformers) {
           t.revalidate();
           t.repaint();
       }
   }
   private JPanel createStressTestPanel() {
       JPanel panel = new JPanel();
       TitledBorder titledBorder = BorderFactory.createTitledBorder("Stress test (with tooltips)");
       titledBorder.setTitleJustification(TitledBorder.CENTER);
       panel.setBorder(titledBorder);
       JButton lowerButton = new JButton("Button");
       lowerButton.setLayout(new FlowLayout());
       lowerButton.setToolTipText("Lower button");
       JButton middleButton = new JButton();
       middleButton.setToolTipText("Middle button");
       middleButton.setLayout(new FlowLayout());
       lowerButton.add(middleButton);
       JButton upperButton = new JButton("Upper button");
       upperButton.setToolTipText("Upper button");
       middleButton.add(upperButton);
       panel.add(createTransformer(lowerButton));
       return panel;
   }
   private JPanel createDemoPanel() {
       JPanel buttonPanel = new JPanel(new GridLayout(3, 2));
       TitledBorder titledBorder = BorderFactory.createTitledBorder("Try three sliders below !");
       Font titleFont = titledBorder.getTitleFont();
       titledBorder.setTitleFont(titleFont.deriveFont(titleFont.getSize2D() + 10));
       titledBorder.setTitleJustification(TitledBorder.CENTER);
       buttonPanel.setBorder(titledBorder);
       JButton b = new JButton("JButton");
       b.setPreferredSize(new Dimension(100,50));
       buttonPanel.add(createTransformer(b));
       Vector<String> v = new Vector<String>();
       v.add("One");
       v.add("Two");
       v.add("Three");
       JList list = new JList(v);
       buttonPanel.add(createTransformer(list));
       
       buttonPanel.add(createTransformer(new JCheckBox("JCheckBox")));
       
       JSlider slider = new JSlider(0, 100);
       slider.setLabelTable(slider.createStandardLabels(25, 0));
       slider.setPaintLabels(true);
       slider.setPaintTicks(true);
       slider.setMajorTickSpacing(10);
       buttonPanel.add(createTransformer(slider));
       buttonPanel.add(createTransformer(new JRadioButton("JRadioButton")));
       final JLabel label = new JLabel("JLabel");
       label.addMouseListener(new MouseAdapter() {
           public void mouseEntered(MouseEvent e) {
               Font font = label.getFont();
               label.setFont(font.deriveFont(font.getSize2D() + 10));
           }
           public void mouseExited(MouseEvent e) {
               Font font = label.getFont();
               label.setFont(font.deriveFont(font.getSize2D() - 10));
           }
       });
       buttonPanel.add(createTransformer(label));
       return buttonPanel;
   }
   private JXTransformer createTransformer(JComponent c) {
       JXTransformer t = new JXTransformer(c);
       transformers.add(t);
       return t;
   }
   private JPanel createToolPanel() {
       JPanel panel = new JPanel(new GridLayout(1, 0));
       rotationSlider = new JSlider(-180, 180, 0);
       rotationSlider.setLabelTable(rotationSlider.createStandardLabels(90, -180));
       rotationSlider.setPaintLabels(true);
       rotationSlider.setPaintTicks(true);
       rotationSlider.setMajorTickSpacing(45);
       rotationSlider.addChangeListener(this);
       rotationSlider.setBorder(BorderFactory.createTitledBorder("Rotate"));
       panel.add(rotationSlider);
       shearingSlider = new JSlider(-10, 10, 0);
       shearingSlider.setLabelTable(shearingSlider.createStandardLabels(5, -10));
       shearingSlider.setPaintLabels(true);
       shearingSlider.setPaintTicks(true);
       shearingSlider.setMajorTickSpacing(2);
       shearingSlider.addChangeListener(this);
       shearingSlider.setBorder(BorderFactory.createTitledBorder("Shear"));
       panel.add(shearingSlider);
       
       scalingSlider = new JSlider(50, 150, 100);
       scalingSlider.setLabelTable(scalingSlider.createStandardLabels(25, 50));
       scalingSlider.setPaintLabels(true);
       scalingSlider.setPaintTicks(true);
       scalingSlider.setMajorTickSpacing(10);
       scalingSlider.addChangeListener(this);
       scalingSlider.setBorder(BorderFactory.createTitledBorder("Scale"));
       panel.add(scalingSlider);
       return panel;
   }
   public void stateChanged(ChangeEvent e) {
       AffineTransform at = new AffineTransform();
       at.rotate(rotationSlider.getValue() * Math.PI / 180);
       double scale = scalingSlider.getValue() / 100.0;
       at.scale(scale, scale);
       double shear = shearingSlider.getValue() / 10.0;
       at.shear(shear, 0);
       for (JXTransformer t : transformers) {
           t.setTransform(at);
       }
   }
   public static void main(String[] args) {
       TransformerDemo demo = new TransformerDemo();
       demo.setSize(800, 600);
       demo.setVisible(true);
   }

}

 </source>
   
  
 
  



Count Components in a Container

   <source lang="java">
  

import java.awt.ruponent; import java.awt.Container; import java.awt.Point; import java.util.ArrayList; import javax.swing.RootPaneContainer; import javax.swing.SwingUtilities; /**

* Copyright (C) 2004 NNL Technology AB
* Visit www.infonode.net for information about InfoNode(R) 
* products and how to contact NNL Technology AB.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, 
* MA 02111-1307, USA.
*/

// $Id: ComponentUtil.java,v 1.25 2005/12/04 13:46:04 jesper Exp $

public class Util {

 public static int countComponents(Container c) {
   int num = 1;
   for (int i = 0; i < c.getComponentCount(); i++) {
     Component comp = c.getComponent(i);
     if (comp instanceof Container)
       num += countComponents((Container) comp);
     else
       num++;
   }
   return num;
 }

}


 </source>
   
  
 
  



Find Component Under Glass Pane At

   <source lang="java">
  

import java.awt.ruponent; import java.awt.Container; import java.awt.Point; import java.util.ArrayList; import javax.swing.RootPaneContainer; import javax.swing.SwingUtilities; /**

* Copyright (C) 2004 NNL Technology AB
* Visit www.infonode.net for information about InfoNode(R) 
* products and how to contact NNL Technology AB.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, 
* MA 02111-1307, USA.
*/

// $Id: ComponentUtil.java,v 1.25 2005/12/04 13:46:04 jesper Exp $

public class Util {

 public static Component findComponentUnderGlassPaneAt(Point p, Component top) {
   Component c = null;
   if (top.isShowing()) {
     if (top instanceof RootPaneContainer)
       c =
       ((RootPaneContainer) top).getLayeredPane().findComponentAt(
           SwingUtilities.convertPoint(top, p, ((RootPaneContainer) top).getLayeredPane()));
     else
       c = ((Container) top).findComponentAt(p);
   }
   return c;
 }

}


 </source>
   
  
 
  



Find First Component Of Type

   <source lang="java">
  

import java.applet.Applet; import java.awt.ruponent; import java.awt.Container; import java.awt.Point; import java.awt.Window; import java.util.ArrayList; import javax.swing.RootPaneContainer; import javax.swing.SwingUtilities; /**

* Copyright (C) 2004 NNL Technology AB
* Visit www.infonode.net for information about InfoNode(R) 
* products and how to contact NNL Technology AB.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, 
* MA 02111-1307, USA.
*/

// $Id: ComponentUtil.java,v 1.25 2005/12/04 13:46:04 jesper Exp $

public class Util {

 public static Component findFirstComponentOfType(Component comp, Class c) {
   if (c.isInstance(comp))
     return comp;
   if (comp instanceof Container) {
     Container container = (Container) comp;
     for (int i = 0; i < container.getComponentCount(); i++) {
       Component comp2 = findFirstComponentOfType(container.getComponent(i), c);
       if (comp2 != null)
         return comp2;
     }
   }
   return null;
 }

}


 </source>
   
  
 
  



Get All Components in a container

   <source lang="java">

/*

* $Id: WindowUtils.java,v 1.16 2009/05/25 16:37:52 kschaefe Exp $
*
* Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle,
* Santa Clara, California 95054, U.S.A. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

import java.awt.ruponent; import java.awt.Container; import java.util.ArrayList; import java.util.List; /**

* Encapsulates various utilities for windows (ie: Frame and
* Dialog objects and descendants, in particular).
*
* @author Richard Bair
*/

public class Utils {

 public static List<Component> getAllComponents(final Container c) {
   Component[] comps = c.getComponents();
   List<Component> compList = new ArrayList<Component>();
   for (Component comp : comps) {
     compList.add(comp);
     if (comp instanceof Container) {
       compList.addAll(getAllComponents((Container) comp));
     }
   }
   return compList;
 }

}

 </source>
   
  
 
  



Get Child At Line

   <source lang="java">
  

import java.awt.ruponent; import java.awt.Container; import java.awt.Point; /**

* Copyright (C) 2004 NNL Technology AB
* Visit www.infonode.net for information about InfoNode(R) 
* products and how to contact NNL Technology AB.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, 
* MA 02111-1307, USA.
*/

// $Id: ComponentUtil.java,v 1.25 2005/12/04 13:46:04 jesper Exp $

public class Util {

 public static final Component getChildAtLine(Container container, Point p, boolean horizontal) {
   if (horizontal) {
     for (int i = 0; i < container.getComponentCount(); i++) {
       Component c = container.getComponent(i);
       if (p.x >= c.getX() && p.x < c.getX() + c.getWidth())
         return c;
     }
   } else {
     for (int i = 0; i < container.getComponentCount(); i++) {
       Component c = container.getComponent(i);
       if (p.y >= c.getY() && p.y < c.getY() + c.getHeight())
         return c;
     }
   }
   return null;
 }

}


 </source>
   
  
 
  



Get Child At Point

   <source lang="java">
  

import java.awt.ruponent; import java.awt.Container; import java.awt.Point;

public class Util{

 public static final Component getChildAt(Container container, Point p) {
   Component c = container.getComponentAt(p);
   return c == null || c.getParent() != container ? null : c;
 }

}


 </source>
   
  
 
  



Get Component Index

   <source lang="java">
  

import java.awt.ruponent; import java.awt.Container; import java.awt.Point; import java.util.ArrayList; /**

* Copyright (C) 2004 NNL Technology AB
* Visit www.infonode.net for information about InfoNode(R) 
* products and how to contact NNL Technology AB.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, 
* MA 02111-1307, USA.
*/

// $Id: ComponentUtil.java,v 1.25 2005/12/04 13:46:04 jesper Exp $

public class Util {

 public static final int getComponentIndex(Component component) {
   if (component != null && component.getParent() != null) {
     Container c = component.getParent();
     for (int i = 0; i < c.getComponentCount(); i++) {
       if (c.getComponent(i) == component)
         return i;
     }
   }
   return -1;
 }
 public static void getComponentTreePosition(Component c, ArrayList pos) {
   if (c.getParent() == null) {
     return;
   }
   getComponentTreePosition(c.getParent(), pos);
   pos.add(new Integer(c.getParent().getComponentCount() - getComponentIndex(c)));
 }

}


 </source>
   
  
 
  



Get Visible Child At

   <source lang="java">
  

import java.awt.ruponent; import java.awt.Container; import java.awt.Point;

public class Util{

 public static final Component getVisibleChildAt(Container container, Point p) {
   for (int i = 0; i < container.getComponentCount(); i++) {
     Component c = container.getComponent(i);
     if (c.isVisible() && c.contains(p.x - c.getX(), p.y - c.getY()))
       return c;
   }
   return null;
 }

}


 </source>
   
  
 
  



Get Visible Children Count

   <source lang="java">
  

import java.awt.ruponent; import java.awt.Container; import java.awt.Point; import java.util.ArrayList; import javax.swing.RootPaneContainer; import javax.swing.SwingUtilities; /**

* Copyright (C) 2004 NNL Technology AB
* Visit www.infonode.net for information about InfoNode(R) 
* products and how to contact NNL Technology AB.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, 
* MA 02111-1307, USA.
*/

// $Id: ComponentUtil.java,v 1.25 2005/12/04 13:46:04 jesper Exp $

public class Util {

 public static int getVisibleChildrenCount(Component c) {
   if (c == null || !(c instanceof Container))
     return 0;
   int count = 0;
   Container container = (Container) c;
   for (int i = 0; i < container.getComponentCount(); i++)
     if (container.getComponent(i).isVisible())
       count++;
   return count;
 }

}


 </source>
   
  
 
  



Has Visible Children

   <source lang="java">
  

import java.awt.ruponent; import java.awt.Container; import java.awt.Point; import java.util.ArrayList; import javax.swing.RootPaneContainer; import javax.swing.SwingUtilities; /**

* Copyright (C) 2004 NNL Technology AB
* Visit www.infonode.net for information about InfoNode(R) 
* products and how to contact NNL Technology AB.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, 
* MA 02111-1307, USA.
*/

// $Id: ComponentUtil.java,v 1.25 2005/12/04 13:46:04 jesper Exp $

public class Util {

 public static boolean hasVisibleChildren(Component c) {
   return getVisibleChildrenCount(c) > 0;
 }
 public static boolean isOnlyVisibleComponent(Component c) {
   return c != null && c.isVisible() && getVisibleChildrenCount(c.getParent()) == 1;
 }
 public static boolean isOnlyVisibleComponents(Component[] c) {
   if (c != null && c.length > 0) {
     boolean visible = getVisibleChildrenCount(c[0].getParent()) == c.length;
     if (visible)
       for (int i = 0; i < c.length; i++)
         visible = visible && c[i].isVisible();
     return visible;
   }
   return false;
 }
 public static int getVisibleChildrenCount(Component c) {
   if (c == null || !(c instanceof Container))
     return 0;
   int count = 0;
   Container container = (Container) c;
   for (int i = 0; i < container.getComponentCount(); i++)
     if (container.getComponent(i).isVisible())
       count++;
   return count;
 }

}


 </source>
   
  
 
  



Is Only Visible Component

   <source lang="java">
  

import java.awt.ruponent; import java.awt.Container; import java.awt.Point; import java.util.ArrayList; import javax.swing.RootPaneContainer; import javax.swing.SwingUtilities; /**

* Copyright (C) 2004 NNL Technology AB
* Visit www.infonode.net for information about InfoNode(R) 
* products and how to contact NNL Technology AB.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, 
* MA 02111-1307, USA.
*/

// $Id: ComponentUtil.java,v 1.25 2005/12/04 13:46:04 jesper Exp $

public class Util {

 public static boolean hasVisibleChildren(Component c) {
   return getVisibleChildrenCount(c) > 0;
 }
 public static boolean isOnlyVisibleComponent(Component c) {
   return c != null && c.isVisible() && getVisibleChildrenCount(c.getParent()) == 1;
 }
 public static boolean isOnlyVisibleComponents(Component[] c) {
   if (c != null && c.length > 0) {
     boolean visible = getVisibleChildrenCount(c[0].getParent()) == c.length;
     if (visible)
       for (int i = 0; i < c.length; i++)
         visible = visible && c[i].isVisible();
     return visible;
   }
   return false;
 }
 public static int getVisibleChildrenCount(Component c) {
   if (c == null || !(c instanceof Container))
     return 0;
   int count = 0;
   Container container = (Container) c;
   for (int i = 0; i < container.getComponentCount(); i++)
     if (container.getComponent(i).isVisible())
       count++;
   return count;
 }

}


 </source>
   
  
 
  



Is Within Parent

   <source lang="java">
  

/*

* Copyright (C) 2001-2004 Colin Bell
* colbell@users.sourceforge.net
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

import java.awt.ruponent; import java.awt.Container; import java.awt.Dimension; import java.awt.FontMetrics; import java.awt.Frame; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.Window; import java.awt.geom.Rectangle2D; import java.beans.PropertyVetoException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JInternalFrame; import javax.swing.SwingUtilities; /**

* Common GUI utilities accessed via static methods.
* 
* @author 
*/

public class GUIUtils {

 public static boolean isWithinParent(Component wind) {
   if (wind == null) {
     throw new IllegalArgumentException("Null Component passed");
   }
   Rectangle windowBounds = wind.getBounds();
   Component parent = wind.getParent();
   Rectangle parentRect = null;
   if (parent != null) {
     parentRect = new Rectangle(parent.getSize());
   } else {
     // parentRect = new
     // Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
     parentRect = getScreenBoundsFor(windowBounds);
   }
   // if (windowBounds.x > (parentRect.width - 20)
   // || windowBounds.y > (parentRect.height - 20)
   // || (windowBounds.x + windowBounds.width) < 20
   // || (windowBounds.y + windowBounds.height) < 20)
   // {
   // return false;
   // }
   if (windowBounds.x < (parentRect.x - 20) || windowBounds.y < (parentRect.y - 20)) {
     return false;
   }
   return true;
 }
 public static Rectangle getScreenBoundsFor(Rectangle rc) {
   final GraphicsDevice[] gds = GraphicsEnvironment.getLocalGraphicsEnvironment()
       .getScreenDevices();
   final List<GraphicsConfiguration> configs = new ArrayList<GraphicsConfiguration>();
   for (int i = 0; i < gds.length; i++) {
     GraphicsConfiguration gc = gds[i].getDefaultConfiguration();
     if (rc.intersects(gc.getBounds())) {
       configs.add(gc);
     }
   }
   GraphicsConfiguration selected = null;
   if (configs.size() > 0) {
     for (Iterator<GraphicsConfiguration> it = configs.iterator(); it.hasNext();) {
       GraphicsConfiguration gcc = it.next();
       if (selected == null)
         selected = gcc;
       else {
         if (gcc.getBounds().contains(rc.x + 20, rc.y + 20)) {
           selected = gcc;
           break;
         }
       }
     }
   } else {
     selected = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
         .getDefaultConfiguration();
   }
   int x = selected.getBounds().x;
   int y = selected.getBounds().y;
   int w = selected.getBounds().width;
   int h = selected.getBounds().height;
   return new Rectangle(x, y, w, h);
 }

}


 </source>