SWING: JLabel Class Cheat Sheet

Following is the declaration for javax.swing.JLabel class −

public class JLabel
   extends JComponent
      implements SwingConstants, Accessible
# Field

Following are the fields for javax.swing.JLabel class

protected Component labelFor

# Constructors
JLabel()Creates a JLabel instance with no image and with an empty string for the title.
JLabel(Icon image)Creates a JLabel instance with the specified image.
JLabel(Icon image, int horizontalAlignment)Creates a JLabel instance with the specified image and horizontal alignment.
JLabel(String text)Creates a JLabel instance with the specified text.
JLabel(String text, Icon icon, int horizontalAlignment)Creates a JLabel instance with the specified text, image, and horizontal alignment.
JLabel(String text, int horizontalAlignment)Creates a JLabel instance with the specified text and horizontal alignment.

# Methods

protected int checkHorizontalKey(int key, String message)Verify that the key is a legal value for the horizontalAlignment properties.
protected int checkVerticalKey(int key, String message)Verify that the key is a legal value for the verticalAlignment or verticalTextPosition properties.
AccessibleContext getAccessibleContext()Get the AccessibleContext of this object.
Icon getDisabledIcon()Returns the icon used by the label when it’s disabled.
int getDisplayedMnemonic()Return the keycode that indicates a mnemonic key.
int getDisplayedMnemonicIndex()Returns the character, as an index, that the look and feel should provide decoration for as representing the mnemonic character.
int getHorizontalAlignment()Returns the alignment of the label’s contents along the x-axis.
int getHorizontalTextPosition()Returns the horizontal position of the label’s text, relative to its image.
Icon getIcon()Returns the graphic image (glyph, icon) that the label displays.
int getIconTextGap()Returns the amount of space between the text and the icon displayed in this label.
Component getLabelFor()Get the component this is labeling.
String getText()Returns the text string that the label displays.
LabelUI getUI()Returns the L&F object that renders this component.
String getUIClassID()Returns a string that specifies the name of the l&f class which renders this component.
int getVerticalAlignment()Returns the alignment of the label’s contents along the y-axis.
int getVerticalTextPosition()Returns the vertical position of the label’s text, relative to its image.
boolean imageUpdate(Image img, int infoflags, int x, int y, int w, int h)This is overridden to return false if the current Icon’s image is not equal to the passed in Image img.
protected String paramString()Returns a string representation of this JLabel.
void setDisabledIcon(Icon disabledIcon)Sets the icon to be displayed if this JLabel is “disabled” (JLabel.setEnabled(false)).
void setDisplayedMnemonic(char aChar)Specifies the displayedMnemonic as a char value.
void setDisplayedMnemonic(int key)Specifies a keycode that indicates a mnemonic key.
void setDisplayedMnemonicIndex(int index)It provides a hint to the look and feels as to which character in the text should be decorated to represent the mnemonic.
void setHorizontalAlignment(int alignment)Sets the alignment of the label’s contents along the x-axis.
void setHorizontalTextPosition(int textPosition)Sets the horizontal position of the label’s text, relative to its image.
void setIcon(Icon icon)Defines the icon this component will display.
void setIconTextGap(int iconTextGap)If both the icon and text properties are set, this property defines the space between them.
void setLabelFor(Component c)Sets the component, this is labelling.
void setText(String text)Defines the single line of text this component will display.
void setUI(LabelUI ui)Sets the L&F object that renders this component.
void setVerticalAlignment(int alignment)Sets the alignment of the label’s contents along the y-axis.
void setVerticalTextPosition(int textPosition)Sets the vertical position of the label’s text, relative to its image.
void updateUI()Resets the UI property to a value from the current look and feel.
# Methods Inherited
  • javax.swing.JComponent
  • java.awt.Container
  • java.awt.Component
  • java.lang.Object
# JLabel Example

SwingControlDemo.java

package com.simplecheatsheet.gui;
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class SwingControlDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingControlDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingControlDemo  swingControlDemo = new SwingControlDemo();      
      swingControlDemo.showLabelDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java Swing Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    
      statusLabel.setSize(350,100);
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showLabelDemo(){
      headerLabel.setText("Control in action: JLabel");      
      JLabel label  = new JLabel("", JLabel.CENTER);        
      label.setText("Welcome to TutorialsPoint Swing Tutorial.");
      label.setOpaque(true);
      label.setBackground(Color.GRAY);
      label.setForeground(Color.WHITE);
      controlPanel.add(label);
      
      mainFrame.setVisible(true);  
   }
}

SWING: JComponent Class Cheat Sheet

Following is the declaration for javax.swing.JComponent class

public abstract class JComponent
   extends Container
      implements Serializable
# Field

Following are the fields for java.awt.Component class

  • protected AccessibleContext accessibleContext − The AccessibleContext associated with this JComponent.
  • protected EventListenerList listenerList − A list of event listeners for this component.
  • static String TOOL_TIP_TEXT_KEY − The comment to display when the cursor is over the component, also known as a “value tip”, “flyover help”, or “flyover label”.
  • protected ComponentUI ui − The look and feel delegate for this component.
  • static int UNDEFINED_CONDITION − Constant used by some of the APIs means that no condition is defined.
  • static int WHEN_ANCESTOR_OF_FOCUSED_COMPONENT − Constant used for registerKeyboardAction which means that the command should be invoked when the receiving component is an ancestor of the focused component or is itself the focused component.
  • static int WHEN_FOCUSED − Constant used for registerKeyboardAction which means that the command should be invoked when the component has the focus.
  • static int WHEN_IN_FOCUSED_WINDOW − Constant used for registerKeyboardAction which means that the command should be invoked when the receiving component is in the window having the focus or is itself the focused component.
# Constructors
JComponent()Default JComponent constructor.

Class Methods

Sr.No.Method & Description
1void addAncestorListener(AncestorListener listener)Registers listener so that it will receive AncestorEvents when it or any of its ancestors move or are made visible or invisible.
2void addNotify()Notifies this component that it now has a parent component.
3void addVetoableChangeListener(VetoableChangeListener listener)Adds a VetoableChangeListener to the listener list.
4void computeVisibleRect(Rectangle visibleRect)Returns the Component’s “visible rect rectangle” – the intersection of the visible rectangles for this component and all of its ancestors.
5boolean contains(int x, int y)Gives the UI delegate an opportunity to define the precise shape of this component for the sake of mouse processing.
6JToolTip createToolTip()Returns the instance of JToolTip that should be used to display the tooltip.
7void disable()Deprecated.As of JDK version 1.1, replaced by java.awt.Component.setEnabled(boolean).
8void enable()Deprecated. As of JDK version 1.1, replaced by java.awt.Component.setEnabled(boolean).
9void firePropertyChange(String propertyName, boolean oldValue, boolean newValue)Supports reporting bound property changes for boolean properties.
10void firePropertyChange(String propertyName, char oldValue, char newValue)Reports a bound property change.
11void firePropertyChange(String propertyName, int oldValue, int newValue)Supports reporting bound property changes for integer properties.
12protected void fireVetoableChange(String propertyName, Object oldValue, Object newValue)Supports reporting constrained property changes.
13AccessibleContext getAccessibleContext()Returns the AccessibleContext associated with this JComponent.
14ActionListener getActionForKeyStroke(KeyStroke aKeyStroke)Returns the object that will perform the action registered for a given keystroke.
15ActionMap getActionMap()Returns the ActionMap used to determine what Action to fire for particular KeyStroke binding.
16float getAlignmentX()Overrides Container.getAlignmentX to return the vertical alignment.
17float getAlignmentY()Overrides Container.getAlignmentY to return the horizontal alignment.
18AncestorListener[]getAncestorListeners()Returns an array of all the ancestor listeners registered on this component.
19boolean getAutoscrolls()Gets the autoscrolls property.
20int getBaseline(int width, int height)Returns the baseline.
21Component.BaselineResizeBehavior getBaselineResizeBehavior()Returns an enum indicating how the baseline of the component changes as the size changes.
22Border getBorder()Returns the border of this component or null if no border is currently set.
23Rectangle getBounds(Rectangle rv)Stores the bounds of this component into “return value” rv and returns rv.
24Object getClientProperty(Object key)Returns the value of the property with the specified key.
25protected Graphics getComponentGraphics(Graphics g)Returns the graphics object used to paint this component.
26JPopupMenu getComponentPopupMenu()Returns JPopupMenu that assigned for this component.
27int getConditionForKeyStroke(KeyStroke aKeyStroke)Returns the condition that determines whether a registered action occurs in response to the specified keystroke.
28int getDebugGraphicsOptions()Returns the state of graphics debugging.
29static Locale getDefaultLocale()Returns the default locale used to initialize each JComponent’s locale property upon creation.
30FontMetrics getFontMetrics(Font font)Gets the FontMetrics for the specified Font.
31Graphics getGraphics()Returns this component’s graphics context, which lets you draw on a component.
32int getHeight()Returns the current height of this component.
33boolean getInheritsPopupMenu()Returns true if the JPopupMenu should be inherited from the parent.
34InputMap getInputMap()Returns the InputMap that is used when the component has focus.
35InputMap getInputMap(int condition)Returns the InputMap that is used during condition.
36InputVerifier getInputVerifier()Returns the input verifier for this component.
37Insets getInsets()If a border has been set on this component, returns the border’s insets; otherwise calls super.getInsets.
38Insets getInsets(Insets insets)Returns an Insets object containing this component’s inset values.
39<T extends EventListener> T[] getListeners(Class<T> listenerType)Returns an array of all the objects currently registered as FooListeners upon this JComponent.
40Point getLocation(Point rv)Stores the x,y origin of this component into “return value” rv and returns rv.
41Dimension getMaximumSize()If the maximum size has been set to a non-null value, just returns it.
42Dimension getMinimumSize()If the minimum size has been set to a non-null value just returns it.
43Component getNextFocusableComponent()Deprecated. As of 1.4, replaced by FocusTraversalPolicy.
44Point getPopupLocation(MouseEvent event)Returns the preferred location to display the popup menu in this component’s coordinate system.
45Dimension getPreferredSize()If the preferredSize has been set to a non-null value just returns it.
46KeyStroke[] getRegisteredKeyStrokes()Returns the KeyStrokes that will initiate registered actions.
47JRootPane getRootPane()Returns the JRootPane ancestor for this component.
48Dimension getSize(Dimension rv)Stores the width/height of this component into “return value” rv and returns rv.
49Point getToolTipLocation(MouseEvent event)Returns the tooltip location in this component’s coordinate system.
50String getToolTipText()Returns the tooltip string that has been set with setToolTipText.
51String getToolTipText(MouseEvent event)Returns the string to be used as the tooltip for the event.
52Container getTopLevelAncestor()Returns the top-level ancestor of this component (either the containing Window or Applet), or null if this component has not been added to any container.
53TransferHandler getTransferHandler()Gets the transferHandler property.
54String getUIClassID()Returns the UIDefaults key used to look up the name of the swing.plaf.ComponentUI class that defines the look and feel for this component.
55boolean getVerifyInputWhenFocusTarget()Returns the value that indicates whether the input verifier for the current focus owner will be called before this component requests focus.
56VetoableChangeListener[] getVetoableChangeListeners()Returns an array of all the vetoable change listeners registered on this component.
57Rectangle getVisibleRect()Returns the component’s “visible rectangle” – the intersection of this component’s visible rectangle, new rectangle(0, 0, getWidth(), getHeight()), and all of its ancestors’ visible rectangles.
58int getWidth()Returns the current width of this component.
59int getX()Returns the current x coordinate of the component’s origin.
60int getY()Returns the current y coordinate of the component’s origin.
61void grabFocus()Requests that this component gets the input focus, and that this component’s top-level ancestor become the focused Window.
62boolean isDoubleBuffered()Returns whether this component should use a buffer to paint.
63static boolean isLightweightComponent(Component c)Returns true if this component is lightweight, that is, if it doesn’t have a native window system peer.
64boolean isManagingFocus()Deprecated.As of 1.4, replaced by Component.setFocusTraversalKeys(int, Set) and Container.setFocusCycleRoot(boolean).
65boolean isOpaque()Returns true if this component is completely opaque.
66boolean isOptimizedDrawingEnabled()Returns true if this component tiles its children, i.e, if it can guarantee that the children will not overlap.
67boolean isPaintingForPrint()Returns true if the current painting operation on this component is part of a print operation.
68boolean isPaintingTile()Returns true if the component is currently painting a tile.
69boolean isRequestFocusEnabled()Returns true if this JComponent should get focus; otherwise returns false.
70boolean isValidateRoot()If this method returns true, revalidate calls by descendants of this component will cause the entire tree beginning with this root to be validated.
71void paint(Graphics g)Invoked by Swing to draw components.
72protected void paintBorder(Graphics g)Paints the component’s border.
73protected void paintChildren(Graphics g)Paints this component’s children.
74protected void paintComponent(Graphics g)Calls the UI delegate’s paint method, if the UI delegate is non-null.
75void paintImmediately(int x, int y, int w, int h)Paints the specified region in this component and all of its descendants that overlap the region, immediately.
76void paintImmediately(Rectangle r)Paints the specified region now.
77protected String paramString()Returns a string representation of this JComponent.
78void print(Graphics g)Invokes this method to print the component to the specified Graphics.
79void printAll(Graphics g)Invokes this method to print the component.
80protected void printBorder(Graphics g)Prints the component’s border.
81protected void printChildren(Graphics g)Prints this component’s children.
82protected void printComponent(Graphics g)This is invoked during a printing operation.
83protected void processComponentKeyEvent(KeyEvent e)Processes any key events that the component itself recognizes.
84protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed)Invoked to process the key bindings for ks as the result of the KeyEvent e.
85protected void processKeyEvent(KeyEvent e)Overrides processKeyEvent to process events.
86protected void processMouseEvent(MouseEvent e)Processes mouse events occurring on this component by dispatching them to any registered MouseListener objects, refer to Component.processMouseEvent(MouseEvent) for a complete description of this method.
87protected void processMouseMotionEvent(MouseEvent e)Processes mouse motion events, such as MouseEvent.MOUSE_DRAGGED.
88void putClientProperty(Object key, Object value)Adds an arbitrary key/value “client property” to this component.
89void registerKeyboardAction(ActionListener anAction, KeyStroke aKeyStroke, int aCondition)This method is now obsolete, please use a combination of getActionMap() and getInputMap() for similiar behavior.
90void registerKeyboardAction(ActionListener anAction, String aCommand, KeyStroke aKeyStroke, int aCondition)This method is now obsolete, please use a combination of getActionMap() and getInputMap() for similiar behavior.
91void removeAncestorListener(AncestorListener listener)Unregisters listener so that it will no longer receive AncestorEvents.
92void removeNotify()Notifies this component that it no longer has a parent component.
93void removeVetoableChangeListener(VetoableChangeListener listener)Removes a VetoableChangeListener from the listener list.
94void repaint(long tm, int x, int y, int width, int height)Adds the specified region to the dirty region list if the component is showing.
95void repaint(Rectangle r)Adds the specified region to the dirty region list, if the component is showing.
96boolean requestDefaultFocus()Deprecated.As of 1.4, replaced by FocusTraversalPolicy.getDefaultComponent(Container).requestFocus()
97void requestFocus()Requests that this component gets the input focus.
98boolean requestFocus(boolean temporary)Requests that this component gets the input focus.
99boolean requestFocusInWindow()Requests that this component gets the input focus.
100protected boolean requestFocusInWindow(boolean temporary)Requests that this component gets the input focus.
101void resetKeyboardActions()Unregisters all the bindings in the first tier InputMaps and ActionMap.
102void reshape(int x, int y, int w, int h)Deprecated.As of JDK 5, replaced by Component.setBounds(int, int, int, int).Moves and resizes this component.
103void revalidate()Supports deferred automatic layout.
104void scrollRectToVisible(Rectangle aRect)Forwards the scrollRectToVisible() message to the JComponent’s parent.
105void setActionMap(ActionMap am)Sets the ActionMap to am.
106void setAlignmentX(float alignmentX)Sets the the vertical alignment.
107void setAlignmentY(float alignmentY)Sets the the horizontal alignment.
108void setAutoscrolls(boolean autoscrolls)Sets the autoscrolls property.
109void setBackground(Color bg)Sets the background color of this component.
110void setBorder(Border border)Sets the border of this component.
111void setComponentPopupMenu(JPopupMenu popup)Sets the JPopupMenu for this JComponent.
112void setDebugGraphicsOptions(int debugOptions)Enables or disables diagnostic information about every graphics operation performed within the component or one of its children.
113static void setDefaultLocale(Locale l)Sets the default locale used to initialize each JComponent’s locale property upon creation.
114void setDoubleBuffered(boolean aFlag)Sets whether this component should use a buffer to paint.
115void setEnabled(boolean enabled)Sets whether or not this component is enabled.
116void setFocusTraversalKeys(int id, Set<? extends AWTKeyStroke> keystrokes)Sets the focus traversal keys for a given traversal operation for this component.
117void setFont(Font font)Sets the font for this component.
118void setForeground(Color fg)Sets the foreground color of this component.
119void setInheritsPopupMenu(boolean value)Sets whether or not getComponentPopupMenu should delegate to the parent, if this component does not have a JPopupMenu assigned to it.
120void setInputMap(int condition, InputMap map)Sets the InputMap to use under the condition condition to map.
121void setInputVerifier(InputVerifier inputVerifier)Sets the input verifier for this component.
122void setMaximumSize(Dimension maximumSize)Sets the maximum size of this component to a constant value.
123void setMinimumSize(Dimension minimumSize)Sets the minimum size of this component to a constant value.
124void setNextFocusableComponent(Component aComponent)Deprecated. As of 1.4, replaced by FocusTraversalPolicy
125void setOpaque(boolean isOpaque)If true, the component paints every pixel within its bounds.
126void setPreferredSize(Dimension preferredSize)Sets the preferred size of this component.
127void setRequestFocusEnabled(boolean requestFocusEnabled)Provides a hint as to whether or not this JComponent should get focus.
128void setToolTipText(String text)Registers the text to display in a tool tip.
129void setTransferHandler(TransferHandler newHandler)Sets the transferHandler property, which is null if the component does not support data transfer operations.
130protected void setUI(ComponentUI newUI)Sets the look and feel delegate for this component.
131void setVerifyInputWhenFocusTarget(boolean verifyInputWhenFocusTarget)Sets the value to indicate whether the input verifier for the current focus owner will be called before this component requests focus.
132void setVisible(boolean aFlag)Makes the component visible or invisible.
133void unregisterKeyboardAction(KeyStroke aKeyStroke)This method is now obsolete.
134void update(Graphics g)Calls paint.
135void updateUI()Resets the UI property to a value from the current look and feel.
# Methods Inherited
  • java.awt.Container
  • java.awt.Component
  • java.lang.Object

SWING: Container Class Cheat Sheet

Following is the declaration for java.awt.Container class −

public class Container
   extends Component
# Constructors
Container()This creates a new Container.
# Methods
Sr.No.Method & Description
1Component add(Component comp)Appends the specified component to the end of this container.
2Component add(Component comp, int index)Adds the specified component to this container at the given position.
3void add(Component comp, Object constraints)Adds the specified component to the end of this container.
4void add(Component comp, Object constraints, int index)Adds the specified component to this container with the specified constraints at the specified index.
5Component add(String name, Component comp)Adds the specified component to this container.
6void addContainerListener(ContainerListener l)Adds the specified container listener to receive container events from this container.
7protected void addImpl(Component comp, Object constraints, int index)Adds the specified component to this container at the specified index.
8void addNotify()Makes this Container displayable by connecting it to a native screen resource.
9void addPropertyChangeListener(PropertyChangeListener listener)Adds a PropertyChangeListener to the listener list.
10void addPropertyChangeListener(String propertyName, PropertyChangeListener listener)Adds a PropertyChangeListener to the listener list for a specific property.
11void applyComponentOrientation(ComponentOrientation o)Sets the ComponentOrientation property of this container and all components contained within it.
12boolean areFocusTraversalKeysSet(int id)Returns whether the Set of focus traversal keys for the given focus traversal operation has been explicitly defined for this Container.
13int countComponents()Deprecated. As of JDK version 1.1, replaced by getComponentCount().
14void deliverEvent(Event e)Deprecated. As of JDK version 1.1, replaced by dispatchEvent(AWTEvent e)
15void doLayout()Causes this container to lay out its components.
16Component findComponentAt(int x, int y)Locates the visible child component that contains the specified position.
17Component findComponentAt(Point p)Locates the visible child component that contains the specified point.
18float getAlignmentX()Returns the alignment along the x axis.
19float getAlignmentY()Returns the alignment along the y axis.
20Component getComponent(int n)Gets the nth component in this container.
21Component getComponentAt(int x, int y)Locates the component that contains the x,y position.
22Component getComponentAt(Point p)Gets the component that contains the specified point.
23int getComponentCount()Gets the number of components in this panel.
24Component[] getComponents()Gets all the components in this container.
25int getComponentZOrder(Component comp)Returns the z-order index of the component inside the container.
26ContainerListener[] getContainerListeners()Returns an array of all the container listeners registered on this container.
27Set<AWTKeyStroke> getFocusTraversalKeys(int id)Returns the Set of focus traversal keys for a given traversal operation for this Container.
28FocusTraversalPolicy getFocusTraversalPolicy()Returns the focus traversal policy that will manage keyboard traversal of this Container’s children, or null if this Container is not a focus cycle root.
29Insets getInsets()Determines the insets of this container, which indicate the size of the container’s border.
30LayoutManager getLayout()Gets the layout manager for this container.
31<T extends EventListener> T[] getListeners(Class<T> listenerType)Returns an array of all the objects currently registered as FooListeners upon this Container.
32Dimension getMaximumSize()Returns the maximum size of this container.
33Dimension getMinimumSize()Returns the minimum size of this container.
34Point getMousePosition(boolean allowChildren)Returns the position of the mouse pointer in this Container’s coordinate space if the Container is under the mouse pointer, otherwise returns null.
35Dimension getPreferredSize()Returns the preferred size of this container.
36Insets insets()Deprecated. As of JDK version 1.1, replaced by getInsets().
37void invalidate()Invalidates the container.
38boolean isAncestorOf(Component c)Checks if the component is contained in the component hierarchy of this container.
39boolean isFocusCycleRoot()Returns whether this Container is the root of a focus traversal cycle.
40boolean isFocusCycleRoot(Container container)Returns whether the specified Container is the focus cycle root of this Container’s focus traversal cycle.
41boolean isFocusTraversalPolicyProvider()Returns whether this container provides focus traversal policy.
42boolean isFocusTraversalPolicySet()Returns whether the focus traversal policy has been explicitly set for this Container.
43void layout()Deprecated. As of JDK version 1.1, replaced by doLayout().
44void list(PrintStream out, int indent)Prints a listing of this container to the specified output stream.
45void list(PrintWriter out, int indent)Prints out a list, starting at the specified indentation, to the specified print writer.
46Component locate(int x, int y)Deprecated. As of JDK version 1.1, replaced by getComponentAt(int, int).
47Dimension minimumSize()Deprecated. As of JDK version 1.1, replaced by getMinimumSize().
48void paint(Graphics g)Paints the container.
49void paintComponents(Graphics g)Paints each of the components in this container.
50protected String paramString()Returns a string representing the state of this Container.
51Dimension preferredSize()Deprecated. As of JDK version 1.1, replaced by getPreferredSize().
52void print(Graphics g)Prints the container.
53void printComponents(Graphics g)Prints each of the components in this container.
54protected void processContainerEvent(ContainerEvent e)Processes container events occurring on this container by dispatching them to any registered ContainerListener objects.
55protected void processEvent(AWTEvent e)Processes events on this container.
56void remove(Component comp)Removes the specified component from this container.
57void remove(int index)Removes the component, specified by index, from this container.
58void removeAll()Removes all the components from this container.
59void removeContainerListener(ContainerListener l)Removes the specified container listener so it no longer receives container events from this container.
60void removeNotify()Makes this container undisplayable by removing its connection to its native screen resource.
61void setComponentZOrder(Component comp, int index)Moves the specified component to the specified z-order index in the container.
62void setFocusCycleRoot(boolean focusCycleRoot)Sets whether this Container is the root of a focus traversal cycle.
63void setFocusTraversalKeys(int id, Set<? extends AWTKeyStroke> keystrokes)Sets the focus traversal keys for a given traversal operation for this Container.
64void setFocusTraversalPolicy(FocusTraversalPolicy policy)Sets the focus traversal policy that will manage keyboard traversal of this container’s children, if this container is a focus cycle root.
65void setFocusTraversalPolicyProvider(boolean provider)Sets whether this container will be used to provide focus traversal policy.
66void setFont(Font f)Sets the font of this container.
67void setLayout(LayoutManager mgr)Sets the layout manager for this container.
68void transferFocusBackward()Transfers the focus to the previous component, as though this Component were the focus owner.
69void transferFocusDownCycle()Transfers the focus down one focus traversal cycle.
70void update(Graphics g)Updates the container.
71void validate()Validates this container and all of its subcomponents.
72protected void validateTree()Recursively descends the container tree and recomputes the layout for any subtrees marked as needing it (those marked as invalid).
# Methods Inherited
  • java.awt.Component
  • java.lang.Object

SWING: Component Class Cheat Sheet

Following is the declaration for java.awt.Component class −

public abstract class Component
   extends Object
      implements ImageObserver, MenuContainer, Serializable
# Field

Following are the fields for java.awt.Component class

  • static float BOTTOM_ALIGNMENT − Ease-of-use constant for getAlignmentY.
  • static float CENTER_ALIGNMENT − Ease-of-use constant for getAlignmentY and getAlignmentX.
  • static float LEFT_ALIGNMENT − Ease-of-use constant for getAlignmentX.
  • static float RIGHT_ALIGNMENT − Ease-of-use constant for getAlignmentX.
  • static float TOP_ALIGNMENT − Ease-of-use constant for getAlignmentY().
# Constructors
protected Component()This creates a new Component.
# Methods
Sr.No.Method & Description
1boolean action(Event evt, Object what)Deprecated. As of JDK version 1.1, should register this component as ActionListener on the component which fires action events.
2void add(PopupMenu popup)Adds the specified popup menu to the component.
3void addComponentListener(ComponentListener l)Adds the specified component listener to receive the component events from this component.
4void addFocusListener(FocusListener l)Adds the specified focus listener to receive focus events from this component, when this component gains input focus.
5void addHierarchyBoundsListener(HierarchyBoundsListener l)Adds the specified hierarchy bounds listener to receive hierarchy bounds events from this component, when the hierarchy to which this container belongs changes.
6void addHierarchyListener(HierarchyListener l)Adds the specified hierarchy listener to receive hierarchy changed events from this component, when the hierarchy to which this container belongs changes.
7void addInputMethodListener(InputMethodListener l)Adds the specified input method listener to receive input method events from this component.
8void addKeyListener(KeyListener l)Adds the specified key listener to receive key events from this component.
9void addMouseListener(MouseListener l)Adds the specified mouse listener to receive mouse events from this component.
10void addMouseMotionListener(MouseMotionListener l)Adds the specified mouse motion listener to receive mouse motion events from this component.
11void addMouseWheelListener(MouseWheelListener l)Adds the specified mouse wheel listener to receive mouse wheel events from this component.
12void addNotify()Makes this Component displayable by connecting it to a native screen resource.
13void addPropertyChangeListener(PropertyChangeListener listener)Adds a PropertyChangeListener to the listener list.
14void addPropertyChangeListener(String propertyName, PropertyChangeListener listener)Adds a PropertyChangeListener to the listener list for a specific property.
15void applyComponentOrientation(ComponentOrientation orientation)Sets the ComponentOrientation property of this component and all components contained within it.
16boolean areFocusTraversalKeysSet(int id)Returns whether the set of focus traversal keys for the given focus traversal operation has been explicitly defined for this Component.
17int checkImage(Image image, ImageObserver observer)Returns the status of the construction of a screen representation of the specified image.
18int checkImage(Image image,int width,int height, ImageObserver observer)Returns the status of the construction of a screen representation of the specified image.
19boolean contains(int x,int y)Checks whether this component “contains” the specified point, where x and y are defined to be relative to the coordinate system of this component.
20boolean contains(Point p)Checks whether this component “contains” the specified point, where the point’s x and y coordinates are defined to be relative to the coordinate system of this component.
21Image createImage(ImageProducer producer)Creates an image from the specified image producer.
22Image createImage(int width,int height)Creates an off-screen drawable image to be used for double buffering.
23VolatileImage createVolatileImage(int width,int height)Creates a volatile off-screen drawable image to be used for double buffering.
24VolatileImage createVolatileImage(int width,int height, ImageCapabilities caps)Creates a volatile off-screen drawable image, with the given capabilities.
25void deliverEvent(Event e)Deprecated. As of JDK version 1.1, replaced by dispatchEvent(AWTEvent e).
26void disable()Deprecated. As of JDK version 1.1, replaced by setEnabled(boolean).
27protected void disableEvents(long eventsToDisable)Disables the events defined by the specified event mask parameter from being delivered to this component.
28void dispatchEvent(AWTEvent e)Dispatches an event to this component or one of its sub components.
29void doLayout()Prompts the layout manager to lay out this component.
30void enable()Deprecated. As of JDK version 1.1, replaced by setEnabled(boolean).
31void enable(boolean b)Deprecated. As of JDK version 1.1, replaced by setEnabled(boolean).
32protected void enableEvents(long eventsToEnable)Enables the events defined by the specified event mask parameter to be delivered to this component.
33void enableInputMethods(boolean enable)Enables or disables input method support for this component.
34protected void firePropertyChange(String propertyName, boolean oldValue, boolean newValue)Supports reporting bound property changes for boolean properties.
35void firePropertyChange(String propertyName, byte oldValue, byte newValue)Reports a bound property change.
36void firePropertyChange(String propertyName, char oldValue, char newValue)Reports a bound property change.
37void firePropertyChange(String propertyName, double oldValue, double newValue)Reports a bound property change.
38void firePropertyChange(String propertyName, float oldValue, float newValue)Reports a bound property change.
39void firePropertyChange(String propertyName, long oldValue, long newValue)Reports a bound property change.
40protected void firePropertyChange(String propertyName, Object oldValue, Object newValue)Supports reporting bound property changes for Object properties.
41void firePropertyChange(String propertyName, short oldValue, short newValue)Reports a bound property change.
42AccessibleContext getAccessibleContext()Gets the AccessibleContext associated with this Component.
43float getAlignmentX()Returns the alignment along the x axis.
44float getAlignmentY()Returns the alignment along the y axis.
45Color getBackground()Gets the background color of this component.
46int getBaseline(int width,int height)Returns the baseline.
47Component.BaselineResizeBehavior getBaselineResizeBehavior()Returns an enum indicating how the baseline of the component changes as the size changes.
48Rectangle getBounds()Gets the bounds of this component in the form of a Rectangle object.
49Rectangle getBounds(Rectangle rv)Stores the bounds of this component into “return value” rv and returns rv.
50ColorModel getColorModel()Gets the instance of ColorModel used to display the component on the output device.
51Component getComponentAt(int x,int y)Determines if this component or one of its immediate subcomponents contains the (x, y) location, and if so, returns the containing component.
52Component getComponentAt(Point p)Returns the component or subcomponent that contains the specified point.
53ComponentListener[] getComponentListeners()Returns an array of all the component listeners registered on this component.
54ComponentOrientation getComponentOrientation()Retrieves the language-sensitive orientation that is to be used to order the elements or the text within this component.
55Cursor getCursor()Gets the cursor set in the component.
56DropTarget getDropTarget()Gets the DropTarget associated with this Component.
57Container getFocusCycleRootAncestor()Returns the Container which is the focus cycle root of this Component’s focus traversal cycle.
58FocusListener[] getFocusListeners()Returns an array of all the focus listeners registered on this component.
59Set<AWTKeyStroke> getFocusTraversalKeys(int id)Returns the Set of focus traversal keys for a given traversal operation for this Component.
60boolean getFocusTraversalKeysEnabled()Returns whether focus traversal keys are enabled for this Component.
61Font getFont()Gets the font of this component.
62FontMetrics getFontMetrics(Font font)Gets the font metrics for the specified font.
63Color getForeground()Gets the foreground color of this component.
64Graphics getGraphics()Creates a graphics context for this component.
65GraphicsConfiguration getGraphicsConfiguration()Gets the GraphicsConfiguration associated with this Component.
66int getHeight()Returns the current height of this component.
67HierarchyBoundsListener[] getHierarchyBoundsListeners()Returns an array of all the hierarchy bounds listeners registered on this component.
68HierarchyListener[] getHierarchyListeners()Returns an array of all the hierarchy listeners registered on this component.
69boolean getIgnoreRepaint()
70InputContext getInputContext()Gets the input context used by this component for handling the communication with input methods, when the text is entered in this component.
71InputMethodListener[] getInputMethodListeners()Returns an array of all the input method listeners registered on this component.
72InputMethodRequests getInputMethodRequests()Gets the input method request handler which supports requests from input methods for this component.
73KeyListener[] getKeyListeners()Returns an array of all the key listeners registered on this component.
74<T extends EventListener> T[] getListeners(Class<T> listenerType)Returns an array of all the objects currently registered as FooListeners upon this Component.
75Locale getLocale()Gets the locale of this component.
76Point getLocation()Gets the location of this component in the form of a point specifying the component’s top-left corner.
77Point getLocation(Point rv)Stores the x,y origin of this component into “return value” rv and returns rv.
78Point getLocationOnScreen()Gets the location of this component in the form of a point specifying the component’s top-left corner in the screen’s coordinate space.
79Dimension getMaximumSize()Gets the maximum size of this component.
80Dimension getMinimumSize()Gets the mininimum size of this component.
81MouseListener[] getMouseListeners()Returns an array of all the mouse listeners registered on this component.
82MouseMotionListener[] getMouseMotionListeners()Returns an array of all the mouse motion listeners registered on this component.
83Point getMousePosition()Returns the position of the mouse pointer in this Component’s coordinate space if the Component is directly under the mouse pointer, otherwise returns null.
84MouseWheelListener[] getMouseWheelListeners()Returns an array of all the mouse wheel listeners registered on this component.
85String getName()Gets the name of the component.
86Container getParent()Gets the parent of this component.
87java.awt.peer.ComponentPeer getPeer()Deprecated. As of JDK version 1.1, programs should not directly manipulate peers; replaced by boolean isDisplayable().
88Dimension getPreferredSize()Gets the preferred size of this component.
89PropertyChangeListener[] getPropertyChangeListeners()Returns an array of all the property change listeners registered on this component.
90PropertyChangeListener[] getPropertyChangeListeners(String propertyName)Returns an array of all the listeners which have been associated with the named property.
91Dimension getSize()Returns the size of this component in the form of a Dimension object.
92Dimension getSize(Dimension rv)Stores the width/height of this component into “return value: rv and returns rv.
93Toolkit getToolkit()Gets the toolkit of this component.
94Object getTreeLock()Gets this component’s locking object (the object that owns the thread sychronization monitor) for AWT component-tree and layout operations.
95int getWidth()Returns the current width of this component.
96int getX()Returns the current x coordinate of the components origin.
97int getY()Returns the current y coordinate of the components origin.
98boolean gotFocus(Event evt, Object what)Deprecated. As of JDK version 1.1, replaced by processFocusEvent(FocusEvent).
99boolean handleEvent(Event evt)Deprecated. As of JDK version 1.1 replaced by processEvent(AWTEvent).
100boolean hasFocus()Returns true if this Component is the focus owner.
101void hide()Deprecated. As of JDK version 1.1, replaced by setVisible(boolean).
102boolean imageUpdate(Image img,int infoflags,int x,int y,int w,int h)Repaints the component when the image has changed.
103boolean inside(int x,int y)Deprecated. As of JDK version 1.1, replaced by contains(int, int).
104void invalidate()Invalidates this component.
105boolean isBackgroundSet()Returns whether the background color has been explicitly set for this Component.
106boolean isCursorSet()Returns whether the cursor has been explicitly set for this Component.
107boolean isDisplayable()Determines whether this component is displayable.
108boolean isDoubleBuffered()Returns true if this component is painted to an offscreen image (buffer)that’s copied to the screen later.
109boolean isEnabled()Determines whether this component is enabled.
110boolean isFocusable()Returns whether this Component can be focused.
111boolean isFocusCycleRoot(Container container)Returns whether the specified Container is the focus cycle root of this Component’s focus traversal cycle.
112boolean isFocusOwner()Returns true if this Component is the focus owner.
113boolean isFocusTraversable()Deprecated. As of 1.4, replaced by isFocusable().
114boolean isFontSet()Returns whether the font has been explicitly set for this Component.
115boolean isForegroundSet()Returns whether the foreground color has been explicitly set for this Component.
116boolean isLightweight()A lightweight component doesn’t have a native toolkit peer.
117boolean isMaximumSizeSet()Returns true if the maximum size has been set to a non-null value otherwise returns false.
118boolean isMinimumSizeSet()Returns whether or not setMinimumSize has been invoked with a non-null value.
119boolean isOpaque()Returns true if this component is completely opaque, returns false by default.
120boolean isPreferredSizeSet()Returns true if the preferred size has been set to a non-null value otherwise returns false.
121boolean isShowing()Determines whether this component is showing on screen.
122boolean isValid()Determines whether this component is valid.
123boolean isVisible()Determines whether this component should be visible when its parent is visible.
124boolean keyDown(Event evt,int key)Deprecated. As of JDK version 1.1, replaced by processKeyEvent(KeyEvent).
125boolean keyUp(Event evt,int key)Deprecated. As of JDK version 1.1, replaced by processKeyEvent(KeyEvent).
126void layout()Deprecated. As of JDK version 1.1, replaced by doLayout().
127void list()Prints a listing of this component to the standard system output stream System.out.
128void list(PrintStream out)Prints a listing of this component to the specified output stream.
129void list(PrintStream out,int indent)Prints out a list, starting at the specified indentation, to the specified print stream.
130void list(PrintWriter out)Prints a listing to the specified print writer.
131void list(PrintWriter out,int indent)Prints out a list, starting at the specified indentation, to the specified print writer.
132Component locate(int x,int y)Deprecated. As of JDK version 1.1, replaced by getComponentAt(int, int).
133Point location()Deprecated. As of JDK version 1.1, replaced by getLocation().
134boolean lostFocus(Event evt, Object what)Deprecated. As of JDK version 1.1, replaced by processFocusEvent(FocusEvent).
135boolean mouseDown(Event evt,int x,int y)Deprecated. As of JDK version 1.1, replaced by processMouseEvent(MouseEvent).
136boolean mouseDrag(Event evt,int x,int y)Deprecated. As of JDK version 1.1, replaced by processMouseMotionEvent(MouseEvent).
137boolean mouseEnter(Event evt,int x,int y)Deprecated. As of JDK version 1.1, replaced by processMouseEvent(MouseEvent).
138boolean mouseExit(Event evt,int x,int y)Deprecated. As of JDK version 1.1, replaced by processMouseEvent(MouseEvent).
139boolean mouseMove(Event evt,int x,int y)Deprecated. As of JDK version 1.1, replaced by processMouseMotionEvent(MouseEvent).
140boolean mouseUp(Event evt,int x,int y)Deprecated. As of JDK version 1.1, replaced by processMouseEvent(MouseEvent).
141void move(int x,int y)Deprecated. As of JDK version 1.1, replaced by setLocation(int, int).
142void nextFocus()Deprecated. As of JDK version 1.1, replaced by transferFocus().
143void paint(Graphics g)Paints this component.
144void paintAll(Graphics g)Paints this component and all of its subcomponents.
145boolean postEvent(Event e)Deprecated. As of JDK version 1.1, replaced by dispatchEvent(AWTEvent).
146boolean prepareImage(Image image,int width,int height, ImageObserver observer)Prepares an image for rendering on this component at the specified width and height.
147void print(Graphics g)Prints this component.
148void printAll(Graphics g)Prints this component and all of its subcomponents.
149protectedvoid processComponentEvent(ComponentEvent e)Processes component events occurring on this component by dispatching them to any registered ComponentListener objects.
150protected void processEvent(AWTEvent e)Processes events occurring on this component.
151protected void processFocusEvent(FocusEvent e)Processes focus events occurring on this component by dispatching them to any registered FocusListener objects.
152protected void processHierarchyBoundsEvent(HierarchyEvent e)Processes hierarchy bounds events occurring on this component by dispatching them to any registered HierarchyBoundsListener objects.
153protected void processHierarchyEvent(HierarchyEvent e)Processes hierarchy events occurring on this component by dispatching them to any registered HierarchyListener objects.
154protectedvoid processInputMethodEvent(InputMethodEvent e)Processes input method events occurring on this component by dispatching them to any registered InputMethodListener objects.
155protected void processKeyEvent(KeyEvent e)Processes key events occurring on this component by dispatching them to any registered KeyListener objects.
156protected void processMouseEvent(MouseEvent e)Processes mouse events occurring on this component by dispatching them to any registered MouseListener objects.
157protected void processMouseMotionEvent(MouseEvent e)Processes mouse motion events occurring on this component by dispatching them to any registered MouseMotionListener objects.
158protected void processMouseWheelEvent(MouseWheelEvent e)Processes mouse wheel events occurring on this component by dispatching them to any registered MouseWheelListener objects.
159void remove(MenuComponent popup)Removes the specified popup menu from the component.
160void removeComponentListener(ComponentListener l)Removes the specified component listener so that it no longer receives component events from this component.
161void removeFocusListener(FocusListener l)Removes the specified focus listener so that it no longer receives focus events from this component.
162void removeHierarchyBoundsListener(HierarchyBoundsListener l)Removes the specified hierarchy bounds listener so that it no longer receives hierarchy bounds events from this component.
163void removeHierarchyListener(HierarchyListener l)Removes the specified hierarchy listener so that it no longer receives hierarchy changed events from this component.
164void removeInputMethodListener(InputMethodListener l)Removes the specified input method listener so that it no longer receives input method events from this component.
165void removeKeyListener(KeyListener l)Removes the specified key listener so that it no longer receives key events from this component.
166void removeMouseListener(MouseListener l)Removes the specified mouse listener so that it no longer receives mouse events from this component.
167void removeMouseMotionListener(MouseMotionListener l)Removes the specified mouse motion listener so that it no longer receives mouse motion events from this component.
168void removeMouseWheelListener(MouseWheelListener l)Removes the specified mouse wheel listener so that it no longer receives mouse wheel events from this component.
169void removeNotify()Makes this component undisplayable by destroying its native screen resource.
170void removePropertyChangeListener(PropertyChangeListener listener)Removes a PropertyChangeListener from the listener list.
171void removePropertyChangeListener(String propertyName, PropertyChangeListener listener)Removes a PropertyChangeListener from the listener list for a specific property.
172void repaint()Repaints this component.
173void repaint(int x,int y,int width,int height)Repaints the specified rectangle of this component.
174void repaint(long tm)Repaints the component.
175void repaint(long tm,int x,int y,int width,int height)Repaints the specified rectangle of this component within tm milliseconds.
176void requestFocus()Requests that this component get the input focus, and that this component’s top-level ancestor become the focused Window.
177protected boolean requestFocus(boolean temporary)Requests that this component get the input focus, and that this component’s top-level ancestor become the focused Window.
178boolean requestFocusInWindow()Requests that this component get the input focus, if this component’s top-level ancestor is already the focused Window.
179protected boolean requestFocusInWindow(boolean temporary)Requests that this component get the input focus, if this component’s top-level ancestor is already the focused Window.
180void reshape(int x,int y,int width,int height)Deprecated. As of JDK version 1.1, replaced by setBounds(int, int, int, int).
181void resize(Dimension d)Deprecated. As of JDK version 1.1, replaced by setSize(Dimension).
182void resize(int width,int height)Deprecated. As of JDK version 1.1, replaced by setSize(int, int).
183void setBackground(Color c)Sets the background color of this component.
184void setBounds(int x,int y,int width,int height)Moves and resizes this component.
185void setBounds(Rectangle r)Moves and resizes this component to conform to the new bounding rectangle r.
186void setComponentOrientation(ComponentOrientation o)Sets the language-sensitive orientation that is to be used to order the elements or text within this component.
187void setCursor(Cursor cursor)Sets the cursor image to the specified cursor.
188void setDropTarget(DropTarget dt)Associate a DropTarget with this component.
189void setEnabled(boolean b)Enables or disables this component, depending on the value of the parameter b.
190void setFocusable(boolean focusable)Sets the focusable state of this Component to the specified value.
191void setFocusTraversalKeys(int id, Set<? extends AWTKeyStroke> keystrokes)Sets the focus traversal keys for a given traversal operation for this Component.
192void setFocusTraversalKeysEnabled(boolean focusTraversalKeysEnabled)Sets whether focus traversal keys are enabled for this component.
193void setFont(Font f)Sets the font of this component.
194void setForeground(Color c)Sets the foreground color of this component.
195void setIgnoreRepaint(boolean ignoreRepaint)Sets whether or not paint messages received from the operating system should be ignored.
196void setLocale(Locale l)Sets the locale of this component.
197void setLocation(int x,int y)Moves this component to a new location.
198void setLocation(Point p)Moves this component to a new location.
199void setMaximumSize(Dimension maximumSize)Sets the maximum size of this component to a constant value.
200void setMinimumSize(Dimension minimumSize)Sets the minimum size of this component to a constant value.
201void setName(String name)Sets the name of the component to the specified string.
202void setPreferredSize(Dimension preferredSize)Sets the preferred size of this component to a constant value.
203void setSize(Dimension d)Resizes this component so that it has width d.width and height d.height.
204void setSize(int width,int height)Resizes this component so that it has width width and height height.
205void setVisible(boolean b)Shows or hides this component depending on the value of parameter b.
206void show()Deprecated. As of JDK version 1.1, replaced by setVisible(boolean).
207void show(boolean b)Deprecated. As of JDK version 1.1, replaced by setVisible(boolean).
208Dimension size()Deprecated. As of JDK version 1.1, replaced by getSize().
209String toString()Returns a string representation of this component and its values.
210void transferFocus()Transfers the focus to the next component, as though this Component were the focus owner.
211void transferFocusBackward()Transfers the focus to the previous component, as though this Component were the focus owner.
212void transferFocusUpCycle()Transfers the focus up one focus traversal cycle.
213void update(Graphics g)Updates this component.
214void validate()Ensures that this component has a valid layout.
215Rectangle bounds()Deprecated. As of JDK version 1.1, replaced by getBounds().
216protected AWTEvent coalesceEvents(AWTEvent existingEvent, AWTEvent newEvent)Potentially coalesce an event being posted with an existing event.
217protected String paramString()Returns a string representing the state of this component.
218protected void firePropertyChange(String propertyName,int oldValue,int newValue)Supports reporting bound property changes for integer properties.
219Dimension preferredSize()Deprecated. As of JDK version 1.1, replaced by getPreferredSize().
220boolean prepareImage(Image image, ImageObserver observer)Prepares an image for rendering on this component.
221Dimension minimumSize()Deprecated. As of JDK version 1.1, replaced by getMinimumSize().
# Methods Inherited
  • java.lang.Object

SWING: PaintEvent Class Cheat Sheet

Following is the declaration for java.awt.event.PaintEvent class

public class PaintEvent
   extends ComponentEvent
# Field

Following are the fields for java.awt.Component class

  • static int PAINT − The paint event type.
  • static int PAINT_FIRST − Marks the first integer ID for the range of paint event IDs.
  • static int PAINT_LAST − Marks the last integer ID for the range of paint event IDs.
  • static int UPDATE − The update event type.
# Constructors
PaintEvent(Component source, int id, Rectangle updateRect)Constructs a PaintEvent object with the specified source component and type.

Class Methods

Rectangle getUpdateRect()Returns the rectangle representing the area that needs to be repainted in response to this event.
String paramString()Returns a parameter string identifying this event.
void setUpdateRect(Rectangle updateRect)Sets the rectangle representing the area that needs to be repainted in response to this event.
# Methods Inherited
  • java.awt.ComponentEvent
  • java.awt.AWTEvent
  • java.util.EventObject
  • java.lang.Object

SWING: MouseMotionEvent Class Cheat Sheet

Following is the declaration for java.awt.event.MouseMotionEvent Class −

public class MouseMotionEvent
   extends InputEvent
# Methods
void mouseDragged(MouseEvent e)Invoked when a mouse button is pressed on a component and then dragged.
void mouseMoved(MouseEvent e)Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.
# Methods Inherited
  • java.awt.event.InputEvent
  • java.awt.event.ComponentEvent
  • java.awt.AWTEvent
  • java.util.EventObject
  • java.lang.Object

SWING: ContainerEvent Class Cheat Sheet

Following is the declaration for java.awt.event.ContainerEvent class

public class ContainerEvent
   extends ComponentEvent
# Field

Following are the fields for java.awt.Component class

  • static int COMPONENT_ADDED − This event indicates that a component was added to the container.
  • static int COMPONENT_REMOVED − This event indicates that a component was removed from the container.
  • static int CONTAINER_FIRST − The first number in the range of IDs used for container events.
  • static int CONTAINER_LAST − The last number in the range of IDs used for container events.
# Constructors
ContainerEvent(Component source, int id, Component child)Constructs a ContainerEvent object.
# Methods
Component getChild()Returns the component that was affected by the event.
Container getContainer()Returns the originator of the event.
String paramString()Returns a parameter string identifying this event.
# Methods Inherited
  • java.awt.ComponentEvent
  • java.awt.AWTEvent
  • java.util.EventObject
  • java.lang.Object

SWING: ComponentEvent Class Cheat Sheet

Following is the declaration for java.awt.event.ComponentEvent class

public class ComponentEvent
   extends AWTEvent
# Field

Following are the fields for java.awt.Component class

  • static int COMPONENT_FIRST − The first number in the range of IDs used for component events.
  • static int COMPONENT_HIDDEN − This event indicates that the component was rendered invisible.
  • static int COMPONENT_LAST − The last number in the range of IDs used for component events.
  • static int COMPONENT_MOVED − This event indicates that the component’s position has changed.
  • static int COMPONENT_RESIZED − This event indicates that the component’s size has changed.
  • static int COMPONENT_SHOWN − This event indicates that the component was made visible.
# Constructors
ComponentEvent(Component source, int id)Constructs a ComponentEvent object.
# Methods
Component getComponent()Returns the originator of the event.
String paramString()Returns a parameter string identifying this event.
# Methods Inherited
  • java.awt.AWTEvent
  • java.util.EventObject
  • java.lang.Object

SWING: AdjustmentEvent Class Cheat Sheet

Following is the declaration for java.awt.event.AdjustmentEvent class

public class AdjustmentEvent
   extends AWTEvent
# Field

Following are the fields for java.awt.Component class

  • static int ADJUSTMENT_FIRST − Marks the first integer ID for the range of adjustment event IDs.
  • static int ADJUSTMENT_LAST − Marks the last integer ID for the range of adjustment event IDs.
  • static int ADJUSTMENT_VALUE_CHANGED − The adjustment value changed event.
  • static int BLOCK_DECREMENT − The block decrement adjustment type.
  • static int BLOCK_INCREMENT − The block increment adjustment type.
  • static int TRACK − The absolute tracking adjustment type.
  • static int UNIT_DECREMENT − The unit decrement adjustment type.
  • static int UNIT_INCREMENT − The unit increment adjustment type.
# Constructors
AdjustmentEvent(Adjustable source, int id, int type, int value)Constructs an AdjustmentEvent object with the specified Adjustable source, event type, adjustment type, and value.
AdjustmentEvent(Adjustable source, int id, int type, int value, boolean isAdjusting)Constructs an AdjustmentEvent object with the specified Adjustable source, event type, adjustment type, and value.
# Methods
Adjustable getAdjustable()Returns the Adjustable object where this event originated.
int getAdjustmentType()Returns the type of adjustment which caused the value changed event.
int getValue()Returns the current value in the adjustment event.
boolean getValueIsAdjusting()Returns true if this is one of the multiple adjustment events.
String paramString()Returns a string representing the state of this Event.
# Methods Inherited
  • java.awt.AWTEvent
  • java.util.EventObject
  • java.lang.Object

SWING: WindowEvent Class Cheat Sheet

Following is the declaration for java.awt.event.WindowEvent class

public class WindowEvent
   extends ComponentEvent
# Field

Following are the fields for java.awt.event.WindowEvent class

  • static int WINDOW_ACTIVATED − The window-activated event type.
  • static int WINDOW_CLOSED − The window closed the event.
  • static int WINDOW_CLOSING − The “window is closing” event.
  • static int WINDOW_DEACTIVATED − The window-deactivated event type.
  • static int WINDOW_DEICONIFIED − The window iconified event type.
  • static int WINDOW_FIRST − The first number in the range of IDs used for window events.
  • static int WINDOW_GAINED_FOCUS − The window-gained-focus event type.
  • static int WINDOW_ICONIFIED − The window iconified event.
  • static int WINDOW_LAST − The last number in the range of IDs used for window events.
  • static int WINDOW_LOST_FOCUS − The window-lost-focus event type.
  • static int WINDOW_OPENED − The window opened the event.
  • static int WINDOW_STATE_CHANGED − The window-state-changed event type.
# Constructors
WindowEvent(Window source, int id)Constructs a WindowEvent object.
WindowEvent(Window source, int id, int oldState, int newState)Constructs a WindowEvent object with the specified previous and new window states.
WindowEvent(Window source, int id, Window opposite)Constructs a WindowEvent object with the specified opposite Window.
WindowEvent(Window source, int id, Window opposite, int oldState, int newState)Constructs a WindowEvent object.
# Methods
int getNewState()For WINDOW_STATE_CHANGED events returns the new state of the window.
int getOldState()For WINDOW_STATE_CHANGED events returns the previous state of the window.
Window getOppositeWindow()Returns the other Window involved in this focus or activation change.
Window getWindow()Returns the originator of the event.
String paramString()Returns a parameter string identifying this event.
# Methods Inherited
  • java.awt.event.ComponentEvent
  • java.awt.AWTEvent
  • java.util.EventObject
  • java.lang.Object

SWING: MouseEvent Class Cheat Sheet

Following is the declaration for java.awt.event.MouseEvent class −

public class MouseEvent
   extends InputEvent
# Field

Following are the fields for java.awt.event.MouseEvent class

  • static int BUTTON1 − Indicates mouse button #1; used by getButton()
  • static int MOUSE_CLICKED − The “mouse clicked” event
  • static int MOUSE_DRAGGED − The “mouse dragged” event
  • static int MOUSE_ENTERED − The “mouse entered” event
  • static int MOUSE_EXITED − The “mouse exited” event
  • static int MOUSE_FIRST − The first number in the range of IDs used for mouse events
  • static int MOUSE_LAST − The last number in the range of IDs used for mouse events
  • static int MOUSE_MOVED − The “mouse moved” event
  • static int MOUSE_PRESSED − The “mouse pressed” event
  • static int MOUSE_RELEASED − The “mouse released” event
  • static int MOUSE_WHEEL − The “mouse wheel” event
  • static int NOBUTTON − Indicates no mouse buttons; used by getButton()
  • static int VK_WINDOWS − Constant for the Microsoft Windows “Windows” key.
# Constructors
MouseEvent(Component source, int id, long when, int modifiers, int x, int y, int clickCount, boolean popupTrigger)Constructs a MouseEvent object with the specified source component, type, modifiers, coordinates, and click count.
MouseEvent(Component source, int id, long when, int modifiers, int x, int y, int clickCount, boolean popupTrigger, int button)Constructs a MouseEvent object with the specified source component, type, modifiers, coordinates, and click count.
MouseEvent(Component source, int id, long when, int modifiers, int x, int y, int xAbs, int yAbs, int clickCount, boolean popupTrigger, int button)Constructs a MouseEvent object with the specified source component, type, modifiers, coordinates, absolute coordinates, and click count.
# Methods
int getButton()Returns which, if any, of the mouse buttons has changed state.
int getClickCount()Returns the number of mouse clicks associated with this event.
Point getLocationOnScreen()Returns the absolute x, y position of the event.
static String getMouseModifiersText(int modifiers)Returns a String describing the modifier keys and mouse buttons that were down during the event, such as “Shift”, or “Ctrl+Shift”.
Point getPoint()Returns the x,y position of the event relative to the source component.
int getX()Returns the horizontal x position of the event relative to the source component.
int getXOnScreen()Returns the absolute horizontal x position of the event.
int getY()Returns the vertical y position of the event relative to the source component.
int getYOnScreen()Returns the absolute vertical y position of the event.
boolean isPopupTrigger()Returns whether or not this mouse event is the popup menu trigger event for the platform.
String paramString()Returns a parameter string identifying this event.
void translatePoint(int x, int y)Translates the event’s coordinates to a new position by adding specified x (horizontal) and y (vertical) offsets.
# Methods Inherited
  • java.awt.event.InputEvent
  • java.awt.event.ComponentEvent
  • java.awt.AWTEvent
  • java.util.EventObject
  • java.lang.Object

SWING: KeyEvent Class Cheat Sheet

Following is the declaration for java.awt.event.KeyEvent class −

public class KeyEvent
   extends InputEvent
# Field

Following are the fields for java.awt.InputEvent class

  • static char CHAR_UNDEFINED − KEY_PRESSED and KEY_RELEASED events that do not map to a valid Unicode character use this for the keyChar value.
  • static int KEY_FIRST − The first number in the range of IDs used for key events.
  • static int KEY_LAST − The last number in the range of IDs used for key events.
  • static int KEY_LOCATION_LEFT − A constant indicating that the key pressed or released is in the left key location (there is more than one possible location for this key).
  • static int KEY_LOCATION_NUMPAD − A constant indicating that the key event originated on the numeric keypad or with a virtual key corresponding to the numeric keypad.
  • static int KEY_LOCATION_RIGHT − A constant indicating that the key pressed or released is in the right key location (there is more than one possible location for this key).
  • static int KEY_LOCATION_STANDARD − A constant indicating that the key pressed or released is not distinguished as the left or right version of a key and did not originate on the numeric keypad (or did not originate with a virtual key corresponding to the numeric keypad).
  • static int KEY_LOCATION_UNKNOWN − A constant indicating that the keyLocation is indeterminate or not relevant.
  • static int KEY_PRESSED − The “key pressed” event.
  • static int KEY_RELEASED − The “key released” event.
  • static int KEY_TYPED − The “key typed” event.
  • static int VK_0 − VK_0 thru VK_9 are the same as ASCII ‘0’ thru ‘9’ (0×30 – 0×39)
  • static int VK_1
  • static int VK_2
  • static int VK_3
  • static int VK_4
  • static int VK_5
  • static int VK_6
  • static int VK_7
  • static int VK_8
  • static int VK_9
  • static int VK_A − VK_A thru VK_Z are the same as ASCII ‘A’ thru ‘Z’ (0×41 – 0×5A)
  • static int VK_ACCEPT − Constant for the Accept or Commit function key.
  • static int VK_ADD
  • static int VK_AGAIN
  • static int VK_ALL_CANDIDATES − Constant for the All Candidates function key.
  • static int VK_ALPHANUMERIC − Constant for the Alphanumeric function key.
  • static int VK_ALT
  • static int VK_ALT_GRAPH − Constant for the AltGraph function key.
  • static int VK_AMPERSAND
  • static int VK_ASTERISK
  • static int VK_AT − Constant for the “@” key.
  • static int VK_B
  • static int VK_BACK_QUOTE
  • static int VK_BACK_SLASH − Constant for the backslash key, “\”
  • static int VK_BACK_SPACE
  • static int VK_BEGIN − Constant for the Begin key.
  • static int VK_BRACELEFT
  • static int VK_BRACERIGHT
  • static int VK_C
  • static int VK_CANCEL
  • static int VK_CAPS_LOCK
  • static int VK_CIRCUMFLEX − Constant for the “^” key.
  • static int VK_CLEAR
  • static int VK_CLOSE_BRACKET − Constant for the close bracket key, “]”
  • static int VK_CODE_INPUT − Constant for the Code Input function key.
  • static int VK_COLON − Constant for the “:” key.
  • static int VK_COMMA − Constant for the comma key, “,”
  • static int VK_COMPOSE − Constant for the Compose function key.
  • static int VK_CONTEXT_MENU − Constant for the Microsoft Windows Context Menu key.
  • static int VK_CONTROL
  • static int VK_CONVERT − Constant for the Convert function key.
  • static int VK_COPY
  • static int VK_CUT
  • static int VK_D
  • static int VK_DEAD_ABOVEDOT
  • static int VK_DEAD_ABOVERING
  • static int VK_DEAD_ACUTE
  • static int VK_DEAD_BREVE
  • static int VK_DEAD_CARON
  • static int VK_DEAD_CEDILLA
  • static int VK_DEAD_CIRCUMFLEX
  • static int VK_DEAD_DIAERESIS
  • static int VK_DEAD_DOUBLEACUTE
  • static int VK_DEAD_GRAVE
  • static int VK_DEAD_IOTA
  • static int VK_DEAD_MACRON
  • static int VK_DEAD_OGONEK
  • static int VK_DEAD_SEMIVOICED_SOUND
  • static int VK_DEAD_TILDE
  • static int VK_DEAD_VOICED_SOUND
  • static int VK_DECIMAL
  • static int VK_DELETE
  • static int VK_DIVIDE
  • static int VK_DOLLAR − Constant for the “$” key.
  • static int VK_DOWN − Constant for the non-numpad down arrow key.
  • static int VK_E
  • static int VK_END
  • static int VK_ENTER
  • static int VK_EQUALS − Constant for the equals key, “=”
  • static int VK_ESCAPE
  • static int VK_EURO_SIGN − Constant for the Euro currency sign key.
  • static int VK_EXCLAMATION_MARK − Constant for the “!” key.
  • static int VK_F
  • static int VK_F1 − Constant for the F1 function key.
  • static int VK_F10 − Constant for the F10 function key.
  • static int VK_F20 − Constant for the F11 function key.
  • static int VK_FINAL
  • static int VK_FIND
  • static int VK_FULL_WIDTH − Constant for the Full-Width Characters function key.
  • static int VK_G
  • static int VK_GREATER
  • static int VK_H
  • static int VK_HALF_WIDTH − Constant for the Half-Width Characters function key.
  • static int VK_HELP
  • static int VK_HIRAGANA − Constant for the Hiragana function key.
  • static int VK_HOME
  • static int VK_I
  • static int VK_INPUT_METHOD_ON_OFF − Constant for the input method on/off-key.
  • static int VK_INSERT
  • static int VK_INVERTED_EXCLAMATION_MARK − Constant for the inverted exclamation mark key.
  • static int VK_J
  • static int VK_JAPANESE_HIRAGANA − Constant for the Japanese-Hiragana function key.
  • static int VK_JAPANESE_KATAKANA − Constant for the Japanese-Katakana function key.
  • static int VK_JAPANESE_ROMAN − Constant for the Japanese-Roman function key.
  • static int VK_K
  • static int VK_KANA
  • static int VK_KANA_LOCK − Constant for the locking Kana function key.
  • static int VK_KANJI
  • static int VK_KATAKANA − Constant for the Katakana function key.
  • static int VK_KP_DOWN − Constant for the numeric keypad down arrow key.
  • static int VK_KP_LEFT − Constant for the numeric keypad left arrow key.
  • static int VK_KP_RIGHT − Constant for the numeric keypad right arrow key.
  • static int VK_KP_UP − Constant for the numeric keypad up arrow key.
  • static int VK_L
  • static int VK_LEFT − Constant for the non-numpad left arrow key.
  • static int VK_LEFT_PARENTHESIS − Constant for the “(” key.
  • static int VK_LESS
  • static int VK_M
  • static int VK_META
  • static int VK_MINUS − Constant for the minus key, “-“
  • static int VK_MODECHANGE
  • static int VK_MULTIPLY
  • static int VK_N
  • static int VK_NONCONVERT − Constant for the Don’t Convert function key.
  • static int VK_NUM_LOCK
  • static int VK_NUMBER_SIGN − Constant for the “#” key.
  • static int VK_NUMPAD0
  • static int VK_NUMPAD1
  • static int VK_NUMPAD2
  • static int VK_NUMPAD3
  • static int VK_NUMPAD4
  • static int VK_NUMPAD5
  • static int VK_NUMPAD6
  • static int VK_NUMPAD7
  • static int VK_NUMPAD8
  • static int VK_NUMPAD9
  • static int VK_O
  • static int VK_OPEN_BRACKET − Constant for the open bracket key, “[“
  • static int VK_P
  • static int VK_PAGE_DOWN
  • static int VK_PAGE_UP
  • static int VK_PASTE
  • static int VK_PAUSE
  • static int VK_PERIOD − Constant for the period key, “.”
  • static int VK_PLUS − Constant for the “+” key.
  • static int VK_PREVIOUS_CANDIDATE − Constant for the Previous Candidate function key.
  • static int VK_PRINTSCREEN
  • static int VK_PROPS
  • static int VK_Q
  • static int VK_QUOTE
  • static int VK_QUOTEDBL
  • static int VK_R
  • static int VK_RIGHT − Constant for the non-numpad right arrow key.
  • static int VK_RIGHT_PARENTHESIS − Constant for the “)” key.
  • static int VK_ROMAN_CHARACTERS − Constant for the Roman Characters function key.
  • static int VK_S
  • static int VK_SCROLL_LOCK
  • static int VK_SEMICOLON − Constant for the semicolon key, “;”
  • static int VK_SEPARATER − This constant is obsolete and is included only for backwards compatibility.
  • static int VK_SEPARATOR − Constant for the Numpad Separator key.
  • static int VK_SHIFT
  • static int VK_SLASH − Constant for the forward-slash key, “/”
  • static int VK_SPACE
  • static int VK_STOP
  • static int VK_SUBTRACT
  • static int VK_T
  • static int VK_TAB
  • static int VK_U
  • static int VK_UNDEFINED − This value is used to indicate that the keyCode is unknown.
  • static int VK_UNDERSCORE − Constant for the “_” key.
  • static int VK_UNDO
  • static int VK_UP − Constant for the non-numpad up arrow key.
  • static int VK_V
  • static int VK_W
  • static int VK_WINDOWS − Constant for the Microsoft Windows “Windows” key.
  • static int VK_X
  • static int VK_Y
  • static int VK_Z
# Constructors
KeyEvent(Component source, int id, long when, int modifiers, int keyCode)Deprecated. as of JDK1.1
KeyEvent(Component source, int id, long when, int modifiers, int keyCode, char keyChar)Constructs a KeyEvent object.
KeyEvent(Component source, int id, long when, int modifiers, int keyCode, char keyChar, int keyLocation)
# Methods
char getKeyChar()Returns the character associated with the key in this event.
int getKeyCode()Returns the integer keyCode associated with the key in this event.
int getKeyLocation()Returns the location of the key that originated this key event.
static String getKeyModifiersText(int modifiers)Returns a String describing the modifier key(s), such as “Shift”, or “Ctrl+Shift”.
static String getKeyText(int keyCode)Returns a String describing the keyCode, such as “HOME”, “F1” or “A”.
boolean isActionKey()Returns whether the key in this event is an “action” key.
String paramString()Returns a parameter string identifying this event.
void setKeyChar(char keyChar)Set the keyChar value to indicate a logical character.
void setKeyCode(int keyCode)Set the keyCode value to indicate a physical key.
void setModifiers(int modifiers)Deprecated. as of JDK1.1.4
# Methods Inherited
  • java.awt.event.InputEvent
  • java.awt.event.ComponentEvent
  • java.awt.AWTEvent
  • java.util.EventObject
  • java.lang.Object

SWING: InputEvent Class Cheat Sheet

Following is the declaration for java.awt.event.InputEvent class

public abstract class InputEvent
   extends ComponentEvent
# Field

Following are the fields for java.awt.event.InputEvent class

  • static int ALT_DOWN_MASK − The Alt key extended modifier constant.
  • static int ALT_GRAPH_DOWN_MASK − The AltGraph key extended modifier constant.
  • static int ALT_GRAPH_MASK − The AltGraph key modifier is constant.
  • static int ALT_MASK − The Alt key modifier is constant.
  • static int BUTTON1_DOWN_MASK − The Mouse Button1 extended modifier constant.
  • static int BUTTON1_MASK − The Mouse Button1 modifier is constant.
  • static int BUTTON2_DOWN_MASK − The Mouse Button2 extended modifier constant.
  • static int BUTTON2_MASK − The Mouse Button2 modifier is constant.
  • static int BUTTON3_DOWN_MASK − The Mouse Button3 extended modifier constant.
  • static int BUTTON3_MASK −The Mouse Button3 modifier constant.
  • static int CTRL_DOWN_MASK − The Control key extended modifier constant.
  • static int CTRL_MASK − The Control key modifier constant.
  • static int META_DOWN_MASK − The Meta key extended modifier constant.
  • static int META_MASK − The Meta key modifier is constant.
  • static int SHIFT_DOWN_MASK − The Shift key extended modifier constant.
  • static int SHIFT_MASK − The Shift key modifier constant.
# Methods
void consume()Consumes this event so that it will not be processed in the default manner by the source which originated it.
int getModifiers()Returns the modifier mask for this event.
int getModifiersEx()Returns the extended modifier mask for this event.
static String getModifiersExText(int modifiers)Returns a String describing the extended modifier keys and mouse buttons, such as “Shift”, “Button1”, or “Ctrl+Shift”.
long getWhen()Returns the timestamp, when this event occurred.
boolean isAltDown()Returns whether or not the Alt modifier is down on this event.
boolean isAltGraphDown()Returns whether or not the AltGraph modifier is down on this event.
boolean isConsumed()Returns whether or not this event has been consumed.
boolean isControlDown()Returns whether or not the Control modifier is down on this event.
boolean isMetaDown()Returns whether or not the Meta modifier is down on this event.
boolean isShiftDown()Returns whether or not the Shift modifier is down on this event.
# Methods Inherited
  • java.awt.event.ComponentEvent
  • java.awt.AWTEvent
  • java.util.EventObject
  • java.lang.Object

SWING: ActionEvent Class Cheat Sheet

Following is the declaration for java.awt.event.ActionEvent class −

public class ActionEvent
   extends AWTEvent
# Field

Following are the fields for java.awt.event.ActionEvent class

  • static int ACTION_FIRST − The first number in the range of IDs used for action events.
  • static int ACTION_LAST − The last number in the range of IDs used for action events.
  • static int ACTION_PERFORMED − This event ID indicates that a meaningful action has occurred.
  • static int ALT_MASK − The alt modifier.
  • static int CTRL_MASK − The control modifier.
  • static int META_MASK − The meta modifier.
  • static int SHIFT_MASK − The shift modifier.
# Constructors
ActionEvent(java.lang.Object source, int id, java.lang.String command)Constructs an ActionEvent object.
ActionEvent(java.lang.Object source, int id, java.lang.String command, int modifiers)Constructs an ActionEvent object with modifier keys.
ActionEvent(java.lang.Object source, int id, java.lang.String command, long when, int modifiers)Constructs an ActionEvent object with the specified modifier keys and timestamp.
# Methods
java.lang.String getActionCommand()Returns the command string associated with this action.
int getModifiers()Returns the modifier keys held down during this action event.
long getWhen()Returns the timestamp of when this event occurred.
java.lang.String paramString()Returns a parameter string identifying this action event.
# Methods Inherited
  • java.awt.AWTEvent
  • java.util.EventObject
  • java.lang.Object

SWING: SWING – AWTEvent Class Cheat Sheet

Following is the declaration for java.awt.AWTEvent class

public class AWTEvent
   extends EventObject
# Field

Following are the fields for java.awt.AWTEvent class

  • static int ACTION_FIRST − The first number in the range of IDs used for action events.
  • static long ACTION_EVENT_MASK − The event mask for selecting action events.
  • static long ADJUSTMENT_EVENT_MASK − The event mask for selecting adjustment events.
  • static long COMPONENT_EVENT_MASK − The event mask for selecting component events.
  • protected boolean consumed − Controls whether or not the event is sent back down to the peer once the source has processed it – false means it’s sent to the peer; true means it’s not.
  • static long CONTAINER_EVENT_MASK − The event mask for selecting container events.
  • static long FOCUS_EVENT_MASK − The event mask for selecting focus events.
  • static long HIERARCHY_BOUNDS_EVENT_MASK − The event mask for selecting hierarchy bounds events.
  • static long HIERARCHY_EVENT_MASK − The event mask for selecting hierarchy events.
  • protected int id − The event’s ID.
  • static long INPUT_METHOD_EVENT_MASK − The event mask for selecting input method events.
  • static long INVOCATION_EVENT_MASK − The event mask for selecting invocation events.
  • static long ITEM_EVENT_MASK − The event mask for selecting item events.
  • static long KEY_EVENT_MASK − The event mask for selecting key events.
  • static long MOUSE_EVENT_MASK − The event mask for selecting mouse events.
  • static long MOUSE_MOTION_EVENT_MASK − The event mask for selecting mouse motion events.
  • static long MOUSE_WHEEL_EVENT_MASK − The event mask for selecting mouse wheel events.
  • static long PAINT_EVENT_MASK − The event mask for selecting paint events.
  • static int RESERVED_ID_MAX − The maximum value for reserved SWING event IDs.
  • static long TEXT_EVENT_MASK − The event mask for selecting text events.
  • static long WINDOW_EVENT_MASK − The event mask for selecting window events.
  • static long WINDOW_FOCUS_EVENT_MASK − The event mask for selecting window focus events.
  • static long WINDOW_STATE_EVENT_MASK − The event mask for selecting window state events.
# Class Constructors
AWTEvent(Event event)Constructs an AWTEvent object from the parameters of a 1.0-style event.
AWTEvent(java.lang.Object source, int id)Constructs an AWTEvent object with the specified source object and type.
# Class Methods
protected void consume()Consumes this event, if this event can be consumed.
int getID()Returns the event type.
protected boolean isConsumed()Returns whether this event has been consumed.
java.lang.String paramString()Returns a string representing the state of this Event.
void setSource(java.lang.Object newSource)Retargets an event to a new source.
java.lang.String toString()Returns a String representation of this object.
# Methods Inherited
  • java.util.EventObject
  • java.lang.Object

SWING: FocusListener Interface Cheat Sheet

Following is the declaration for java.awt.event.FocusListener interface

public interface FocusListener
extends EventListener
# Methods
void focusGained(FocusEvent e)Invoked when a component gains the keyboard focus.
void focusLost(FocusEvent e)Invoked when a component loses the keyboard focus.
# Methods Inherited

java.awt.event.EventListener

# FocusListener Example

SwingListenerDemo.java

package com.simplecheatsheet.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingListenerDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;
   
   public SwingListenerDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingListenerDemo  swingListenerDemo = new SwingListenerDemo();  
      swingListenerDemo.showFocusListenerDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showFocusListenerDemo(){
      headerLabel.setText("Listener in action: FocusListener");      
      JButton okButton = new JButton("OK");
      JButton cancelButton = new JButton("Cancel");
   
      okButton.addFocusListener(new CustomFocusListener());  
      cancelButton.addFocusListener(new CustomFocusListener());  
   
      controlPanel.add(okButton);
      controlPanel.add(cancelButton);     
      mainFrame.setVisible(true);  
   }
   class CustomFocusListener implements FocusListener{
      public void focusGained(FocusEvent e) {
         statusLabel.setText(statusLabel.getText() 
            + e.getComponent().getClass().getSimpleName() + " gained focus. ");
      }
      public void focusLost(FocusEvent e) {
         statusLabel.setText(statusLabel.getText() 
            + e.getComponent().getClass().getSimpleName() + " lost focus. ");
      }
   }
}

SWING: MouseMotionListener Interface Cheat Sheet

Following is the declaration for java.awt.event.MouseMotionListener interface

public interface MouseMotionListener
extends EventListener

Interface Methods

void mouseDragged(MouseEvent e)Invoked when a mouse button is pressed on a component and then dragged.
void mouseMoved(MouseEvent e)Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.
# Methods Inherited

java.awt.event.EventListener

# MouseMotionListener Example

SwingListenerDemo.java

package com.simplecheatsheet.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingListenerDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingListenerDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingListenerDemo  swingListenerDemo = new SwingListenerDemo();  
      swingListenerDemo.showMouseMotionListenerDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showMouseMotionListenerDemo(){
      headerLabel.setText("Listener in action: MouseMotionListener");      

      JPanel panel = new JPanel();      
      panel.setBackground(Color.magenta);
      panel.setLayout(new FlowLayout());        
      panel.addMouseMotionListener(new CustomMouseMotionListener());
      
      JLabel msglabel 
         = new JLabel("Welcome to TutorialsPoint SWING Tutorial.",JLabel.CENTER);        
      
      panel.add(msglabel);
      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   }
   class CustomMouseMotionListener implements MouseMotionListener {
      public void mouseDragged(MouseEvent e) {
         statusLabel.setText("Mouse Dragged: ("+e.getX()+", "+e.getY() +")");
      }
      public void mouseMoved(MouseEvent e) {
         statusLabel.setText("Mouse Moved: ("+e.getX()+", "+e.getY() +")");
      }    
   }
}

SWING: ContainerListener Interface Cheat Sheet

Following is the declaration for java.awt.event.ContainerListener interface

public interface ContainerListener
extends EventListener
# Methods
void componentAdded(ContainerEvent e)Invoked when a component has been added to the container.
void componentRemoved(ContainerEvent e)Invoked when a component has been removed from the container.
# Methods Inherited
  • java.awt.event.EventListener
# ContainerListener Example

SwingListenerDemo.java

package com.simplecheatsheet.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingListenerDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingListenerDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingListenerDemo  swingListenerDemo = new SwingListenerDemo();  
      swingListenerDemo.showContainerListenerDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showContainerListenerDemo(){
      headerLabel.setText("Listener in action: ContainerListener");      

      JPanel panel = new JPanel();      
      panel.setBackground(Color.magenta);            
      panel.addContainerListener(new CustomContainerListener());  

      JLabel msglabel = new JLabel("Welcome to TutorialsPoint SWING Tutorial."
         ,JLabel.CENTER);        
      panel.add(msglabel);

      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   }
   
   class CustomContainerListener implements ContainerListener {
      public void componentAdded(ContainerEvent e) {
         statusLabel.setText(statusLabel.getText() 
            + e.getComponent().getClass().getSimpleName() + " added. ");
      }
      public void componentRemoved(ContainerEvent e) {
         statusLabel.setText(statusLabel.getText() 
            + e.getComponent().getClass().getSimpleName() + " removed. ");
      }
   }
}

SWING: AdjustmentListener Interface Cheat Sheet

Following is the declaration for java.awt.event.AdjustmentListener interface

public interface AdjustmentListener
   extends EventListener
# Methods
void adjustmentValueChanged(AdjustmentEvent e)Invoked when the value of the adjustable has changed.
# Methods Inherited

java.awt.event.EventListener

# AdjustmentListener Example

SwingListenerDemo.java

package com.simplecheatsheet.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingListenerDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingListenerDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingListenerDemo  swingListenerDemo = new SwingListenerDemo();  
      swingListenerDemo.showAdjustmentListenerDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showAdjustmentListenerDemo(){
      headerLabel.setText("Listener in action: AdjustmentListener");      

      JPanel panel = new JPanel();
      JScrollBar scrollbar = new JScrollBar();
      scrollbar.addAdjustmentListener(new CustomAdjustmentListener());

      panel.add(scrollbar);
      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   }
   class CustomAdjustmentListener implements AdjustmentListener {
      public void adjustmentValueChanged(AdjustmentEvent e) {
         statusLabel.setText("Adjustment value: "+Integer.toString(e.getValue()));
      }
   }
}

SWING: WindowListener Interface Cheat Sheet

Following is the declaration for java.awt.event.WindowListener interface

public interface WindowListener
   extends EventListener
# Methods
void windowActivated(WindowEvent e)Invoked when the Window is set to be the active Window.
void windowClosed(WindowEvent e)Invoked when a window has been closed as a result of calling dispose on the Window.
void windowClosing(WindowEvent e)Invoked when the user attempts to close the Window from the Window’s system menu.
void windowDeactivated(WindowEvent e)Invoked when a Window is no longer the active Window.
void windowDeiconified(WindowEvent e)Invoked when a Window is changed from a minimized to a normal state.
void windowIconified(WindowEvent e)Invoked when a Window is changed from a normal to a minimized state.
void windowOpened(WindowEvent e)Invoked the first time a Window is made visible.
# Methods Inherited

java.awt.EventListener

# WindowListener Example

SwingListenerDemo.java

package com.simplecheatsheet.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingListenerDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingListenerDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingListenerDemo  swingListenerDemo = new SwingListenerDemo();  
      swingListenerDemo.showWindowListenerDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showWindowListenerDemo(){
      headerLabel.setText("Listener in action: WindowListener");      
      JButton okButton = new JButton("OK");

      aboutFrame = new JFrame();
      aboutFrame.setSize(300,200);;
      aboutFrame.setTitle("WindowListener Demo");
      aboutFrame.addWindowListener(new CustomWindowListener());
      
      JPanel panel = new JPanel();      
      panel.setBackground(Color.white);            
      JLabel msglabel = new JLabel("Welcome to TutorialsPoint SWING Tutorial."
         ,JLabel.CENTER);        
      panel.add(msglabel);
      aboutFrame.add(panel);
      aboutFrame.setVisible(true); 
   }
   class CustomWindowListener implements WindowListener {
      public void windowOpened(WindowEvent e) {
      }
      public void windowClosing(WindowEvent e) {
         aboutFrame.dispose();
      }
      public void windowClosed(WindowEvent e) {
      }
      public void windowIconified(WindowEvent e) {
      }
      public void windowDeiconified(WindowEvent e) {
      }
      public void windowActivated(WindowEvent e) {
      }
      public void windowDeactivated(WindowEvent e) {
      }
   }   
}

SWING: MouseListener Interface Cheat Sheet

Following is the declaration for java.awt.event.MouseListener interface

public interface MouseListener
   extends EventListener
# Methods
void mouseClicked(MouseEvent e)Invoked when the mouse button has been clicked (pressed and released) on a component.
void mouseEntered(MouseEvent e)Invoked when the mouse enters a component.
void mouseExited(MouseEvent e)Invoked when the mouse exits a component.
void mousePressed(MouseEvent e)Invoked when a mouse button has been pressed on a component.
void mouseReleased(MouseEvent e)Invoked when a mouse button has been released on a component.
# Methods Inherited
  • java.awt.EventListener
# MouseListener Example

SwingListenerDemo.java

package com.simplecheatsheet.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingListenerDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingListenerDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingListenerDemo  swingListenerDemo = new SwingListenerDemo();  
      swingListenerDemo.showMouseListenerDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showMouseListenerDemo(){
      headerLabel.setText("Listener in action: MouseListener");      

      JPanel panel = new JPanel();      
      panel.setBackground(Color.magenta);
      panel.setLayout(new FlowLayout());        
      panel.addMouseListener(new CustomMouseListener());

      JLabel msglabel = 
      new JLabel("Welcome to TutorialsPoint SWING Tutorial.",JLabel.CENTER);        
      panel.add(msglabel);

      msglabel.addMouseListener(new CustomMouseListener());
      panel.add(msglabel);

      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   }
   class CustomMouseListener implements MouseListener {
      public void mouseClicked(MouseEvent e) {
         statusLabel.setText("Mouse Clicked: ("+e.getX()+", "+e.getY() +")");
      }
      public void mousePressed(MouseEvent e) {
      }
      public void mouseReleased(MouseEvent e) {
      }
      public void mouseEntered(MouseEvent e) {
      }
      public void mouseExited(MouseEvent e) {
      }
   }
}

SWING: KeyListener Interface Cheat Sheet

Following is the declaration for java.awt.event.KeyListener interface −

public interface KeyListener
   extends EventListener
# Methods
void keyPressed(KeyEvent e)Invoked when a key has been pressed.
void keyReleased(KeyEvent e)Invoked when a key has been released.
void keyTyped(KeyEvent e)Invoked when a key has been typed.
# Methods Inherited

java.awt.EventListener

# KeyListener Example

SwingListenerDemo.java

package com.simplecheatsheet.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingListenerDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingListenerDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingListenerDemo  swingListenerDemo = new SwingListenerDemo();  
      swingListenerDemo.showKeyListenerDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private JTextField textField;
   private void showKeyListenerDemo(){
      headerLabel.setText("Listener in action: KeyListener");      
      textField  = new JTextField(10);
      textField.addKeyListener(new CustomKeyListener());
      JButton okButton = new JButton("OK");
      
      okButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            statusLabel.setText("Entered text: " + textField.getText());                
         }
      });
      controlPanel.add(textField);
      controlPanel.add(okButton);    
      mainFrame.setVisible(true);  
   }
   class CustomKeyListener implements KeyListener{
      public void keyTyped(KeyEvent e) {
      }
      public void keyPressed(KeyEvent e) {
         if(e.getKeyCode() == KeyEvent.VK_ENTER){
            statusLabel.setText("Entered text: " + textField.getText());
         }
      }
      public void keyReleased(KeyEvent e) {
      }   
   }
}

SWING: ComponentListener Interface Cheat Sheet

Following is the declaration for java.awt.event.ComponentListener interface

public interface ComponentListener
   extends EventListener
# Methods
void componentHidden(ComponentEvent e)Invoked when the component has been made invisible.
void componentMoved(ComponentEvent e)Invoked when the component’s position changes.
void componentResized(ComponentEvent e)Invoked when the component’s size changes.
void componentShown(ComponentEvent e)Invoked when the component has been made visible.
# Methods Inherited

java.awt.EventListener

# ComponentListener Example

SwingListenerDemo.java

package com.simplecheatsheet.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingListenerDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingListenerDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingListenerDemo  swingListenerDemo = new SwingListenerDemo();  
      swingListenerDemo.showComponentListenerDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showComponentListenerDemo(){
      headerLabel.setText("Listener in action: ComponentListener");      
   
      JPanel panel = new JPanel();      
      panel.setBackground(Color.magenta);            

      JLabel msglabel = 
      new JLabel("Welcome to TutorialsPoint SWING Tutorial.",JLabel.CENTER);        
      panel.add(msglabel);
	
      msglabel.addComponentListener(new CustomComponentListener());      
      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   }
   class CustomComponentListener implements ComponentListener {
      public void componentResized(ComponentEvent e) {
         statusLabel.setText(statusLabel.getText() 
            + e.getComponent().getClass().getSimpleName() + " resized. ");
      }
      public void componentMoved(ComponentEvent e) {
         statusLabel.setText(statusLabel.getText() 
            + e.getComponent().getClass().getSimpleName() + " moved. ");
      }
      public void componentShown(ComponentEvent e) {
         statusLabel.setText(statusLabel.getText() 
            + e.getComponent().getClass().getSimpleName() + " shown. ");
      }
      public void componentHidden(ComponentEvent e) {
         statusLabel.setText(statusLabel.getText() 
            + e.getComponent().getClass().getSimpleName() + " hidden. ");
      }
   }
}

SWING: ActionListener Interface Cheat Sheet

Following is the declaration for java.awt.event.ActionListener interface

public interface ActionListener
   extends EventListener
# Methods
void actionPerformed(ActionEvent e)Invoked when an action occurs.
# Methods Inherited

java.awt.EventListener

# ActionListener Example

SwingListenerDemo.java

package com.simplecheatsheett.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingListenerDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingListenerDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingListenerDemo  swingListenerDemo = new SwingListenerDemo();  
      swingListenerDemo.showActionListenerDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());
      
      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showActionListenerDemo(){
      headerLabel.setText("Listener in action: ActionListener");      

      JPanel panel = new JPanel();      
      panel.setBackground(Color.magenta);            
      JButton okButton = new JButton("OK");

      okButton.addActionListener(new CustomActionListener());        
      panel.add(okButton);
      controlPanel.add(panel);
      mainFrame.setVisible(true); 
   }
   class CustomActionListener implements ActionListener{
      public void actionPerformed(ActionEvent e) {
         statusLabel.setText("Ok Button Clicked.");
      }
   }	
}

SWING: WindowAdapter Class Cheat Sheet

Following is the declaration for java.awt.event.WindowAdapter class

public abstract class WindowAdapter
   extends Object
      implements WindowListener, WindowStateListener, WindowFocusListener
# Class Constructors

WindowAdapter()

# Methods
void windowActivated(WindowEvent e)Invoked when a Window is activated.
void windowClosed(WindowEvent e)Invoked when a Window has been closed.
void windowClosing(WindowEvent e)Invoked when a Window is in the process of being closed.
void windowDeactivated(WindowEvent e)Invoked when a Window is de-activated.
void windowDeiconified(WindowEvent e)Invoked when a Window is de-iconified.
void windowGainedFocus(WindowEvent e)Invoked when the Window is set to be the focused Window, which means that the Window, or one of its subcomponents, will receive keyboard events.
void windowIconified(WindowEvent e)Invoked when a Window is iconified.
void windowLostFocus(WindowEvent e)Invoked when the Window is no longer the focused Window, which means that keyboard events will no longer be delivered to the Window or any of its subcomponents.
void windowOpened(WindowEvent e)Invoked when a Window has been opened.
void windowStateChanged(WindowEvent e)Invoked when a Window state is changed.
# Methods Inherited
  • java.lang.Object
# WindowAdapter Example

SwingAdapterDemo.java

package com.simplecheatsheet.gui;

import java.awt.*;
import java.awt.event.*;

public class SwingAdapterDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingAdapterDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingAdapterDemo  swingAdapterDemo = new SwingAdapterDemo();        
      swingAdapterDemo.showWindowAdapterDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showWindowAdapterDemo(){
      headerLabel.setText("Listener in action: WindowAdapter");      
      JButton okButton = new JButton("OK");
      final JFrame aboutFrame = new JFrame();
      aboutFrame.setSize(300,200);;
      aboutFrame.setTitle("WindowAdapter Demo");
      
      aboutFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            aboutFrame.dispose();
         }        
      });    
      JLabel msglabel 
         = new JLabel("Welcome to TutorialsPoint SWING Tutorial.",JLabel.CENTER);
	   aboutFrame.add(msgLabel);
      aboutFrame.setVisible(true);
   }
}

SWING: WindowAdapter Class Cheat Sheet

Following is the declaration for java.awt.event.WindowAdapter class

public abstract class WindowAdapter
   extends Object
      implements WindowListener, WindowStateListener, WindowFocusListener
# Constructors

WindowAdapter()

# Methods
void windowActivated(WindowEvent e)Invoked when a Window is activated.
void windowClosed(WindowEvent e)Invoked when a Window has been closed.
void windowClosing(WindowEvent e)Invoked when a Window is in the process of being closed.
void windowDeactivated(WindowEvent e)Invoked when a Window is de-activated.
void windowDeiconified(WindowEvent e)Invoked when a Window is de-iconified.
void windowGainedFocus(WindowEvent e)Invoked when the Window is set to be the focused Window, which means that the Window, or one of its subcomponents, will receive keyboard events.
void windowIconified(WindowEvent e)Invoked when a Window is iconified.
void windowLostFocus(WindowEvent e)Invoked when the Window is no longer the focused Window, which means that keyboard events will no longer be delivered to the Window or any of its subcomponents.
void windowOpened(WindowEvent e)Invoked when a Window has been opened.
void windowStateChanged(WindowEvent e)Invoked when a Window state is changed.
# Methods Inherited
  • java.lang.Object
# WindowAdapter Example

SwingAdapterDemo.java

package com.simplecheatsheet.gui;

import java.awt.*;
import java.awt.event.*;

public class SwingAdapterDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingAdapterDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingAdapterDemo  swingAdapterDemo = new SwingAdapterDemo();        
      swingAdapterDemo.showWindowAdapterDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showWindowAdapterDemo(){
      headerLabel.setText("Listener in action: WindowAdapter");      
      JButton okButton = new JButton("OK");
      final JFrame aboutFrame = new JFrame();
      aboutFrame.setSize(300,200);;
      aboutFrame.setTitle("WindowAdapter Demo");
      
      aboutFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            aboutFrame.dispose();
         }        
      });    
      JLabel msglabel 
         = new JLabel("Welcome to TutorialsPoint SWING Tutorial.",JLabel.CENTER);
	   aboutFrame.add(msgLabel);
      aboutFrame.setVisible(true);
   }
}

SWING: MouseMotionAdapter Class Cheat Sheet

Following is the declaration for java.awt.event.MouseMotionAdapter class

public abstract class MouseMotionAdapter
   extends Object
      implements MouseMotionListener
# Constructors

MouseMotionAdapter()

# Methods
void mouseDragged(MouseEvent e)Invoked when a mouse button is pressed on a component and then dragged.
void mouseMoved(MouseEvent e)Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.
# Methods Inherited
  • java.lang.Object
# MouseMotionAdapter Example

SwingAdapterDemo.java

package com.simplecheatsheet.gui;

import java.awt.*;
import java.awt.event.*;

public class SwingAdapterDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingAdapterDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingAdapterDemo  swingAdapterDemo = new SwingAdapterDemo();        
      swingAdapterDemo.showMouseMotionAdapterDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showMouseMotionAdapterDemo(){
      headerLabel.setText("Listener in action: MouseMotionAdapter");      
      JPanel panel = new JPanel();      
      panel.setBackground(Color.magenta);
      panel.setLayout(new FlowLayout());        
      
      panel.addMouseMotionListener(new MouseMotionAdapter(){
         public void mouseMoved(MouseEvent e) {
            statusLabel.setText("Mouse Moved: ("+e.getX()+", "+e.getY() +")");
         }                
      });
      JLabel msglabel 
         = new JLabel("Welcome to TutorialsPoint SWING Tutorial.",JLabel.CENTER);
      
      panel.add(msglabel);
      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   }
}

SWING: MouseAdapter Class Cheat Sheet

Following is the declaration for java.awt.event.MouseAdapter class

public abstract class MouseAdapter
   extends Object
      implements MouseListener, MouseWheelListener, MouseMotionListener
# Constructors

MouseAdapter()

# Methods
void mouseClicked(MouseEvent e)Invoked when the mouse button has been clicked (pressed and released) on a component.
void mouseDragged(MouseEvent e)Invoked when a mouse button is pressed on a component and then dragged.
void mouseEntered(MouseEvent e)Invoked when the mouse enters a component.
void mouseExited(MouseEvent e)Invoked when the mouse exits a component.
void mouseMoved(MouseEvent e)Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.
void mousePressed(MouseEvent e)Invoked when a mouse button has been pressed on a component.
void mouseReleased(MouseEvent e)Invoked when a mouse button has been released on a component.
void mouseWheelMoved(MouseWheelEvent e)Invoked when the mouse wheel is rotated.
# Methods Inherited
  • java.lang.Object
# MouseAdapter Example

SwingAdapterDemo.java

package com.simplecheatsheet.gui;

import java.awt.*;
import java.awt.event.*;

public class SwingAdapterDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingAdapterDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      AwtAdapterDemo  awtAdapterDemo = new AwtAdapterDemo();  
      swingAdapterDemo.showMouseAdapterDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showMouseAdapterDemo(){
      headerLabel.setText("Listener in action: MouseAdapter");      
      JPanel panel = new JPanel();      
      panel.setBackground(Color.magenta);
      panel.setLayout(new FlowLayout());        
      
      panel.addMouseListener(new MouseAdapter(){
         public void mouseClicked(MouseEvent e) {
            statusLabel.setText("Mouse Clicked: ("+e.getX()+", "+e.getY() +")");
         }                
      });
      JLabel msglabel 
         = new JLabel("Welcome to TutorialsPoint SWING Tutorial.",JLabel.CENTER);
      
      msglabel.addMouseListener(new MouseAdapter(){
         public void mouseClicked(MouseEvent e) {
            statusLabel.setText("Mouse Clicked: ("+e.getX()+", "+e.getY() +")");
         }                
      });
      panel.add(msglabel);
      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   }
}

SWING: KeyAdapter Class Cheat Sheet

Following is the declaration for java.awt.event.KeyAdapter class

public abstract class KeyAdapter
   extends Object
      implements KeyListener
# Constructors

KeyAdapter()

# Methods
void keyPressed(KeyEvent e)Invoked when a key has been pressed.
void keyReleased(KeyEvent e)Invoked when a key has been released.
void keyTyped(KeyEvent e)Invoked when a key has been typed.
# Methods Inherited
  • java.lang.Object
# KeyAdapter Example

SwingAdapterDemo.java

package com.simplecheatsheet.gui;

import java.awt.*;
import java.awt.event.*;

public class SwingAdapterDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingAdapterDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingAdapterDemo  swingAdapterDemo = new SwingAdapterDemo();        
      swingAdapterDemo.showKeyAdapterDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showKeyAdapterDemo(){
      headerLabel.setText("Listener in action: KeyAdapter");      
      final JTextField textField = new JTextField(10);
      
      textField.addKeyListener(new KeyAdapter() {
         public void keyPressed(KeyEvent e) {                
            if(e.getKeyCode() == KeyEvent.VK_ENTER){
               statusLabel.setText("Entered text: "+ textField.getText());
            }
         }        
      });
      JButton okButton = new JButton("OK");
      okButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            statusLabel.setText("Entered text: "+ textField.getText());                
         }
      });
      controlPanel.add(textField);
      controlPanel.add(okButton);    
      mainFrame.setVisible(true);  
   }
}

SWING: FocusAdapter Class Cheat Sheet

Following is the declaration for java.awt.event.FocusAdapter class

public abstract class FocusAdapter
   extends Object
      implements FocusListener
# Constructors

FocusAdapter()

# Methods
void focusGained(FocusEvent e)Invoked when a component gains the keyboard focus.
# Methods Inherited
  • java.lang.Object
# FocusAdapter Example

SwingAdapterDemo.java

package com.simplecheatsheet.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingAdapterDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingAdapterDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingAdapterDemo  swingAdapterDemo = new SwingAdapterDemo();        
      swingAdapterDemo.showFocusAdapterDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   
   private void showFocusAdapterDemo(){
      headerLabel.setText("Listener in action: FocusAdapter");      
      JButton okButton = new JButton("OK");
      JButton cancelButton = new JButton("Cancel");
      
      okButton.addFocusListener(new FocusAdapter() { 
         public void focusGained(FocusEvent e) {
            statusLabel.setText(statusLabel.getText() 
               + e.getComponent().getClass().getSimpleName() 
               + " gained focus. ");
         }
      });  
      cancelButton.addFocusListener(new FocusAdapter(){
         public void focusLost(FocusEvent e) {
            statusLabel.setText(statusLabel.getText() 
               + e.getComponent().getClass().getSimpleName() 
               + " lost focus. ");
         }
      });  
      controlPanel.add(okButton);
      controlPanel.add(cancelButton);     
      mainFrame.setVisible(true);  
   }
}

SWING: SpringLayout Class Cheat Sheet

Following is the declaration for javax.swing.SpringLayout class −

public class SpringLayout
   extends Object
      implements LayoutManager2

# Field

Following are the fields for javax.swing.SpringLayout class −

  • static String BASELINE − Specifies the baseline of a component.
  • static String EAST − Specifies the right edge of a component’s bounding rectangle.
  • static String HEIGHT − Specifies the height of a component’s bounding rectangle.
  • static String HORIZONTAL_CENTER − Specifies the horizontal center of a component’s bounding rectangle.
  • static String NORTH − Specifies the top edge of a component’s bounding rectangle.
  • static String SOUTH − Specifies the bottom edge of a component’s bounding rectangle.
  • static String VERTICAL_CENTER − Specifies the vertical center of a component’s bounding rectangle.
  • static String WEST − Specifies the left edge of a component’s bounding rectangle.
  • static String WIDTH − Specifies the width of a component’s bounding rectangle.

# Constructors

SpringLayout()Creates a new SpringLayout.

# Methods

void addLayoutComponent(Component component, Object constraints)If constraints are an instance of SpringLayout.Constraints associate the constraints with the specified component.
void addLayoutComponent(String name, Component c)It has no effect since this layout manager does not use a per-component string.
Spring getConstraint(String edgeName, Component c)Returns the spring controlling the distance between the specified edge of the component and the top or left edge of its parent.
SpringLayout.Constraints getConstraints(Component c)Returns the constraints for the specified component.
float getLayoutAlignmentX(Container p)Returns 0.5f (centered).
float getLayoutAlignmentY(Container p)Returns 0.5f (centered).
void invalidateLayout(Container p)Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.
void layoutContainer(Container parent)Lays out the specified container.
Dimension maximumLayoutSize(Container parent)Calculates the maximum size dimensions for the specified container, given the components it contains.
Dimension minimumLayoutSize(Container parent)Calculates the minimum size dimensions for the specified container, given the components it contains.
Dimension preferredLayoutSize(Container parent)Calculates the preferred size dimensions for the specified container, given the components it contains.
void putConstraint(String e1, Component c1, int pad, String e2, Component c2)Links edge e1 of component c1 to edge e2 of component c2, with a fixed distance between the edges.
void putConstraint(String e1, Component c1, Spring s, String e2, Component c2)Links edge e1 of component c1 to edge e2 of component c2.
void removeLayoutComponent(Component c)Removes the constraints associated with the specified component.

# Methods Inherited

  • java.lang.Object

# SpringLayout Example

SwingLayoutDemo.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingSpringLayout {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingSpringLayout(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingSpringLayout swingLayoutDemo = new SwingSpringLayout();  
      swingLayoutDemo.showSpringLayoutDemo();       
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });
		controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showSpringLayoutDemo(){
      headerLabel.setText("Layout in action: SpringLayout");   
      SpringLayout layout = new SpringLayout();

      JPanel panel = new JPanel();
      panel.setLayout(layout);
      JLabel label = new JLabel("Enter Name: ");
      JTextField textField = new JTextField("", 15);
      panel.add(label);
      panel.add(textField);

      layout.putConstraint(SpringLayout.WEST, label,5, SpringLayout.WEST, controlPanel);
      layout.putConstraint(SpringLayout.NORTH, label,5, SpringLayout.NORTH, controlPanel);
      layout.putConstraint(SpringLayout.WEST, textField,5, SpringLayout.EAST, label);
      layout.putConstraint(SpringLayout.NORTH, textField,5, SpringLayout.NORTH, 
         controlPanel);
      
      layout.putConstraint(SpringLayout.EAST, panel,5, SpringLayout.EAST, textField);
      layout.putConstraint(SpringLayout.SOUTH, panel,5, SpringLayout.SOUTH, textField);
      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   } 
}

SWING: GroupLayout Class Cheat Sheet

Following is the declaration for javax.swing.GroupLayout class −

public class GroupLayout
   extends Object
      implements LayoutManager2

# Field

Following are the fields for javax.swing.GroupLayout class

  • static int DEFAULT_SIZE − Indicates the size from the component or the gap should be used for a particular range value.
  • static int PREFERRED_SIZE − Indicates the preferred size from the component or the gap should be used for a particular range value.

# Constructors

GroupLayout(Container host)Creates a GroupLayout for the specified Container.

# Methods

void addLayoutComponent(Component component, Object constraints)Notification that a Component has been added to the parent container.
void addLayoutComponent(String name, Component component)Notification that a Component has been added to the parent container.
GroupLayout.ParallelGroup createBaselineGroup(boolean resizable, boolean anchorBaselineToTop)Creates and returns a ParallelGroup that aligns its elements along the baseline.
GroupLayout.ParallelGroup createParallelGroup()Creates and returns a ParallelGroup with an alignment of Alignment.LEADING.
GroupLayout.ParallelGroup createParallelGroup(GroupLayout.Alignment alignment)Creates and returns a ParallelGroup with the specified alignment.
GroupLayout.ParallelGroup createParallelGroup(GroupLayout.Alignment alignment, boolean resizable)Creates and returns a ParallelGroup with the specified alignment and resize behavior.
GroupLayout.SequentialGroup createSequentialGroup()Creates and returns a SequentialGroup.
boolean getAutoCreateContainerGaps()Returns true if the gaps between the container and the components that border the container are automatically created.
boolean getAutoCreateGaps()Returns true if the gaps between the components are automatically created.
boolean getHonorsVisibility()Returns whether the component visibility is considered when sizing and positioning the components.
float getLayoutAlignmentX(Container parent)Returns the alignment along the x-axis.
float getLayoutAlignmentY(Container parent)Returns the alignment along the y-axis.
LayoutStyle getLayoutStyle()Returns the LayoutStyle used for calculating the preferred gap between the components.
void invalidateLayout(Container parent)Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.
void layoutContainer(Container parent)Lays out the specified container.
void linkSize(Component... components)Forces the specified components to have the same size regardless of their preferred, minimum, or maximum sizes.
void linkSize(int axis, Component... components)Forces the specified components to have the same size along the specified axis regardless of their preferred, minimum, or maximum sizes.
Dimension maximumLayoutSize(Container parent)Returns the maximum size for the specified container.
Dimension minimumLayoutSize(Container parent)Returns the minimum size for the specified container.
Dimension preferredLayoutSize(Container parent)Returns the preferred size for the specified container.
void removeLayoutComponent(Component component)Notifies that a Component has been removed from the parent container.
void replace(Component existingComponent, Component newComponent)Replaces an existing component with a new one.
void setAutoCreateContainerGaps(boolean autoCreateContainerPadding)Sets whether a gap between the container and the components that touch the border of the container should automatically be created.
void setAutoCreateGaps(boolean autoCreatePadding)Sets whether a gap between the components should automatically be created.
void setHonorsVisibility(boolean honorsVisibility)Sets whether the component visibility is considered when sizing and positioning the components.
void setHonorsVisibility(Component component, Boolean honorsVisibility)Sets whether the component’s visibility is considered for sizing and positioning.
void setHorizontalGroup(GroupLayout.Group group)Sets the Group that positions and sizes the components along the horizontal axis.
void setLayoutStyle(LayoutStyle layoutStyle)Sets the LayoutStyle used to calculate the preferred gaps between the components.
void setVerticalGroup(GroupLayout.Group group)Sets the Group that positions and sizes the components along the vertical axis.
String toString()Returns a string representation of this GroupLayout.

# Methods Inherited

  • java.lang.Object

# GroupLayout Example

SwingLayoutDemo.java

package com.simplecheatsheet.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingLayoutDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;
   private JLabel msglabel;

   public SwingLayoutDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo();  
      swingLayoutDemo.showGroupLayoutDemo();       
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showGroupLayoutDemo(){
      headerLabel.setText("Layout in action: GroupLayout");      
      JPanel panel = new JPanel();
      
      // panel.setBackground(Color.darkGray);
      panel.setSize(200,200);
      GroupLayout layout = new GroupLayout(panel);
      layout.setAutoCreateGaps(true);
      layout.setAutoCreateContainerGaps(true);
      
      JButton btn1 = new JButton("Button 1");
      JButton btn2 = new JButton("Button 2");
      JButton btn3 = new JButton("Button 3");

      layout.setHorizontalGroup(layout.createSequentialGroup()
         .addComponent(btn1)
         .addGroup(layout.createSequentialGroup()
         .addGroup(layout.createParallelGroup(
         GroupLayout.Alignment.LEADING)
         .addComponent(btn2)
         .addComponent(btn3))));
   
      layout.setVerticalGroup(layout.createSequentialGroup()
         .addComponent(btn1)
         .addComponent(btn2)
         .addComponent(btn3));
      
      panel.setLayout(layout);        
      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   }
}

SWING: GridBagLayout Class Cheat Sheet

Following is the declaration for java.awt.GridBagLayout class −

public class GridBagLayout
   extends Object
      implements LayoutManager2, Serializable

# Field

Following are the fields for java.awt.GridBagLayout class −

  • static int DEFAULT_SIZE − Indicates the size from the component or the gap should be used for a particular range value.
  • static int PREFERRED_SIZE − Indicates the preferred size from the component or the gap should be used for a particular range value.

# Constructors

GridBagLayout()Creates a grid bag layout manager.

Class Methods

void addLayoutComponent(Component comp, Object constraints)Adds the specified component to the layout, using the specified constraints object.
void addLayoutComponent(String name, Component comp)Adds the specified component with the specified name to the layout.
protected void adjustForGravity(GridBagConstraints constraints, Rectangle r)Adjusts the x, y width and height fields to the correct values depending on the constraint geometry and pads.
protected void AdjustForGravity(GridBagConstraints constraints, Rectangle r)This method is obsolete and supplied for backward compatibility only; new code should call adjustForGravity instead.
protected void arrangeGrid(Container parent)Lays out the grid.
protected void ArrangeGrid(Container parent)This method is obsolete and supplied for backward compatibility only; new code should call arrangeGrid instead.
GridBagConstraints getConstraints(Component comp)Gets the constraints for the specified component.
float getLayoutAlignmentX(Container parent)Returns the alignment along the x-axis.
float getLayoutAlignmentY(Container parent)Returns the alignment along the y-axis.
int[][] getLayoutDimensions()Determines column widths and row heights for the layout grid.
protected java.awt.GridBagLayoutInfo getLayoutInfo(Container parent, int sizeflag)Fills in an instance of GridBagLayoutInfo for the current set of managed children.
protected java.awt.GridBagLayoutInfo GetLayoutInfo(Container parent, int sizeflag)This method is obsolete and supplied for backward compatibility only; new code should call getLayoutInfo instead.
Point getLayoutOrigin()Determines the origin of the layout area, in the graphics coordinate space of the target container.
double[][] getLayoutWeights()Determines the weights of the layout grid’s columns and rows.
protected Dimension getMinSize(Container parent, java.awt.GridBagLayoutInfo info)Figures out the minimum size of the master based on the information from getLayoutInfo().
protected Dimension GetMinSize(Container parent, java.awt.GridBagLayoutInfo info)This method is obsolete and supplied for backward compatibility only; new code should call getMinSize instead.
void invalidateLayout(Container target)Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.
void layoutContainer(Container parent)Lays out the specified container using this grid bag layout.
Point location(int x, int y)Determines which cell in the layout grid contains the point specified by (x, y).
protected GridBagConstraints lookupConstraints(Component comp)Retrieves the constraints for the specified component.
Dimension maximumLayoutSize(Container target)Returns the maximum dimensions for this layout given the components in the specified target container.
Dimension minimumLayoutSize(Container parent)Determines the minimum size of the parent container using this grid bag layout.
Dimension preferredLayoutSize(Container parent)Determines the preferred size of the parent container using this grid bag layout.
void removeLayoutComponent(Component comp)Removes the specified component from this layout.
void setConstraints(Component comp, GridBagConstraints constraints)Sets the constraints for the specified component in this layout.
String toString()Returns a string representation of this grid bag layout’s values.

# Methods Inherited

  • java.lang.Object

# GridBagLayout Example

SwingLayoutDemo.java

package com.simplecheatsheet.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingLayoutDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;
   private JLabel msglabel;

   public SwingLayoutDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo();  
      swingLayoutDemo.showGridBagLayoutDemo();       
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showGridBagLayoutDemo(){
      headerLabel.setText("Layout in action: GridBagLayout");      

      JPanel panel = new JPanel();
      panel.setBackground(Color.darkGray);
      panel.setSize(300,300);
      GridBagLayout layout = new GridBagLayout();

      panel.setLayout(layout);        
      GridBagConstraints gbc = new GridBagConstraints();

      gbc.fill = GridBagConstraints.HORIZONTAL;
      gbc.gridx = 0;
      gbc.gridy = 0;
      panel.add(new JButton("Button 1"),gbc);

      gbc.gridx = 1;
      gbc.gridy = 0;
      panel.add(new JButton("Button 2"),gbc); 

      gbc.fill = GridBagConstraints.HORIZONTAL;
      gbc.ipady = 20;   
      gbc.gridx = 0;
      gbc.gridy = 1;
      panel.add(new JButton("Button 3"),gbc); 

      gbc.gridx = 1;
      gbc.gridy = 1;       
      panel.add(new JButton("Button 4"),gbc);  

      gbc.gridx = 0;
      gbc.gridy = 2;      
      gbc.fill = GridBagConstraints.HORIZONTAL;
      gbc.gridwidth = 2;
      panel.add(new JButton("Button 5"),gbc);  

      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   }
}

SWING: GridLayout Class Cheat Sheet

Following is the declaration for java.awt.GridLayout class −

public class GridLayout
   extends Object
      implements LayoutManager, Serializable

# Constructors

GridLayout()Creates a grid layout with a default of one column per component, in a single row.
GridLayout(int rows, int cols)Creates a grid layout with the specified number of rows and columns.
GridLayout(int rows, int cols, int hgap, int vgap)Creates a grid layout with the specified number of rows and columns.

# Methods

void addLayoutComponent(String name, Component comp)Adds the specified component with the specified name to the layout.
int getColumns()Gets the number of columns in this layout.
int getHgap()Gets the horizontal gap between the components.
int getRows()Gets the number of rows in this layout.
int getVgap()Gets the vertical gap between the components.
void layoutContainer(Container parent)Lays out the specified container using this layout.
Dimension minimumLayoutSize(Container parent)Determines the minimum size of the container argument using this grid layout.
Dimension preferredLayoutSize(Container parent)Determines the preferred size of the container argument using this grid layout.
void removeLayoutComponent(Component comp)Removes the specified component from the layout.
void setColumns(int cols)Sets the number of columns in this layout to the specified value.
void setHgap(int hgap)Sets the horizontal gap between the components to the specified value.
void setRows(int rows)Sets the number of rows in this layout to the specified value.
void setVgap(int vgap)Sets the vertical gap between the components to the specified value.
String toString()Returns the string representation of this grid layout’s values.

# Methods Inherited

  • java.lang.Object

# GridLayout Example

SwingLayoutDemo.java

package com.simplecheatsheet.gui;

import javax.swing.*;

public class SwingLayoutDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;
   private JLabel msglabel;
   
   public SwingLayoutDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo();  
      swingLayoutDemo.showGridLayoutDemo();       
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showGridLayoutDemo(){
      headerLabel.setText("Layout in action: GridLayout");      
      
      JPanel panel = new JPanel();
      panel.setBackground(Color.darkGray);
      panel.setSize(300,300);
      GridLayout layout = new GridLayout(0,3);
      layout.setHgap(10);
      layout.setVgap(10);
      
      panel.setLayout(layout);        
      panel.add(new JButton("Button 1"));
      panel.add(new JButton("Button 2")); 
      panel.add(new JButton("Button 3")); 
      panel.add(new JButton("Button 4")); 
      panel.add(new JButton("Button 5")); 
      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   }
}

SWING: FlowLayout Class Cheat Sheet

Following is the declaration for java.awt.FlowLayout class −

public class FlowLayout
   extends Object
      implements LayoutManager, Serializable

# Field

Following are the fields for java.awt.BorderLayout class

  • static int CENTER − This value indicates that each row of components should be centered.
  • static int LEADING − This value indicates that each row of components should be justified to the leading edge of the container’s orientation. For example, to the left in left-to-right orientations.
  • static int LEFT − This value indicates that each row of components should be left-justified.
  • static int RIGHT − This value indicates that each row of components should be right-justified.
  • static int TRAILING − This value indicates that each row of components should be justified to the trailing edge of the container’s orientation. For example, to the right in left-to-right orientations.

# Constructors

FlowLayout()Constructs a new FlowLayout with a centered alignment and a default 5-unit horizontal and vertical gap.
FlowLayout(int align)Constructs a new FlowLayout with the specified alignment and a default 5-unit horizontal and vertical gap.
FlowLayout(int align, int hgap, int vgap)Creates a new flow layout manager with the indicated alignment and the indicated horizontal and vertical gaps.

# Methods

void addLayoutComponent(String name, Component comp)Adds the specified component to the layout.
int getAlignment()Gets the alignment for this layout.
int getHgap()Gets the horizontal gap between the components.
int getVgap()Gets the vertical gap between the components.
void layoutContainer(Container target)Lays out the container.
Dimension minimumLayoutSize(Container target)Returns the minimum dimensions needed to layout the visible components contained in the specified target container.
Dimension preferredLayoutSize(Container target)Returns the preferred dimensions for this layout given the visible components in the specified target container.
void removeLayoutComponent(Component comp)Removes the specified component from the layout.
void setAlignment(int align)Sets the alignment for this layout.
void setHgap(int hgap)Sets the horizontal gap between the components.
void setVgap(int vgap)Sets the vertical gap between the components.
String toString()Returns a string representation of this FlowLayout object and its values.

# Methods Inherited

  • java.lang.Object

# FlowLayout Example

SwingLayoutDemo.java

package com.simplecheatsheet.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingLayoutDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;
   private JLabel msglabel;

   public SwingLayoutDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo();  
      swingLayoutDemo.showFlowLayoutDemo();       
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showFlowLayoutDemo(){
      headerLabel.setText("Layout in action: FlowLayout");      

      JPanel panel = new JPanel();
      panel.setBackground(Color.darkGray);
      panel.setSize(200,200);
      FlowLayout layout = new FlowLayout();
      layout.setHgap(10);              
      layout.setVgap(10);
      
      panel.setLayout(layout);        
      panel.add(new JButton("OK"));
      panel.add(new JButton("Cancel"));       
      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   }
}

SWING: CardLayout Class Cheat Sheet

Following is the declaration for java.awt.CardLayout class

public class CardLayout
   extends Object
      implements LayoutManager2, Serializable

# Constructors

CardLayout()Creates a new card layout with the gaps of size zero.
CardLayout(int hgap, int vgap)Creates a new card layout with the specified horizontal and vertical gaps.

# Methods

void addLayoutComponent(Component comp, Object constraints)Adds the specified component to this card layout’s internal table of names.
void addLayoutComponent(String name, Component comp)If the layout manager uses a per-component string, adds the component comp to the layout, associating it with the string specified by name.
void first(Container parent)Flips to the first card of the container.
int getHgap()Gets the horizontal gap between the components.
float getLayoutAlignmentX(Container parent)Returns the alignment along the x axis.
float getLayoutAlignmentY(Container parent)Returns the alignment along the y-axis.
int getVgap()Gets the vertical gap between the components.
void invalidateLayout(Container target)Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.
void last(Container parent)Flips to the last card of the container.
void layoutContainer(Container parent)Lays out the specified container using this card layout.
Dimension maximumLayoutSize(Container target)Returns the maximum dimensions for this layout given the components in the specified target container.
Dimension minimumLayoutSize(Container parent)Calculates the minimum size for the specified panel.
void next(Container parent)Flips to the next card of the specified container.
Dimension preferredLayoutSize(Container parent)Determines the preferred size of the container argument using this card layout.
void previous(Container parent)Flips to the previous card of the specified container.
void removeLayoutComponent(Component comp)Removes the specified component from the layout.
void setHgap(int hgap)Sets the horizontal gap between the components.
void setVgap(int vgap)Sets the vertical gap between the components.
void show(Container parent, String name)Flips to the component that was added to this layout with the specified name, using addLayoutComponent.
String toString()Returns a string representation of the state of this card layout.

# Methods Inherited

  • java.lang.Object

# CardLayout Example

SwingLayoutDemo.java

package com.simplecheatsheet.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingLayoutDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;
   private JLabel msglabel;

   public SwingLayoutDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo();  
      swingLayoutDemo.showCardLayoutDemo();       
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      
      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showCardLayoutDemo(){
      headerLabel.setText("Layout in action: CardLayout");      

      final JPanel panel = new JPanel();
      panel.setBackground(Color.CYAN);
      panel.setSize(300,300);

      CardLayout layout = new CardLayout();
      layout.setHgap(10);
      layout.setVgap(10);
      panel.setLayout(layout);        
      
      JPanel buttonPanel = new JPanel(new FlowLayout());
      buttonPanel.add(new JButton("OK"));
      buttonPanel.add(new JButton("Cancel"));    

      JPanel textBoxPanel = new JPanel(new FlowLayout());
      textBoxPanel.add(new JLabel("Name:"));
      textBoxPanel.add(new JTextField(20));

      panel.add("Button", buttonPanel);
      panel.add("Text", textBoxPanel);
      final DefaultComboBoxModel panelName = new DefaultComboBoxModel();

      panelName.addElement("Button");
      panelName.addElement("Text");
      final JComboBox listCombo = new JComboBox(panelName);    
      
      listCombo.setSelectedIndex(0);
      JScrollPane listComboScrollPane = new JScrollPane(listCombo);    
      JButton showButton = new JButton("Show");

      showButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) { 
            String data = "";
            if (listCombo.getSelectedIndex() != -1) {  
               CardLayout cardLayout = (CardLayout)(panel.getLayout());
               cardLayout.show(panel, 
                  (String)listCombo.getItemAt(listCombo.getSelectedIndex()));            
            }              
            statusLabel.setText(data);
         }
      }); 
      controlPanel.add(listComboScrollPane);
      controlPanel.add(showButton);
      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   }
}

SWING: BorderLayout Class Cheat Sheet

Following is the declaration for java.awt.BorderLayout class

public class BorderLayout
   extends Object
      implements LayoutManager2, Serializable

Field

Following are the fields for java.awt.BorderLayout class −

static String AFTER_LAST_LINE − Synonym for PAGE_END.

static String AFTER_LINE_ENDS − Synonym for LINE_END.

static String BEFORE_FIRST_LINE − Synonym for PAGE_START.

static String BEFORE_LINE_BEGINS − Synonym for LINE_START.

static String CENTER − The center layout constraint (middle of the container).

static String EAST − The east layout constraint (right side of the container).

static String LINE_END − The component goes at the end of the line direction for the layout.

static String LINE_START − The component goes at the beginning of the line direction for the layout.

static String NORTH − The north layout constraint (top of the container).

static String PAGE_END − The component comes after the last line of the layout’s content.

static String PAGE_START − The component comes before the first line of the layout’s content.

static String SOUTH − The south layout constraint (bottom of the container).

static String WEST − The west layout constraint (left side of the container).

# Constructors

BorderLayout()Constructs a new border layout with no gaps between the components.
BorderLayout(int hgap, int vgap)Constructs a border layout with the specified gaps between the components.

# Methods

void addLayoutComponent(Component comp, Object constraints)Adds the specified component to the layout, using the specified constraint object.
void addLayoutComponent(String name, Component comp)If the layout manager uses a per-component string, adds the component comp to the layout, associating it with the string specified by name.
int getHgap()Returns the horizontal gap between the components.
float getLayoutAlignmentX(Container parent)Returns the alignment along the x-axis.
float getLayoutAlignmentY(Container parent)Returns the alignment along the y-axis.
int getVgap()Returns the vertical gap between the components.
void invalidateLayout(Container target)Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.
void layoutContainer(Container target)Lays out the container argument using this border layout.
Dimension maximumLayoutSize(Container target)Returns the maximum dimensions for this layout given the components in the specified target container.
Dimension minimumLayoutSize(Container target)Determines the minimum size of the target container using this layout manager.
Dimension preferredLayoutSize(Container target)Determines the preferred size of the target container using this layout manager, based on the components in the container.
void removeLayoutComponent(Component comp)Removes the specified component from this border layout.
void setHgap(int hgap)Sets the horizontal gap between the components.
void setVgap(int vgap)Sets the vertical gap between the components.
String toString()Returns a string representation of the state of this border layout.

# Methods Inherited

  • java.lang.Object

# BorderLayout Example

SwingLayoutDemo.java

package com.simplecheatsheet.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingLayoutDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;
   private JLabel msglabel;

   public SwingLayoutDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo();  
      swingLayoutDemo.showBorderLayoutDemo();       
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showBorderLayoutDemo(){
      headerLabel.setText("Layout in action: BorderLayout");      

      JPanel panel = new JPanel();
      panel.setBackground(Color.darkGray);
      panel.setSize(300,300);
      BorderLayout layout = new BorderLayout();
      layout.setHgap(10);
      layout.setVgap(10);
      
      panel.setLayout(layout);        
      panel.add(new JButton("Center"),BorderLayout.CENTER);
      panel.add(new JButton("Line Start"),BorderLayout.LINE_START); 
      panel.add(new JButton("Line End"),BorderLayout.LINE_END);
      panel.add(new JButton("East"),BorderLayout.EAST);   
      panel.add(new JButton("West"),BorderLayout.WEST); 
      panel.add(new JButton("North"),BorderLayout.NORTH); 
      panel.add(new JButton("South"),BorderLayout.SOUTH); 

      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   }
}

SWING: LayoutManager2 Interface Cheat Sheet

Following is the declaration for java.awt.LayoutManager2 interface

public interface LayoutManger2
   extends LayoutManager

# Methods

void addLayoutComponent(Component comp, Object constraints)Adds the specified component to the layout, using the specified constraint object.
float getLayoutAlignmentX(Container target)Returns the alignment along the x axis.
float getLayoutAlignmentY(Container target)Returns the alignment along the y axis.
void invalidateLayout(Container target)Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.
Dimension maximumLayoutSize(Container target)Calculates the maximum size dimensions for the specified container, given the components it contains.

SWING: LayoutManager Interface Cheat Sheet

Following is the declaration for java.awt.LayoutManager interface

public interface LayoutManager

# Methods

void addLayoutComponent(String name, Component comp)If the layout manager uses a per-component string, adds the component comp to the layout, associating it with the string specified by name.
void layoutContainer(Container parent)Lays out the specified container.
Dimension minimumLayoutSize(Container parent)Calculates the minimum size dimensions for the specified container, given the components it contains.
Dimension preferredLayoutSize(Container parent)Calculates the preferred size dimensions for the specified container, given the components it contains.
void removeLayoutComponent(Component comp)Removes the specified component from the layout.

SWING: JPopupMenu Class Cheat Sheet

Following is the declaration for javax.swing.JPopupMenu class

public class JPopupMenu
   extends JComponent
      implements Accessible, MenuElement

# Constructors

JPopupMenu()Constructs a JPopupMenu without an “invoker”.
JPopupMenu(String label)Constructs a JPopupMenu with the specified title.

# Methods

JMenuItem add(Action a)Appends a new menu item to the end of the menu which dispatches the specified Action object.
JMenuItem add(JMenuItem menuItem)Appends the specified menu item to the end of this menu.
JMenuItem add(String s)Creates a new menu item with the specified text and appends it to the end of this menu.
void addMenuKeyListener(MenuKeyListener l)Adds a MenuKeyListener to the popup menu.
void addPopupMenuListener(PopupMenuListener l)Adds a PopupMenu listener.
void addSeparator()Appends a new separator at the end of the menu.
protected PropertyChangeListener createActionChangeListener(JMenuItem b)Returns a properly configured PropertyChangeListener which updates the control as changes to the Action occur.
protected JMenuItem createActionComponent(Action a)Factory method which creates the JMenuItem for Actions added to the JPopupMenu.
protected void firePopupMenuCanceled()Notifies PopupMenuListeners that this popup menu is canceled.
protected void firePopupMenuWillBecomeInvisible()Notifies PopupMenuListeners that this popup menu will become invisible.
protected void firePopupMenuWillBecomeVisible()Notifies PopupMenuListeners that this popup menu will become visible.
AccessibleContext getAccessibleContext()Gets the AccessibleContext associated with this JPopupMenu.
Component getComponent()Returns this JPopupMenu component.
Component getComponentAtIndex(int i)Deprecated. Replaced by Container.getComponent(int)
int getComponentIndex(Component c)Returns the index of the specified component.
static boolean getDefaultLightWeightPopupEnabled()Gets the defaultLightWeightPopupEnabled property, which by default is true.
Component getInvoker()Returns the component which is the ‘invoker’ of this popup menu.
String getLabel()Returns the popup menu’s label.
Insets getMargin()Returns the margin, in pixels, between the popup menu’s border and its containers.
MenuKeyListener[]getMenuKeyListeners()Returns an array of all the MenuKeyListeners added to this JPopupMenu with addMenuKeyListener().
PopupMenuListener[] getPopupMenuListeners()Returns an array of all the PopupMenuListeners added to this JMenuItem with addPopupMenuListener().
SingleSelectionModel getSelectionModel()Returns the model object that handles single selections.
MenuElement[] getSubElements()Returns an array of MenuElements containing the submenu for this menu component.
PopupMenuUI getUI()Returns the look and feel (L&F) object that renders this component.
String getUIClassID()Returns the name of the L&F class that renders this component.
void insert(Action a, int index)Inserts a menu item for the specified Action object at a given position.
void insert(Component component, int index)Inserts the specified component into the menu at a given position.
boolean isBorderPainted()Checks whether the border should be painted.
boolean isLightWeightPopupEnabled()Gets the lightWeightPopupEnabled property.
boolean isPopupTrigger(MouseEvent e)Returns true if the MouseEvent is considered a popup trigger by the JPopupMenu’s currently installed UI.
boolean isVisible()Returns true if the popup menu is visible (currently being displayed).
void menuSelectionChanged(boolean isIncluded)Message when the menubar selection changes to activate or deactivate this menu.
void pack()Lays out the container so that it uses the minimum space needed to display its contents.
protected void paintBorder(Graphics g)Paints the popup menu’s border if the borderPainted property is true.
protected String paramString()Returns a string representation of this JPopupMenu.
protected void processFocusEvent(FocusEvent evt)Processes focus events occurring on this component by dispatching them to any registered FocusListener objects.
protected void processKeyEvent(KeyEvent evt)Processes keystroke events such as mnemonics and accelerators.
void processKeyEvent(KeyEvent e, MenuElement[] path, MenuSelectionManager manager)Processes a key event forwarded from the MenuSelectionManager and changes the menu selection, if necessary, by using MenuSelectionManager’s API.
void processMouseEvent(MouseEvent event, MenuElement[] path, MenuSelectionManager manager)This method is required to conform to the MenuElement interface, but it not implemented.
void remove(int pos)Removes the component at the specified index from this popup menu.
void removeMenuKeyListener(MenuKeyListener l)Removes a MenuKeyListener from the popup menu.
void removePopupMenuListener(PopupMenuListener l)Removes a PopupMenu listener.
void setBorderPainted(boolean b)Sets whether the border should be painted.
static void setDefaultLightWeightPopupEnabled(boolean aFlag)Sets the default value of the lightWeightPopupEnabled property.
void setInvoker(Component invoker)Sets the invoker of this popup menu the component in which the popup menu is to be displayed.
void setLabel(String label)Sets the popup menu’s label.
void setLightWeightPopupEnabled(boolean aFlag)Sets the value of the lightWeightPopupEnabled property, which by default is true.
void setLocation(int x, int y)Sets the location of the upper left corner of the popup menu using x, y coordinates.
void setPopupSize(Dimension d)Sets the size of the Popup window using a Dimension object.
void setPopupSize(int width, int height)Sets the size of the Popup window to the specified width and height.
void setSelected(Component sel)Sets the currently selected component, This will result in a change in the selection model.
void setSelectionModel(SingleSelectionModel model)Sets the model object to handle single selections.
void setUI(PopupMenuUI ui)Sets the L&F object that renders this component.
void setVisible(boolean b)Sets the visibility of the popup menu.
void show(Component invoker, int x, int y)Displays the popup menu at the position x,y in the coordinate space of the component invoker.
void updateUI()Resets the UI property to a value from the current look and feel.

# Methods Inherited

  • javax.swing.JComponent
  • java.awt.Container
  • java.awt.Component
  • java.lang.Object

# JPopupMenu Example

SwingMenuDemo.java

import java.awt.*;
import java.awt.event.*;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;

public class SwingJpopupMenu{
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel; 

   public SwingJpopupMenu(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingJpopupMenu  swingMenuDemo = new SwingJpopupMenu();     
      swingMenuDemo.showPopupMenuDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showPopupMenuDemo(){
      final JPopupMenu editMenu = new JPopupMenu("Edit"); 

      JMenuItem cutMenuItem = new JMenuItem("Cut");
      cutMenuItem.setActionCommand("Cut");

      JMenuItem copyMenuItem = new JMenuItem("Copy");
      copyMenuItem.setActionCommand("Copy");

      JMenuItem pasteMenuItem = new JMenuItem("Paste");
      pasteMenuItem.setActionCommand("Paste");

      MenuItemListener menuItemListener = new MenuItemListener();

      cutMenuItem.addActionListener(menuItemListener);
      copyMenuItem.addActionListener(menuItemListener);
      pasteMenuItem.addActionListener(menuItemListener);

      editMenu.add(cutMenuItem);
      editMenu.add(copyMenuItem);
      editMenu.add(pasteMenuItem);   

      mainFrame.addMouseListener(new MouseAdapter() {
         public void mouseClicked(MouseEvent e) {            
            editMenu.show(mainFrame, e.getX(), e.getY());
         }               
      });
      mainFrame.add(editMenu); 
      mainFrame.setVisible(true);
   }
   class MenuItemListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {            
         statusLabel.setText(e.getActionCommand() + " MenuItem clicked.");
      }    
   }   
}

SWING: JRadioButtonMenuItem Class Cheat Sheet

Following is the declaration for javax.swing.JRadioButtonMenuItem class

public class JRadioButtonMenuItem
   extends JMenuItem
      implements Accessible

# Constructors

JRadioButtonMenuItem()Creates a JRadioButtonMenuItem with no set text or icon.
JRadioButtonMenuItem(Action a)Creates a radio button menu item whose properties are taken from the Action supplied.
JRadioButtonMenuItem(Icon icon)Creates a JRadioButtonMenuItem with an icon.
JRadioButtonMenuItem(Icon icon, boolean selected)Creates a radio button menu item with the specified image and selection state, but no text.
JRadioButtonMenuItem(String text)Creates a JRadioButtonMenuItem with text.
JRadioButtonMenuItem(String text, boolean selected)Creates a radio button menu item with the specified text and selection state.
JRadioButtonMenuItem(String text, Icon icon)Creates a radio button menu item with the specified text and Icon.
JRadioButtonMenuItem(String text, Icon icon, boolean selected)Creates a radio button menu item with the specified text, image, and selection state.

# Methods

AccessibleContext getAccessibleContext()Gets the AccessibleContext associated with this JRadioButtonMenuItem.
String getUIClassID()Returns the name of the L&F class that renders this component.
protected String paramString()Returns a string representation of this JRadioButtonMenuItem.

# Methods Inherited

  • javax.swing.JMenuItem
  • javax.swing.JAbstractButton
  • javax.swing.JComponent
  • java.awt.Container
  • java.awt.Component
  • java.lang.Object

# JRadioButtonMenuItem Example

SwingMenuDemo.java

package com.simplecheatsheet.gui;

import java.awt.*;
import java.awt.event.*;

public class SwingMenuDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel; 

   public SwingMenuDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingMenuDemo swingMenuDemo = new SwingMenuDemo();     
      swingMenuDemo.showMenuDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showMenuDemo(){
      //create a menu bar
      final JMenuBar menuBar = new JMenuBar();

      //create menus
      JMenu fileMenu = new JMenu("File");
      JMenu editMenu = new JMenu("Edit"); 
      final JMenu aboutMenu = new JMenu("About");
      final JMenu linkMenu = new JMenu("Links");
     
      //create menu items
      JMenuItem newMenuItem = new JMenuItem("New");
      newMenuItem.setMnemonic(KeyEvent.VK_N);
      newMenuItem.setActionCommand("New");

      JMenuItem openMenuItem = new JMenuItem("Open");
      openMenuItem.setActionCommand("Open");

      JMenuItem saveMenuItem = new JMenuItem("Save");
      saveMenuItem.setActionCommand("Save");

      JMenuItem exitMenuItem = new JMenuItem("Exit");
      exitMenuItem.setActionCommand("Exit");

      JMenuItem cutMenuItem = new JMenuItem("Cut");
      cutMenuItem.setActionCommand("Cut");

      JMenuItem copyMenuItem = new JMenuItem("Copy");
      copyMenuItem.setActionCommand("Copy");

      JMenuItem pasteMenuItem = new JMenuItem("Paste");
      pasteMenuItem.setActionCommand("Paste");

      MenuItemListener menuItemListener = new MenuItemListener();

      newMenuItem.addActionListener(menuItemListener);
      openMenuItem.addActionListener(menuItemListener);
      saveMenuItem.addActionListener(menuItemListener);
      exitMenuItem.addActionListener(menuItemListener);
      cutMenuItem.addActionListener(menuItemListener);
      copyMenuItem.addActionListener(menuItemListener);
      pasteMenuItem.addActionListener(menuItemListener);
      final JCheckBoxMenuItem showWindowMenu = new JCheckBoxMenuItem("Show About", true);
      
      showWindowMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            
            if(showWindowMenu.getState()){
               menuBar.add(aboutMenu);
            } else {
               menuBar.remove(aboutMenu);
            }
         }
      });
      final JRadioButtonMenuItem showLinksMenu = new JRadioButtonMenuItem(
         "Show Links", true);
      
      showLinksMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            
            if(menuBar.getMenu(3)!= null){
               menuBar.remove(linkMenu);
               mainFrame.repaint();
            } else {                   
               menuBar.add(linkMenu);
               mainFrame.repaint();
            }
         }
      });
      //add menu items to menus
      fileMenu.add(newMenuItem);
      fileMenu.add(openMenuItem);
      fileMenu.add(saveMenuItem);
      fileMenu.addSeparator();
      fileMenu.add(showWindowMenu);
      fileMenu.addSeparator();
      fileMenu.add(showLinksMenu);       
      fileMenu.addSeparator();
      fileMenu.add(exitMenuItem);        
      
      editMenu.add(cutMenuItem);
      editMenu.add(copyMenuItem);
      editMenu.add(pasteMenuItem);

      //add menu to menubar
      menuBar.add(fileMenu);
      menuBar.add(editMenu);
      menuBar.add(aboutMenu);       
      menuBar.add(linkMenu);

      //add menubar to the frame
      mainFrame.setJMenuBar(menuBar);
      mainFrame.setVisible(true);     
   }
   class MenuItemListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {            
         statusLabel.setText(e.getActionCommand() + " JMenuItem clicked.");
      }    
   }
}

SWING: JCheckboxMenuItem Class Cheat Sheet

Following is the declaration for javax.swing.JCheckBoxMenuItem class

public class JCheckBoxMenuItem
   extends JMenuItem
      implements SwingConstants, Accessible

# Constructors

JCheckboxMenuItem()Creates an initially unselected checkbox menu item with no set text or icon.
JCheckboxMenuItem(Action a)Creates a menu item whose properties are taken from the Action supplied.
JCheckboxMenuItem(Icon icon)Creates an initially unselected checkbox menu item with an icon.
JCheckboxMenuItem(String text)Creates an initially unselected checkbox menu item with text.
JCheckboxMenuItem(String text, boolean b)Creates a checkbox menu item with the specified text and selection state.
JCheckboxMenuItem(String text, Icon icon)Creates an initially unselected checkbox menu item with the specified text and icon.
JCheckboxMenuItem(String text, Icon icon, boolean b)Creates a checkbox menu item with the specified text, icon, and selection state.

# Methods

AccessibleContext getAccessibleContext()Gets the AccessibleContext associated with this JCheckBoxMenuItem.
Object[] getSelectedObjects()Returns an array (length 1) containing the checkbox menu item label or null if the checkbox is not selected.
boolean getState()Returns the selected-state of the item.
String getUIClassID()Returns the name of the L&F class that renders this component.
protected String paramString()Returns a string representation of this JCheckBoxMenuItem.
void setState(boolean b)Sets the selected-state of the item.

# Methods Inherited

  • javax.swing.JMenuItem
  • javax.swing.JAbstractButton
  • javax.swing.JComponent
  • java.awt.Container
  • java.awt.Component
  • java.lang.Object

# JCheckboxMenuItem Example

SwingMenuDemo.java

package com.simplecheatsheet.gui;

import java.awt.*;
import java.awt.event.*;

public class SwingMenuDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel; 

   public SwingMenuDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingMenuDemo  swingMenuDemo = new SwingMenuDemo();     
      swingMenuDemo.showMenuDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showMenuDemo(){
      //create a menu bar
      final JMenuBar menuBar = new JMenuBar();

      //create menus
      JMenu fileMenu = new JMenu("File");
      JMenu editMenu = new JMenu("Edit"); 
      final JMenu aboutMenu = new JMenu("About");
      final JMenu linkMenu = new JMenu("Links");
     
      //create menu items
      JMenuItem newMenuItem = new JMenuItem("New");
      newMenuItem.setMnemonic(KeyEvent.VK_N);
      newMenuItem.setActionCommand("New");

      JMenuItem openMenuItem = new JMenuItem("Open");
      openMenuItem.setActionCommand("Open");

      JMenuItem saveMenuItem = new JMenuItem("Save");
      saveMenuItem.setActionCommand("Save");

      JMenuItem exitMenuItem = new JMenuItem("Exit");
      exitMenuItem.setActionCommand("Exit");

      JMenuItem cutMenuItem = new JMenuItem("Cut");
      cutMenuItem.setActionCommand("Cut");

      JMenuItem copyMenuItem = new JMenuItem("Copy");
      copyMenuItem.setActionCommand("Copy");

      JMenuItem pasteMenuItem = new JMenuItem("Paste");
      pasteMenuItem.setActionCommand("Paste");

      MenuItemListener menuItemListener = new MenuItemListener();

      newMenuItem.addActionListener(menuItemListener);
      openMenuItem.addActionListener(menuItemListener);
      saveMenuItem.addActionListener(menuItemListener);
      exitMenuItem.addActionListener(menuItemListener);
      cutMenuItem.addActionListener(menuItemListener);
      copyMenuItem.addActionListener(menuItemListener);
      pasteMenuItem.addActionListener(menuItemListener);

      final JCheckBoxMenuItem showWindowMenu = new JCheckBoxMenuItem(
         "Show About", true);
      showWindowMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            
            if(showWindowMenu.getState()){
               menuBar.add(aboutMenu);
            } else {
               menuBar.remove(aboutMenu);
            }
         }
      });
      final JRadioButtonMenuItem showLinksMenu = new JRadioButtonMenuItem(
         "Show Links", true);
      
      showLinksMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            
            if(menuBar.getMenu(3)!= null){
               menuBar.remove(linkMenu);
               mainFrame.repaint();
            } else {                   
               menuBar.add(linkMenu);
               mainFrame.repaint();
            }
         }
      });
      //add menu items to menus
      fileMenu.add(newMenuItem);
      fileMenu.add(openMenuItem);
      fileMenu.add(saveMenuItem);
      fileMenu.addSeparator();
      fileMenu.add(showWindowMenu);
      fileMenu.addSeparator();
      fileMenu.add(showLinksMenu);       
      fileMenu.addSeparator();
      fileMenu.add(exitMenuItem);        
      editMenu.add(cutMenuItem);
      editMenu.add(copyMenuItem);
      editMenu.add(pasteMenuItem);

      //add menu to menubar
      menuBar.add(fileMenu);
      menuBar.add(editMenu);
      menuBar.add(aboutMenu);       
      menuBar.add(linkMenu);

      //add menubar to the frame
      mainFrame.setJMenuBar(menuBar);
      mainFrame.setVisible(true);     
   }
   class MenuItemListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {            
         statusLabel.setText(e.getActionCommand() + " JMenuItem clicked.");
      }    
   }
}

SWING: JMenu Class Cheat Sheet

Following is the declaration for javax.swing.JMenu class

public class JMenu
   extends JMenuItem
      implements Accessible, MenuElement

# Field

Following is the field for java.awt.Component class

protected JMenu.WinListener popupListenerThe window-closing listener for the popup.

# Constructors

JMenu()Constructs a new JMenu with no text.
JMenu(Action a)Constructs a menu whose properties are taken from the Action supplied.
JMenu(String s)Constructs a new JMenu with the supplied string as its text.
JMenu(String s, boolean b)Constructs a new JMenu with the supplied string as its text and specified as a tear-off menu or not.

# Methods

JMenuItem add(Action a)Creates a new menu item attached to the specified Action object and appends it to the end of this menu.
Component add(Component c)Appends a component to the end of this menu.
Component add(Component c, int index)Adds the specified component to this container at the given position.
JMenuItem add(JMenuItem menuItem)Appends a menu item to the end of this menu.
JMenuItem add(String s)Creates a new menu item with the specified text and appends it to the end of this menu.
void addMenuListener(MenuListener l)Adds a listener for menu events.
void addSeparator()Appends a new separator to the end of the menu.
void applyComponentOrientation(ComponentOrientation o)Sets the ComponentOrientation property of this menu and all components contained within it.
protected PropertyChangeListener createActionChangeListener(JMenuItem b)Returns a properly configured PropertyChangeListener which updates the control as changes to the Action occur.
protected JMenuItem createActionComponent(Action a)Factory method which creates the JMenuItem for Actions added to the JMenu.
protected JMenu.WinListener createWinListener(JPopupMenu p)Creates a window-closing listener for the popup.
void doClick(int pressTime)Programmatically performs a “click”.
protected void fireMenuCanceled()Notifies all listeners that have registered interest for notification on this event type.
protected void fireMenuDeselected()Notifies all listeners that have registered interest for notification on this event type.
protected void fireMenuSelected()Notifies all listeners that have registered interest for notification on this event type.
AccessibleContext getAccessibleContext()Gets the AccessibleContext associated with this JMenu.
Component getComponent()Returns the java.awt.Component used to paint this MenuElement.
int getDelay()Returns the suggested delay, in milliseconds, before submenus are popped up or down.
JMenuItem getItem(int pos)Returns the JMenuItem at the specified position.
int getItemCount()Returns the number of items on the menu, including separators.
Component getMenuComponent(int n)Returns the component at position n.
int getMenuComponentCount()Returns the number of components on the menu.
Component[] getMenuComponents()Returns an array of Components of the menu’s subcomponents.
MenuListener[]getMenuListeners()Returns an array of all the MenuListeners added to this JMenu with addMenuListener().
JPopupMenu getPopupMenu()Returns the popup menu associated with this menu.
protected Point getPopupMenuOrigin()Computes the origin for the JMenu’s popup menu.
MenuElement[] getSubElements()Returns an array of MenuElements containing the submenu for this menu component.
String getUIClassID()Returns the name of the L&F class that renders this component.
JMenuItem insert(Action a, int pos)Inserts a new menu item attached to the specified Action object at a given position.
JMenuItem insert(JMenuItem mi, int pos)Inserts the specified JMenuitem at a given position.
void insert(String s, int pos)Inserts a new menu item with the specified text at a given position.
void insertSeparator(int index)Inserts a separator at the specified position.
boolean isMenuComponent(Component c)Returns true, if the specified component exists in the submenu hierarchy.
boolean isPopupMenuVisible()Returns true, if the menu’s popup window is visible.
boolean isSelected()Returns true, if the menu is currently selected (highlighted).
boolean isTearOff()Returns true, if the menu can be torn off.
boolean isTopLevelMenu()Returns true, if the menu is a ‘top-level menu’, that is if it is the direct child of a menubar.
void menuSelectionChanged(boolean isIncluded)Message when the menubar selection changes to activate or deactivate this menu.
protected String paramString()Returns a string representation of this JMenu.
protected void processKeyEvent(KeyEvent evt)Processes keystroke events such as mnemonics and accelerators.
void remove(Component c)Removes the component c from this menu.
void remove(int pos)Removes the menu item at the specified index from this menu.
void remove(JMenuItem item)Removes the specified menu item from this menu.
void removeAll()Removes all menu items from this menu.
void removeMenuListener(MenuListener l)Removes a listener for menu events.
void setAccelerator(KeyStroke keyStroke)setAccelerator is not defined for JMenu.
void setComponentOrientation(ComponentOrientation o)Sets the language-sensitive orientation that is used to order the elements or text within this component.
void setDelay(int d)Sets the suggested delay before the menu’s PopupMenu is popped up or down.
void setMenuLocation(int x, int y)Sets the location of the popup component.
void setModel(ButtonModel newModel)Sets the data model for the “menu button” the label that the user clicks to open or close the menu.
void setPopupMenuVisible(boolean b)Sets the visibility of the menu’s popup.
void setSelected(boolean b)Sets the selection status of the menu.
void updateUI()Resets the UI property with a value from the current look and feel.

# Methods Inherited

  • javax.swing.JAbstractButton
  • javax.swing.JComponent
  • java.awt.Container
  • java.awt.Component
  • java.lang.Object

# JMenu Example

SwingMenuDemo.java

package com.simplecheatsheet.gui;

import java.awt.*;
import java.awt.event.*;

public class SwingMenuDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel; 

   public SwingMenuDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingMenuDemo  swingMenuDemo = new SwingMenuDemo();     
      swingMenuDemo.showMenuDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showMenuDemo(){
      //create a menu bar
      final JMenuBar menuBar = new JMenuBar();

      //create menus
      JMenu fileMenu = new JMenu("File");
      JMenu editMenu = new JMenu("Edit"); 
      final JMenu aboutMenu = new JMenu("About");
      final JMenu linkMenu = new JMenu("Links");
     
      //create menu items
      JMenuItem newMenuItem = new JMenuItem("New");
      newMenuItem.setMnemonic(KeyEvent.VK_N);
      newMenuItem.setActionCommand("New");

      JMenuItem openMenuItem = new JMenuItem("Open");
      openMenuItem.setActionCommand("Open");

      JMenuItem saveMenuItem = new JMenuItem("Save");
      saveMenuItem.setActionCommand("Save");

      JMenuItem exitMenuItem = new JMenuItem("Exit");
      exitMenuItem.setActionCommand("Exit");

      JMenuItem cutMenuItem = new JMenuItem("Cut");
      cutMenuItem.setActionCommand("Cut");

      JMenuItem copyMenuItem = new JMenuItem("Copy");
      copyMenuItem.setActionCommand("Copy");

      JMenuItem pasteMenuItem = new JMenuItem("Paste");
      pasteMenuItem.setActionCommand("Paste");

      MenuItemListener menuItemListener = new MenuItemListener();

      newMenuItem.addActionListener(menuItemListener);
      openMenuItem.addActionListener(menuItemListener);
      saveMenuItem.addActionListener(menuItemListener);
      exitMenuItem.addActionListener(menuItemListener);
      cutMenuItem.addActionListener(menuItemListener);
      copyMenuItem.addActionListener(menuItemListener);
      pasteMenuItem.addActionListener(menuItemListener);

      final JCheckBoxMenuItem showWindowMenu = new JCheckBoxMenuItem(
         "Show About", true);
      showWindowMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            
            if(showWindowMenu.getState()){
               menuBar.add(aboutMenu);
            } else {
               menuBar.remove(aboutMenu);
            }
         }
      });
      final JRadioButtonMenuItem showLinksMenu = new JRadioButtonMenuItem(
         "Show Links", true);
      
      showLinksMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            
            if(menuBar.getMenu(3)!= null){
               menuBar.remove(linkMenu);
               mainFrame.repaint();
            } else {                   
               menuBar.add(linkMenu);
               mainFrame.repaint();
            }
         }
      });
      //add menu items to menus
      fileMenu.add(newMenuItem);
      fileMenu.add(openMenuItem);
      fileMenu.add(saveMenuItem);
      fileMenu.addSeparator();
      fileMenu.add(showWindowMenu);
      fileMenu.addSeparator();
      fileMenu.add(showLinksMenu);       
      fileMenu.addSeparator();
      fileMenu.add(exitMenuItem);        
      
      editMenu.add(cutMenuItem);
      editMenu.add(copyMenuItem);
      editMenu.add(pasteMenuItem);

      //add menu to menubar
      menuBar.add(fileMenu);
      menuBar.add(editMenu);
      menuBar.add(aboutMenu);       
      menuBar.add(linkMenu);

      //add menubar to the frame
      mainFrame.setJMenuBar(menuBar);
      mainFrame.setVisible(true);     
   }
   class MenuItemListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {            
         statusLabel.setText(e.getActionCommand() + " JMenuItem clicked.");
      }    
   }
}

SWING: JMenuItem Class Cheat Sheet

Following is the declaration for javax.swing.JMenuItem class

public class JMenuItem
   extends AbstractButton
      implements Accessible, MenuElement

# Constructors

JMenuItem()Creates a JMenuItem with no set text or icon.
JMenuItem(Action a)Creates a menu item whose properties are taken from the specified Action.
JMenuItem(Icon icon)Creates a JMenuItem with the specified icon.
JMenuItem(String text)Creates a JMenuItem with the specified text.
JMenuItem(String text, Icon icon)Creates a JMenuItem with the specified text and icon.
JMenuItem(String text, int mnemonic)Creates a JMenuItem with the specified text and keyboard mnemonic.

# Methods

protected void actionPropertyChanged(Action action, String propertyName)Updates the button’s state in response to property changes in the associated action.
void addMenuDragMouseListener(MenuDragMouseListener l)Adds a MenuDragMouseListener to the menu item.
void addMenuKeyListener(MenuKeyListener l)Adds a MenuKeyListener to the menu item.
protected void configurePropertiesFromAction(Action a)Sets the properties on this button to match those in the specified Action.
protected void fireMenuDragMouseDragged(MenuDragMouseEvent event)Notifies all listeners that have registered interest for notification on this event type.
protected void fireMenuDragMouseEntered(MenuDragMouseEvent event)Notifies all listeners that have registered interest for notification on this event type.
protected void fireMenuDragMouseExited(MenuDragMouseEvent event)Notifies all listeners that have registered interest for notification on this event type.
protected void fireMenuDragMouseReleased(MenuDragMouseEvent event)Notifies all listeners that have registered interest for notification on this event type.
protected void fireMenuKeyPressed(MenuKeyEvent event)Notifies all listeners that have registered interest for notification on this event type.
protected void fireMenuKeyReleased(MenuKeyEvent event)Notifies all listeners that have registered interest for notification on this event type.
protected void fireMenuKeyTyped(MenuKeyEvent event)Notifies all listeners that have registered interest for notification on this event type.
KeyStroke getAccelerator()Returns the KeyStroke which serves as an accelerator for the menu item.
AccessibleContext getAccessibleContext()Returns the AccessibleContext associated with this JMenuItem.
Component getComponent()Returns the java.awt.Component used to paint this object.
MenuDragMouseListener[] getMenuDragMouseListeners()Returns an array of all the MenuDragMouseListeners added to this JMenuItem with addMenuDragMouseListener().
MenuKeyListener[] getMenuKeyListeners()Returns an array of all the MenuKeyListeners added to this JMenuItem with addMenuKeyListener().
MenuElement[] getSubElements()This method returns an array containing the sub-menu components for this menu component.
String getUIClassID()Returns the suffix used to construct the name of the L&F class used to render this component.
protected void init(String text, Icon icon)Initializes the menu item with the specified text and icon.
boolean isArmed()Returns whether the menu item is “armed”.
void menuSelectionChanged(boolean isIncluded)Called by the MenuSelectionManager when the MenuElement is selected or unselected.
protected String paramString()Returns a string representation of this JMenuItem.
void processKeyEvent(KeyEvent e, MenuElement[] path, MenuSelectionManager manager)Processes a key event forwarded from the MenuSelectionManager and changes the menu selection, if necessary, by using MenuSelectionManager’s API.
void processMenuDragMouseEvent(MenuDragMouseEvent e)Handles mouse drag on a menu.
void processMenuKeyEvent(MenuKeyEvent e)Handles a keystroke in a menu.
void processMouseEvent(MouseEvent e, MenuElement[] path, MenuSelectionManager manager)Processes a mouse event forwarded from the MenuSelectionManager and changes the menu selection, if necessary, by using the MenuSelectionManager’s API.
void removeMenuDragMouseListener(MenuDragMouseListener l)Removes a MenuDragMouseListener from the menu item.
void removeMenuKeyListener(MenuKeyListener l)Removes a MenuKeyListener from the menu item.
void setAccelerator(KeyStroke keyStroke)Sets the key combination which invokes the menu item’s action listeners without navigating the menu hierarchy.
void setArmed(boolean b)Identifies the menu item as “armed”.
void setEnabled(boolean b)Enables or disables the menu item.
void setModel(ButtonModel newModel)Sets the model that this button represents.
void setUI(MenuItemUI ui)Sets the look and feel object that renders this component.
void updateUI()Resets the UI property with a value from the current look and feel.

# Methods Inherited

  • javax.swing.JAbstractButton
  • javax.swing.JComponent
  • java.awt.Container
  • java.awt.Component
  • java.lang.Object

# JMenuItem Example

SwingMenuDemo.java

package com.simplecheatsheet.gui;

import java.awt.*;
import java.awt.event.*;

public class SwingMenuDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel; 

   public SwingMenuDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingMenuDemo swingMenuDemo = new SwingMenuDemo();     
      swingMenuDemo.showMenuDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showMenuDemo(){
      //create a menu bar
      final JMenuBar menuBar = new JMenuBar();

      //create menus
      JMenu fileMenu = new JMenu("File");
      JMenu editMenu = new JMenu("Edit"); 
      final JMenu aboutMenu = new JMenu("About");
      final JMenu linkMenu = new JMenu("Links");
     
      //create menu items
      JMenuItem newMenuItem = new JMenuItem("New");
      newMenuItem.setMnemonic(KeyEvent.VK_N);
      newMenuItem.setActionCommand("New");

      JMenuItem openMenuItem = new JMenuItem("Open");
      openMenuItem.setActionCommand("Open");

      JMenuItem saveMenuItem = new JMenuItem("Save");
      saveMenuItem.setActionCommand("Save");

      JMenuItem exitMenuItem = new JMenuItem("Exit");
      exitMenuItem.setActionCommand("Exit");

      JMenuItem cutMenuItem = new JMenuItem("Cut");
      cutMenuItem.setActionCommand("Cut");

      JMenuItem copyMenuItem = new JMenuItem("Copy");
      copyMenuItem.setActionCommand("Copy");

      JMenuItem pasteMenuItem = new JMenuItem("Paste");
      pasteMenuItem.setActionCommand("Paste");

      MenuItemListener menuItemListener = new MenuItemListener();

      newMenuItem.addActionListener(menuItemListener);
      openMenuItem.addActionListener(menuItemListener);
      saveMenuItem.addActionListener(menuItemListener);
      exitMenuItem.addActionListener(menuItemListener);
      cutMenuItem.addActionListener(menuItemListener);
      copyMenuItem.addActionListener(menuItemListener);
      pasteMenuItem.addActionListener(menuItemListener);

      final JCheckBoxMenuItem showWindowMenu = new JCheckBoxMenuItem(
         "Show About", true);
      
      showWindowMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            
            if(showWindowMenu.getState()){
               menuBar.add(aboutMenu);
            } else {
               menuBar.remove(aboutMenu);
            }
         }
      });
      final JRadioButtonMenuItem showLinksMenu = new JRadioButtonMenuItem(
         "Show Links", true);
      
      showLinksMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            
            if(menuBar.getMenu(3)!= null){
               menuBar.remove(linkMenu);
               mainFrame.repaint();
            } else {                   
               menuBar.add(linkMenu);
               mainFrame.repaint();
            }
         }
      });

      //add menu items to menus
      fileMenu.add(newMenuItem);
      fileMenu.add(openMenuItem);
      fileMenu.add(saveMenuItem);
      fileMenu.addSeparator();
      fileMenu.add(showWindowMenu);
      fileMenu.addSeparator();
      fileMenu.add(showLinksMenu);       
      fileMenu.addSeparator();
      fileMenu.add(exitMenuItem);        
      editMenu.add(cutMenuItem);
      editMenu.add(copyMenuItem);
      editMenu.add(pasteMenuItem);

      //add menu to menubar
      menuBar.add(fileMenu);
      menuBar.add(editMenu);
      menuBar.add(aboutMenu);       
      menuBar.add(linkMenu);

      //add menubar to the frame
      mainFrame.setJMenuBar(menuBar);
      mainFrame.setVisible(true);     
   }

   class MenuItemListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {            
         statusLabel.setText(e.getActionCommand() + " JMenuItem clicked.");
      }    
   }
}

SWING: JMenuBar Class Cheat Sheet

Following is the declaration for javax.swing.JMenuBar class

public class JMenuBar
   extends JComponent
      implements Accessible, MenuElement

# Constructors

JMenuBar()Creates a new menu bar.

# Methods

JMenu add(JMenu c)Appends the specified menu to the end of the menu bar.
void addNotify()Overrides JComponent.addNotify to register this menu bar with the current keyboard manager.
AccessibleContext getAccessibleContext()Gets the AccessibleContext associated with this JMenuBar.
Component getComponent()Implemented to be a MenuElement.
Component getComponentAtIndex(int i)Deprecated. Replaced by getComponent(int i)
int getComponentIndex(Component c)Returns the index of the specified component.
JMenu getHelpMenu()Gets the help menu for the menu bar.
Insets getMargin()Returns the margin between the menubar’s border and its menus.
JMenu getMenu(int index)Returns the menu at the specified position in the menu bar.
int getMenuCount()Returns the number of items in the menu bar.
SingleSelectionModel getSelectionModel()Returns the model object that handles single selections.
MenuElement[] getSubElements()Implemented to be a MenuElement. Returns the menus in this menu bar.
MenuBarUI getUI()Returns the menubar’s current UI.
String getUIClassID()Returns the name of the L&F class that renders this component.
boolean isBorderPainted()Returns true if the menu bars border should be painted.
boolean isSelected()Returns true if the menu bar currently has a component selected.
void menuSelectionChanged(boolean isIncluded)Implemented to be a MenuElement, does nothing.
protected void paintBorder(Graphics g)Paints the menubar’s border, if the BorderPainted property is true.
protected String paramString()Returns a string representation of this JMenuBar.
protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed)Subclassed to check all the child menus.
void processKeyEvent(KeyEvent e, MenuElement[] path, MenuSelectionManager manager)Implemented to be a MenuElement, does nothing.
void processMouseEvent(MouseEvent event, MenuElement[] path, MenuSelectionManager manager)Implemented to be a MenuElement, does nothing.
void removeNotify()Overrides JComponent.removeNotify to unregister this menu bar with the current keyboard manager.
void setBorderPainted(boolean b)Sets whether the border should be painted.
void setHelpMenu(JMenu menu)Sets the help menu that appears when the user selects the “help” option in the menu bar.
void setMargin(Insets m)Sets the margin between the menubar’s border and its menus.
void setSelected(Component sel)Sets the currently selected component, producing a change to the selection model.
void setSelectionModel(SingleSelectionModel model)Sets the model object to handle single selections.
void setUI(MenuBarUI ui)Sets the L&F object that renders this component.
void updateUI()Resets the UI property with a value from the current look and feel.

# Methods Inherited

  • javax.swing.JComponent
  • java.awt.Container
  • java.awt.Component
  • java.lang.Object

# JMenuBar Example

SwingMenuDemo.java

package com.simplecheatsheet.gui;

import java.awt.*;
import java.awt.event.*;

public class SwingMenuDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel; 

   public SwingMenuDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingMenuDemo  swingMenuDemo = new SwingMenuDemo();     
      swingMenuDemo.showMenuDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showMenuDemo(){
      //create a menu bar
      final JMenuBar menuBar = new JMenuBar();

      //create menus
      JMenu fileMenu = new JMenu("File");
      JMenu editMenu = new JMenu("Edit"); 
      final JMenu aboutMenu = new JMenu("About");
      final JMenu linkMenu = new JMenu("Links");
     
      //create menu items
      JMenuItem newMenuItem = new JMenuItem("New");
      newMenuItem.setMnemonic(KeyEvent.VK_N);
      newMenuItem.setActionCommand("New");

      JMenuItem openMenuItem = new JMenuItem("Open");
      openMenuItem.setActionCommand("Open");

      JMenuItem saveMenuItem = new JMenuItem("Save");
      saveMenuItem.setActionCommand("Save");

      JMenuItem exitMenuItem = new JMenuItem("Exit");
      exitMenuItem.setActionCommand("Exit");

      JMenuItem cutMenuItem = new JMenuItem("Cut");
      cutMenuItem.setActionCommand("Cut");

      JMenuItem copyMenuItem = new JMenuItem("Copy");
      copyMenuItem.setActionCommand("Copy");

      JMenuItem pasteMenuItem = new JMenuItem("Paste");
      pasteMenuItem.setActionCommand("Paste");

      MenuItemListener menuItemListener = new MenuItemListener();

      newMenuItem.addActionListener(menuItemListener);
      openMenuItem.addActionListener(menuItemListener);
      saveMenuItem.addActionListener(menuItemListener);
      exitMenuItem.addActionListener(menuItemListener);
      cutMenuItem.addActionListener(menuItemListener);
      copyMenuItem.addActionListener(menuItemListener);
      pasteMenuItem.addActionListener(menuItemListener);

      final JCheckBoxMenuItem showWindowMenu = new JCheckBoxMenuItem("Show About", true);
      showWindowMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            
            if(showWindowMenu.getState()){
               menuBar.add(aboutMenu);
            } else {
               menuBar.remove(aboutMenu);
            }
         }
      });
      final JRadioButtonMenuItem showLinksMenu = new JRadioButtonMenuItem(
         "Show Links", true);
      showLinksMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            
            if(menuBar.getMenu(3)!= null){
               menuBar.remove(linkMenu);
               mainFrame.repaint();
            } else {                   
               menuBar.add(linkMenu);
               mainFrame.repaint();
            }
         }
      });
      //add menu items to menus
      fileMenu.add(newMenuItem);
      fileMenu.add(openMenuItem);
      fileMenu.add(saveMenuItem);
      fileMenu.addSeparator();
      fileMenu.add(showWindowMenu);
      fileMenu.addSeparator();
      fileMenu.add(showLinksMenu);       
      fileMenu.addSeparator();
      fileMenu.add(exitMenuItem);        
      
      editMenu.add(cutMenuItem);
      editMenu.add(copyMenuItem);
      editMenu.add(pasteMenuItem);

      //add menu to menubar
      menuBar.add(fileMenu);
      menuBar.add(editMenu);
      menuBar.add(aboutMenu);       
      menuBar.add(linkMenu);

      //add menubar to the frame
      mainFrame.setJMenuBar(menuBar);
      mainFrame.setVisible(true);     
   }
   class MenuItemListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {            
         statusLabel.setText(e.getActionCommand() + " JMenuItem clicked.");
      }    
   }
}

SWING: Containers JWindow Class Cheat Sheet

Following is the declaration for javax.swing.JWindow class

public class JWindow
   extends Window
      implements Accessible, RootPaneContainer

# Field

Following are the fields for java.awt.Component class 

protected AccessibleContext accessibleContextThe accessible context property.
protected JRootPane rootPaneThe JRootPane instance that manages the contentPane and optional menuBar for this frame, as well as the glassPane.
protected boolean rootPaneCheckingEnabled If true then calls to add and setLayout will be forwarded to the contentPane.

# Constructors

JWindow()Creates a window with no specified owner.
JWindow(Frame owner)Creates a window with the specified owner frame.
JWindow(GraphicsConfiguration gc)Creates a window with the specified GraphicsConfiguration of a screen device.
JWindow(Window owner)Creates a window with the specified owner window.
JWindow(Window owner, GraphicsConfiguration gc)Creates a window with the specified owner window and GraphicsConfiguration of a screen device.

# Methods

protected void addImpl(Component comp, Object constraints, int index)Adds the specified child Component.
protected JRootPane createRootPane()Called by the constructor methods to create the default rootPane.
AccessibleContext getAccessibleContext()Gets the AccessibleContext associated with this JWindow.
Container getContentPane()Returns the Container which is the contentPane for this window.
Component getGlassPane()Returns the glassPane Component for this window.
Graphics getGraphics()Creates a graphics context for this component.
JLayeredPane getLayeredPane()Returns the layeredPane object for this window.
JRootPane getRootPane()Returns the rootPane object for this window.
TransferHandler getTransferHandler()Gets the transferHandler property.
protected boolean isRootPaneCheckingEnabled()Returns whether calls to add and setLayout are forwarded to the contentPane.
protected String paramString()Returns a string representation of this JWindow.
void remove(Component comp)Removes the specified component from the container.
void repaint(long time, int x, int y, int width, int height)Repaints the specified rectangle of this component within time milliseconds.
void setContentPane(Container contentPane)Sets the contentPane property for this window.
void setGlassPane(Component glassPane)Sets the glassPane property.
void setLayeredPane(JLayeredPane layeredPane)Sets the layeredPane property.
void setLayout(LayoutManager manager)Sets the LayoutManager.
protected void setRootPane(JRootPane root)Sets the new rootPane object for this window.
protected void setRootPaneCheckingEnabled(boolean enabled)Sets whether calls to add and setLayout are forwarded to the contentPane.
void setTransferHandler(TransferHandler newHandler)Sets the transferHandler property, which is a mechanism to support the transfer of data into this component.
void update(Graphics g)Calls paint(g).
protected void windowInit()Called by the constructors to init the JWindow properly.

# Inherited

  • java.awt.Window
  • java.awt.Container
  • java.awt.Component
  • java.lang.Object

# JWindow Example

SwingContainerDemo.java

package com.simplecheatsheet.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingContainerDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;
   private JLabel msglabel;

   public SwingContainerDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingContainerDemo  swingContainerDemo = new SwingContainerDemo();  
      swingContainerDemo.showJWindowDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java Swing Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    
      statusLabel.setSize(350,100);

      msglabel = new JLabel("Welcome to TutorialsPoint SWING Tutorial.", JLabel.CENTER);

      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showJWindowDemo(){
      headerLabel.setText("Container in action: JWindow");   
      final MessageWindow window = new MessageWindow(
         mainFrame, "Welcome to TutorialsPoint SWING Tutorial.");

      JButton okButton = new JButton("Open a Window");
      okButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            window.setVisible(true);
            statusLabel.setText("A Window shown to the user."); 
         }
      });
      controlPanel.add(okButton);
      mainFrame.setVisible(true);  
   }
   class MessageWindow extends JWindow{
      private String message; 
      public MessageWindow(JFrame parent, String message) { 
         super(parent);               
         this.message = message; 
         setSize(300, 300);       
         setLocationRelativeTo(parent);         
      }
      public void paint(Graphics g) { 
         super.paint(g);
         g.drawRect(0,0,getSize().width - 1,getSize().height - 1); 
         g.drawString(message,50,150); 
      } 
   }
}

SWING: Containers JFrame Class Cheat Sheet

Following is the declaration for javax.swing.JFrame class

public class JFrame
   extends Frame
      implements WindowConstants, Accessible, RootPaneContainer

# Field

Following are the fields for java.awt.Component class 

protected AccessibleContext accessibleContext  The accessible context property.
static int EXIT_ON_CLOSEThe exit application default window close operation.
protected JRootPane rootPaneThe JRootPane instance that manages the contentPane and optional menuBar for this frame, as well as the glassPane.
protected boolean rootPaneCheckingEnabledIf true then calls to add and setLayout will be forwarded to the contentPane.

# Constructors

JFrame()Constructs a new frame that is initially invisible.
JFrame(GraphicsConfiguration gc)Creates a Frame in the specified GraphicsConfiguration of a screen device and a blank title.
JFrame(String title)Creates a new, initially invisible Frame with the specified title.
JFrame(String title, GraphicsConfiguration gc)Creates a JFrame with the specified title and the specified GraphicsConfiguration of a screen device.

# Methods

protected void addImpl(Component comp, Object constraints, int index)Adds the specified child Component.
protected JRootPane createRootPane()Called by the constructor methods to create the default rootPane.
protected void frameInit()Called by the constructors to init the JFrame properly.
AccessibleContext getAccessibleContext()Gets the AccessibleContext associated with this JFrame.
Container getContentPane()Returns the contentPane object for this frame.
int getDefaultCloseOperation()Returns the operation that occurs when the user initiates a “close” on this frame.
Component getGlassPane()Returns the glassPane object for this frame.
Graphics getGraphics()Creates a graphics context for this component.
JMenuBar getJMenuBar()Returns the menubar set on this frame.
JLayeredPane getLayeredPane()Returns the layeredPane object for this frame.
JRootPane getRootPane()Returns the rootPane object for this frame.
TransferHandler getTransferHandler()Gets the transferHandler property.
static boolean isDefaultLookAndFeelDecorated()Returns true if the newly created JFrames have their Window decorations provided by the current look and feel.
protected boolean isRootPaneCheckingEnabled()Returns whether calls to add and setLayout are forwarded to the contentPane.
protected String paramString()Returns a string representation of this JFrame.
protected void processWindowEvent(WindowEvent e)Processes window events occurring on this component.
void remove(Component comp)Removes the specified component from the container.
void repaint(long time, int x, int y, int width, int height)Repaints the specified rectangle of this component within time milliseconds.
void setContentPane(Container contentPane)Sets the contentPane property.
void setDefaultCloseOperation(int operation)Sets the operation that will happen by default when the user initiates a “close” on this frame.
static void setDefaultLookAndFeelDecorated(boolean defaultLookAndFeelDecorated)Provides a hint as to whether or not newly created JFrames should have their Window decorations (such as borders, widgets to close the window, title…) provided by the current look and feel.
void setGlassPane(Component glassPane)Sets the glassPane property.
void setIconImage(Image image)Sets the image to be displayed as the icon for this window.
void setJMenuBar(JMenuBar menubar)Sets the menubar for this frame.
void setLayeredPane(JLayeredPane layeredPane)Sets the layeredPane property.
void setLayout(LayoutManager manager)Sets the LayoutManager.
protected void setRootPane(JRootPane root)Sets the rootPane property.
protected void setRootPaneCheckingEnabled(boolean enabled)Sets whether calls to add and setLayout are forwarded to the contentPane.
void setTransferHandler(TransferHandler newHandler)Sets the transferHandler property, which is a mechanism to support the transfer of data into this component.
void update(Graphics g)Just calls paint(g).

# Inherited

  • java.awt.Frame
  • java.awt.Window
  • java.awt.Container
  • java.awt.Component
  • java.lang.Object

# JFrame Example

SwingContainerDemo.java

package com.simplecheatsheet.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingContainerDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;
   private JLabel msglabel;

   public SwingContainerDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingContainerDemo  swingContainerDemo = new SwingContainerDemo();  
      swingContainerDemo.showJFrameDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java Swing Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    
      statusLabel.setSize(350,100);
      msglabel = new JLabel("Welcome to TutorialsPoint SWING Tutorial.", JLabel.CENTER);

      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showJFrameDemo(){
      headerLabel.setText("Container in action: JFrame");   
      final JFrame frame = new JFrame();
      frame.setSize(300, 300);
      frame.setLayout(new FlowLayout());       
      frame.add(msglabel);
      
      frame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            frame.dispose();
         }        
      });    
      JButton okButton = new JButton("Open a Frame");
      okButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            statusLabel.setText("A Frame shown to the user.");
            frame.setVisible(true);
         }
      });
      controlPanel.add(okButton);
      mainFrame.setVisible(true);  
   }
}

SWING: Containers JPanel Class Cheat Sheet

Following is the declaration for javax.swing.JPanel class

public class JPanel
   extends JComponent
      implements Accessible

# Constructors

JPanel()Creates a new JPanel with a double buffer and a flow layout.
JPanel(boolean isDoubleBuffered)Creates a new JPanel with FlowLayout and the specified buffering strategy.
JPanel(LayoutManager layout)Creates a new buffered JPanel with the specified layout manager.
JPanel(LayoutManager layout, boolean isDoubleBuffered)Creates a new JPanel with the specified layout manager and buffering strategy.

# Methods

AccessibleContext getAccessibleContext()Gets the AccessibleContext associated with this JPanel.
PanelUI getUI()Returns the look and feel (L&F) object that renders this component.
String getUIClassID()Returns a string that specifies the name of the L&F class which renders this component.
protected String paramString()Returns a string representation of this JPanel.
void setUI(PanelUI ui)Sets the look and feel (L&F) object that renders this component.
void updateUI()Resets the UI property with a value from the current look and feel.

# Methods Inherited

  • javax.swing.JComponent
  • java.awt.Container
  • java.awt.Component
  • java.lang.Object

# JPanel Example

SwingContainerDemo.java

package com.simplecheatsheet.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingContainerDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;
   private JLabel msglabel;

   public SwingContainerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingContainerDemo  swingContainerDemo = new SwingContainerDemo();  
      swingContainerDemo.showJPanelDemo();
   }

   private void prepareGUI(){
      mainFrame = new JFrame("Vi du Java Swing");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    

      statusLabel.setSize(350,100);

      msglabel = new JLabel("Chao mung ban den voi bai huong dan Java Swing.", JLabel.CENTER);

      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showJPanelDemo(){
      headerLabel.setText("Container in action: JPanel");      

      JPanel panel = new JPanel();
      panel.setBackground(Color.magenta);
      panel.setLayout(new FlowLayout());        
      panel.add(msglabel);

      controlPanel.add(panel);        
      mainFrame.setVisible(true);      
   }   
}