SWING MouseMotionListener Interface
Introduction
The interfaceMouseMotionListener is used for receiving mouse motion events on a component. The class that process mouse motion events needs to implements this interface.Class declaration
Following is the declaration for java.awt.event.MouseMotionListener interface:public interface MouseMotionListener extends EventListener
Interface methods
S.N. | Method & Description |
---|---|
1 | void mouseDragged(MouseEvent e) Invoked when a mouse button is pressed on a component and then dragged. |
2 | void mouseMoved(MouseEvent e) Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed. |
Methods inherited
This class inherits methods from the following interfaces:- java.awt.event.EventListener
MouseMotionListener Example
Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >SwingListenerDemo.java
package com.tutorialspoint.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() +")"); } } }Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingListenerDemo.javaIf no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingListenerDemoVerify the following output
SWING FocusListener Interface
Introduction
The interfaceFocusListener is used for receiving keyboard focus events. The class that process focus events needs to implements this interface.Class declaration
Following is the declaration for java.awt.event.FocusListener interface:public interface FocusListener extends EventListener
Interface methods
S.N. | Method & Description |
---|---|
1 | void focusGained(FocusEvent e) Invoked when a component gains the keyboard focus. |
2 | void focusLost(FocusEvent e) Invoked when a component loses the keyboard focus. |
Methods inherited
This class inherits methods from the following interfaces:- java.awt.event.EventListener
FocusListener Example
Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >SwingListenerDemo.java
package com.tutorialspoint.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. "); } } }Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingListenerDemo.javaIf no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingListenerDemoVerify the following output
SWING Event Adapters
Adapters are abstract classes for receiving various events. The methods in these classes are empty. These classes exists as convenience for creating listener objects.SWING FocusAdapter Class
Introduction
The class FocusAdapter is an abstract (adapter) class for receiving keyboard focus events. All methods of this class are empty. This class is convenience class for creating listener objects.Class declaration
Following is the declaration for java.awt.event.FocusAdapter class:public abstract class FocusAdapter extends Object implements FocusListener
Class constructors
S.N. | Constructor & Description |
---|---|
1 | FocusAdapter() |
Class methods
S.N. | Method & Description |
---|---|
1 | void focusGained(FocusEvent e) Invoked when a component gains the keyboard focus. |
2 | focusLost(FocusEvent e) Invoked when a component loses the keyboard focus. |
Methods inherited
This class inherits methods from the following classes:- java.lang.Object
FocusAdapter Example
Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >SwingAdapterDemo.java
package com.tutorialspoint.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); } }Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingAdapterDemo.javaIf no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingAdapterDemoVerify the following output
SWING KeyAdapter Class
Introduction
The class KeyAdapter is an abstract (adapter) class for receiving keyboard events. All methods of this class are empty. This class is convenience class for creating listener objects.Class declaration
Following is the declaration for java.awt.event.KeyAdapter class:public abstract class KeyAdapter extends Object implements KeyListener
Class constructors
S.N. | Constructor & Description |
---|---|
1 | KeyAdapter() |
Class methods
S.N. | Method & Description |
---|---|
1 | void keyPressed(KeyEvent e) Invoked when a key has been pressed. |
2 | void keyReleased(KeyEvent e) Invoked when a key has been released. |
3 | void keyTyped(KeyEvent e) Invoked when a key has been typed. |
Methods inherited
This class inherits methods from the following classes:- java.lang.Object
KeyAdapter Example
Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >SwingAdapterDemo.java
package com.tutorialspoint.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); } }Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingAdapterDemo.javaIf no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingAdapterDemoVerify the following output
SWING MouseAdapter Class
Introduction
The class MouseAdapter is an abstract (adapter) class for receiving mouse events. All methods of this class are empty. This class is convenience class for creating listener objects.Class declaration
Following is the declaration for java.awt.event.MouseAdapter class:public abstract class MouseAdapter extends Object implements MouseListener, MouseWheelListener, MouseMotionListener
Class constructors
S.N. | Constructor & Description |
---|---|
1 | MouseAdapter() |
Class methods
S.N. | Method & Description |
---|---|
1 | void mouseClicked(MouseEvent e) Invoked when the mouse button has been clicked (pressed and released) on a component. |
2 | void mouseDragged(MouseEvent e) Invoked when a mouse button is pressed on a component and then dragged. |
3 | void mouseEntered(MouseEvent e) Invoked when the mouse enters a component. |
4 | void mouseExited(MouseEvent e) Invoked when the mouse exits a component. |
5 | void mouseMoved(MouseEvent e) Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed. |
6 | void mousePressed(MouseEvent e) Invoked when a mouse button has been pressed on a component. |
7 | void mouseReleased(MouseEvent e) Invoked when a mouse button has been released on a component. |
8 | void mouseWheelMoved(MouseWheelEvent e) Invoked when the mouse wheel is rotated. |
Methods inherited
This class inherits methods from the following classes:- java.lang.Object
MouseAdapter Example
Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >SwingAdapterDemo.java
package com.tutorialspoint.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); } }Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingAdapterDemo.javaIf no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingAdapterDemoVerify the following output
SWING MouseMotionAdapter Class
Introduction
The class MouseMotionAdapter is an abstract (adapter) class for receiving mouse motion events. All methods of this class are empty. This class is convenience class for creating listener objects.Class declaration
Following is the declaration for java.awt.event.MouseMotionAdapter class:public abstract class MouseMotionAdapter extends Object implements MouseMotionListener
Class constructors
S.N. | Constructor & Description |
---|---|
1 | MouseMotionAdapter() |
Class methods
S.N. | Method & Description |
---|---|
1 | void mouseDragged(MouseEvent e) Invoked when a mouse button is pressed on a component and then dragged. |
2 | void mouseMoved(MouseEvent e) Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed. |
Methods inherited
This class inherits methods from the following classes:- java.lang.Object
MouseMotionAdapter Example
Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >SwingAdapterDemo.java
package com.tutorialspoint.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); } }Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingAdapterDemo.javaIf no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingAdapterDemoVerify the following output
SWING WindowAdapter Class
Introduction
The class WindowAdapter is an abstract (adapter) class for receiving window events. All methods of this class are empty. This class is convenience class for creating listener objects.Class declaration
Following is the declaration for java.awt.event.WindowAdapter class:public abstract class WindowAdapter extends Object implements WindowListener, WindowStateListener, WindowFocusListener
Class constructors
S.N. | Constructor & Description |
---|---|
1 | WindowAdapter() |
Class methods
S.N. | Method & Description |
---|---|
1 | void windowActivated(WindowEvent e) Invoked when a window is activated. |
2 | void windowClosed(WindowEvent e) Invoked when a window has been closed. |
3 | void windowClosing(WindowEvent e) Invoked when a window is in the process of being closed. |
4 | void windowDeactivated(WindowEvent e) Invoked when a window is de-activated. |
5 | void windowDeiconified(WindowEvent e) Invoked when a window is de-iconified. |
6 | 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. |
7 | void windowIconified(WindowEvent e) Invoked when a window is iconified. |
8 | 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. |
9 | void windowOpened(WindowEvent e) Invoked when a window has been opened. |
10 | void windowStateChanged(WindowEvent e) Invoked when a window state is changed. |
Methods inherited
This class inherits methods from the following classes:- java.lang.Object
WindowAdapter Example
Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >SwingAdapterDemo.java
package com.tutorialspoint.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); } }Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingAdapterDemo.javaIf no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingAdapterDemoVerify the following output
SWING Layouts
Introduction
Layout means the arrangement of components within the container. In other way we can say that placing the components at a particular position within the container. The task of layouting the controls is done automatically by the Layout Manager.Layout Manager
The layout manager automatically positions all the components within the container. If we do not use layout manager then also the components are positioned by the default layout manager. It is possible to layout the controls by hand but it becomes very difficult because of the following two reasons.- It is very tedious to handle a large number of controls within the container.
- Oftenly the width and height information of a component is not given when we need to arrange them.
The layout manager is associated with every Container object. Each layout manager is an object of the class that implements the LayoutManager interface.
SWING LayoutManager Interface
Introduction
The interfaceLayoutManager is used to define the interface for classes that know how to lay out Containers.Class declaration
Following is the declaration for java.awt.LayoutManager interface:public interface LayoutManager
Interface methods
S.N. | Method & Description |
---|---|
1 | 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. |
2 | void layoutContainer(Container parent) Lays out the specified container. |
3 | Dimension minimumLayoutSize(Container parent) Calculates the minimum size dimensions for the specified container, given the components it contains. |
4 | Dimension preferredLayoutSize(Container parent) Calculates the preferred size dimensions for the specified container, given the components it contains. |
5 | void removeLayoutComponent(Component comp) Removes the specified component from the layout. |
SWING LayoutManager2 Interface
Introduction
The interfaceLayoutManger is used to define the interface for classes that know how to lay out Containers based on a layout constraints object.Class declaration
Following is the declaration for java.awt.LayoutManager2 interface:public interface LayoutManger2 extends LayoutManager
Interface methods
S.N. | Method & Description |
---|---|
1 | void addLayoutComponent(Component comp, Object constraints) Adds the specified component to the layout, using the specified constraint object. |
2 | float getLayoutAlignmentX(Container target) Returns the alignment along the x axis. |
3 | float getLayoutAlignmentY(Container target) Returns the alignment along the y axis. |
4 | void invalidateLayout(Container target) Invalidates the layout, indicating that if the layout manager has cached information it should be discarded. |
5 | Dimension maximumLayoutSize(Container target) Calculates the maximum size dimensions for the specified container, given the components it contains. |
SWING BorderLayout Class
Introduction
The class BorderLayout arranges the components to fit in the five regions: east, west, north, south and center. Each region is can contain only one component and each component in each region is identified by the corresponding constant NORTH, SOUTH, EAST, WEST, and CENTER.Class declaration
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 container).
- static String EAST -- The east layout constraint (right side of 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 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 container).
- static String WEST -- The west layout constraint (left side of container).
Class constructors
S.N. | Constructor & Description |
---|---|
1 | BorderLayout() Constructs a new border layout with no gaps between components. |
2 | BorderLayout(int hgap, int vgap) Constructs a border layout with the specified gaps between components. |
Class methods
S.N. | Method & Description |
---|---|
1 | void addLayoutComponent(Component comp, Object constraints) Adds the specified component to the layout, using the specified constraint object. |
2 | 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. |
3 | int getHgap() Returns the horizontal gap between components. |
4 | float getLayoutAlignmentX(Container parent) Returns the alignment along the x axis. |
5 | float getLayoutAlignmentY(Container parent) Returns the alignment along the y axis. |
6 | int getVgap() Returns the vertical gap between components. |
7 | void invalidateLayout(Container target) Invalidates the layout, indicating that if the layout manager has cached information it should be discarded. |
8 | void layoutContainer(Container target) |
9 | Dimension maximumLayoutSize(Container target) Returns the maximum dimensions for this layout given the components in the specified target container. |
10 | Dimension minimumLayoutSize(Container target) Determines the minimum size of the target container using this layout manager. |
11 | Dimension preferredLayoutSize(Container target) Determines the preferred size of the target container using this layout manager, based on the components in the container. |
12 | void removeLayoutComponent(Component comp) Removes the specified component from this border layout. |
13 | void setHgap(int hgap) Sets the horizontal gap between components. |
14 | void setVgap(int vgap) Sets the vertical gap between components. |
15 | String toString() Returns a string representation of the state of this border layout. |
Methods inherited
This class inherits methods from the following classes:- java.lang.Object
BorderLayout Example
Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >SwingLayoutDemo.java
package com.tutorialspoint.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); } }Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingLayoutDemo.javaIf no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingLayoutDemoVerify the following output
SWING CardLayout Class
Introduction
The class CardLayout arranges each component in the container as a card. Only one card is visible at a time, and the container acts as a stack of cards.Class declaration
Following is the declaration for java.awt.CardLayout class:public class CardLayout extends Object implements LayoutManager2, Serializable
Class constructors
S.N. | Constructor & Description |
---|---|
1 | CardLayout() Creates a new card layout with gaps of size zero. |
2 | CardLayout(int hgap, int vgap) Creates a new card layout with the specified horizontal and vertical gaps. |
Class methods
S.N. | Method & Description |
---|---|
1 | void addLayoutComponent(Component comp, Object constraints) Adds the specified component to this card layout's internal table of names. |
2 | 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. |
3 | void first(Container parent) Flips to the first card of the container. |
4 | int getHgap() Gets the horizontal gap between components. |
5 | float getLayoutAlignmentX(Container parent) Returns the alignment along the x axis. |
6 | float getLayoutAlignmentY(Container parent) Returns the alignment along the y axis. |
7 | int getVgap() Gets the vertical gap between components. |
8 | void invalidateLayout(Container target) Invalidates the layout, indicating that if the layout manager has cached information it should be discarded. |
9 | void last(Container parent) Flips to the last card of the container. |
10 | void layoutContainer(Container parent) Lays out the specified container using this card layout. |
11 | Dimension maximumLayoutSize(Container target) Returns the maximum dimensions for this layout given the components in the specified target container. |
12 | Dimension minimumLayoutSize(Container parent) Calculates the minimum size for the specified panel. |
13 | void next(Container parent) Flips to the next card of the specified container. |
14 | Dimension preferredLayoutSize(Container parent) Determines the preferred size of the container argument using this card layout. |
15 | void previous(Container parent) Flips to the previous card of the specified container. |
16 | void removeLayoutComponent(Component comp) Removes the specified component from the layout. |
17 | void setHgap(int hgap) Sets the horizontal gap between components. |
18 | void setVgap(int vgap) Sets the vertical gap between components. |
19 | void show(Container parent, String name) Flips to the component that was added to this layout with the specified name, using addLayoutComponent. |
20 | String toString() Returns a string representation of the state of this card layout. |
Methods inherited
This class inherits methods from the following classes:- java.lang.Object
CardLayout Example
Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >SwingLayoutDemo.java
package com.tutorialspoint.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); } }Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingLayoutDemo.javaIf no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingLayoutDemoVerify the following output
SWING FlowLayout Class
Introduction
The class FlowLayout components in a left-to-right flow.Class declaration
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.
Class constructors
S.N. | Constructor & Description |
---|---|
1 | FlowLayout() Constructs a new FlowLayout with a centered alignment and a default 5-unit horizontal and vertical gap. |
2 | FlowLayout(int align) Constructs a new FlowLayout with the specified alignment and a default 5-unit horizontal and vertical gap. |
3 | FlowLayout(int align, int hgap, int vgap) Creates a new flow layout manager with the indicated alignment and the indicated horizontal and vertical gaps. |
Class methods
S.N. | Method & Description |
---|---|
1 | void addLayoutComponent(String name, Component comp) Adds the specified component to the layout. |
2 | int getAlignment() Gets the alignment for this layout. |
3 | int getHgap() Gets the horizontal gap between components. |
4 | int getVgap() Gets the vertical gap between components. |
5 | void layoutContainer(Container target) Lays out the container. |
6 | Dimension minimumLayoutSize(Container target) Returns the minimum dimensions needed to layout the visible components contained in the specified target container. |
7 | Dimension preferredLayoutSize(Container target) Returns the preferred dimensions for this layout given the visible components in the specified target container. |
8 | void removeLayoutComponent(Component comp) Removes the specified component from the layout. |
9 | void setAlignment(int align) Sets the alignment for this layout. |
10 | void setHgap(int hgap) Sets the horizontal gap between components. |
11 | void setVgap(int vgap) Sets the vertical gap between components. |
12 | String toString() Returns a string representation of this FlowLayout object and its values. |
Methods inherited
This class inherits methods from the following classes:- java.lang.Object
FlowLayout Example
Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >SwingLayoutDemo.java
package com.tutorialspoint.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); } }Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingLayoutDemo.javaIf no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingLayoutDemoVerify the following output
SWING GridLayout Class
Introduction
The class GridLayout arranges components in a rectangular grid.Class declaration
Following is the declaration for java.awt.GridLayout class:public class GridLayout extends Object implements LayoutManager, Serializable
Class constructors
S.N. | Constructor & Description |
---|---|
1 | GridLayout() Creates a grid layout with a default of one column per component, in a single row. |
2 | GridLayout(int rows, int cols) Creates a grid layout with the specified number of rows and columns. |
3 | GridLayout(int rows, int cols, int hgap, int vgap) Creates a grid layout with the specified number of rows and columns. |
Class methods
S.N. | Method & Description |
---|---|
1 | void addLayoutComponent(String name, Component comp) Adds the specified component with the specified name to the layout. |
2 | int getColumns() Gets the number of columns in this layout. |
3 | int getHgap() Gets the horizontal gap between components. |
4 | int getRows() Gets the number of rows in this layout. |
5 | int getVgap() Gets the vertical gap between components. |
6 | void layoutContainer(Container parent) Lays out the specified container using this layout. |
7 | Dimension minimumLayoutSize(Container parent) Determines the minimum size of the container argument using this grid layout. |
8 | Dimension preferredLayoutSize(Container parent) Determines the preferred size of the container argument using this grid layout. |
9 | void removeLayoutComponent(Component comp) Removes the specified component from the layout. |
10 | void setColumns(int cols) Sets the number of columns in this layout to the specified value. |
11 | void setHgap(int hgap) Sets the horizontal gap between components to the specified value. |
12 | void setRows(int rows) Sets the number of rows in this layout to the specified value. |
13 | void setVgap(int vgap) Sets the vertical gap between components to the specified value. |
14 | String toString() Returns the string representation of this grid layout's values. |
Methods inherited
This class inherits methods from the following classes:- java.lang.Object
GridLayout Example
Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >SwingLayoutDemo.java
package com.tutorialspoint.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); } }Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingLayoutDemo.javaIf no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingLayoutDemoVerify the following output
SWING GridBagLayout Class
Introduction
The class GridBagLayout arranges components in a horizontal and vertical manner.Class declaration
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 gap should be used for a particular range value.
- static int PREFERRED_SIZE --Indicates the preferred size from the component or gap should be used for a particular range value.
Class constructors
S.N. | Constructor & Description |
---|---|
1 | GridBagLayout() Creates a grid bag layout manager. |
Class methods
S.N. | Method & Description |
---|---|
1 | void addLayoutComponent(Component comp, Object constraints) Adds the specified component to the layout, using the specified constraints object. |
2 | void addLayoutComponent(String name, Component comp) Adds the specified component with the specified name to the layout. |
3 | 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. |
4 | protected void AdjustForGravity(GridBagConstraints constraints, Rectangle r) This method is obsolete and supplied for backwards compatability only; new code should call adjustForGravity instead. |
5 | protected void arrangeGrid(Container parent) Lays out the grid. |
6 | protected void ArrangeGrid(Container parent) This method is obsolete and supplied for backwards compatability only; new code should call arrangeGrid instead. |
7 | GridBagConstraints getConstraints(Component comp) Gets the constraints for the specified component. |
8 | float getLayoutAlignmentX(Container parent) Returns the alignment along the x axis. |
9 | float getLayoutAlignmentY(Container parent) Returns the alignment along the y axis. |
10 | int[][] getLayoutDimensions() Determines column widths and row heights for the layout grid. |
11 | protected java.awt.GridBagLayoutInfo getLayoutInfo(Container parent, int sizeflag) Fills in an instance of GridBagLayoutInfo for the current set of managed children. |
12 | protected java.awt.GridBagLayoutInfo GetLayoutInfo(Container parent, int sizeflag) This method is obsolete and supplied for backwards compatability only; new code should call getLayoutInfo instead. |
13 | Point getLayoutOrigin() Determines the origin of the layout area, in the graphics coordinate space of the target container. |
14 | double[][] getLayoutWeights() Determines the weights of the layout grid's columns and rows. |
15 | protected Dimension getMinSize(Container parent, java.awt.GridBagLayoutInfo info) Figures out the minimum size of the master based on the information from getLayoutInfo(). |
16 | protected Dimension GetMinSize(Container parent, java.awt.GridBagLayoutInfo info) This method is obsolete and supplied for backwards compatability only; new code should call getMinSize instead. |
17 | void invalidateLayout(Container target) Invalidates the layout, indicating that if the layout manager has cached information it should be discarded. |
18 | void layoutContainer(Container parent) Lays out the specified container using this grid bag layout. |
19 | Point location(int x, int y) Determines which cell in the layout grid contains the point specified by (x, y). |
20 | protected GridBagConstraints lookupConstraints(Component comp) Retrieves the constraints for the specified component. |
21 | Dimension maximumLayoutSize(Container target) Returns the maximum dimensions for this layout given the components in the specified target container. |
22 | Dimension minimumLayoutSize(Container parent) Determines the minimum size of the parent container using this grid bag layout. |
23 | Dimension preferredLayoutSize(Container parent) Determines the preferred size of the parent container using this grid bag layout. |
24 | void removeLayoutComponent(Component comp) Removes the specified component from this layout. |
25 | void setConstraints(Component comp, GridBagConstraints constraints) Sets the constraints for the specified component in this layout. |
26 | String toString() Returns a string representation of this grid bag layout's values. |
Methods inherited
This class inherits methods from the following classes:- java.lang.Object
GridBagLayout Example
Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >SwingLayoutDemo.java
package com.tutorialspoint.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); } }Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingLayoutDemo.javaIf no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingLayoutDemoVerify the following output
SWING GroupLayout Class
Introduction
The class GroupLayout hierarchically groups components in order to position them in a Container .Class declaration
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 gap should be used for a particular range value.
- static int PREFERRED_SIZE -- Indicates the preferred size from the component or gap should be used for a particular range value.
Class constructors
S.N. | Constructor & Description |
---|---|
1 | GroupLayout(Container host) Creates a GroupLayout for the specified Container. |
Class methods
S.N. | Method & Description |
---|---|
1 | void addLayoutComponent(Component component, Object constraints) Notification that a Component has been added to the parent container. |
2 | void addLayoutComponent(String name, Component component) Notification that a Component has been added to the parent container. |
3 | GroupLayout.ParallelGroup createBaselineGroup(boolean resizable, boolean anchorBaselineToTop) Creates and returns a ParallelGroup that aligns it's elements along the baseline. |
4 | GroupLayout.ParallelGroup createParallelGroup() Creates and returns a ParallelGroup with an alignment of Alignment.LEADING. |
5 | GroupLayout.ParallelGroup createParallelGroup(GroupLayout.Alignment alignment) Creates and returns a ParallelGroup with the specified alignment. |
6 | GroupLayout.ParallelGroup createParallelGroup(GroupLayout.Alignment alignment, boolean resizable) Creates and returns a ParallelGroup with the specified alignment and resize behavior. |
7 | GroupLayout.SequentialGroup createSequentialGroup() Creates and returns a SequentialGroup. |
8 | boolean getAutoCreateContainerGaps() Returns true if gaps between the container and components that border the container are automatically created. |
9 | boolean getAutoCreateGaps() Returns true if gaps between components are automatically created. |
10 | boolean getHonorsVisibility() Returns whether component visiblity is considered when sizing and positioning components. |
11 | float getLayoutAlignmentX(Container parent) Returns the alignment along the x axis. |
12 | float getLayoutAlignmentY(Container parent) Returns the alignment along the y axis. |
13 | LayoutStyle getLayoutStyle() Returns the LayoutStyle used for calculating the preferred gap between components. |
14 | void invalidateLayout(Container parent) Invalidates the layout, indicating that if the layout manager has cached information it should be discarded. |
15 | void layoutContainer(Container parent) Lays out the specified container. |
16 | void linkSize(Component... components) Forces the specified components to have the same size regardless of their preferred, minimum or maximum sizes. |
17 | 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. |
18 | Dimension maximumLayoutSize(Container parent) Returns the maximum size for the specified container. |
19 | Dimension minimumLayoutSize(Container parent) Returns the minimum size for the specified container. |
20 | Dimension preferredLayoutSize(Container parent) Returns the preferred size for the specified container. |
21 | void removeLayoutComponent(Component component) Notification that a Component has been removed from the parent container. |
22 | void replace(Component existingComponent, Component newComponent) Replaces an existing component with a new one. |
23 | void setAutoCreateContainerGaps(boolean autoCreateContainerPadding) Sets whether a gap between the container and components that touch the border of the container should automatically be created. |
24 | void setAutoCreateGaps(boolean autoCreatePadding) Sets whether a gap between components should automatically be created. |
25 | void setHonorsVisibility(boolean honorsVisibility) Sets whether component visiblity is considered when sizing and positioning components. |
26 | void setHonorsVisibility(Component component, Boolean honorsVisibility) Sets whether the component's visiblity is considered for sizing and positioning. |
27 | void setHorizontalGroup(GroupLayout.Group group) Sets the Group that positions and sizes components along the horizontal axis. |
28 | void setLayoutStyle(LayoutStyle layoutStyle) Sets the LayoutStyle used to calculate the preferred gaps between components. |
29 | void setVerticalGroup(GroupLayout.Group group) Sets the Group that positions and sizes components along the vertical axis. |
30 | String toString() Returns a string representation of this GroupLayout. |
Methods inherited
This class inherits methods from the following classes:- java.lang.Object
GroupLayout Example
Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >SwingLayoutDemo.java
package com.tutorialspoint.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); } }Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingLayoutDemo.javaIf no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingLayoutDemoVerify the following output
SWING SpringLayout Class
Introduction
The class SpringLayout positions the children of its associated container according to a set of constraints.Class declaration
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.
Class constructors
S.N. | Constructor & Description |
---|---|
1 | SpringLayout() Creates a new SpringLayout. |
Class methods
S.N. | Method & Description |
---|---|
1 | void addLayoutComponent(Component component, Object constraints) If constraints is an instance of SpringLayout.Constraints, associates the constraints with the specified component. |
2 | void addLayoutComponent(String name, Component c) Has no effect, since this layout manager does not use a per-component string. |
3 | 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. |
4 | SpringLayout.Constraints getConstraints(Component c) Returns the constraints for the specified component. |
5 | float getLayoutAlignmentX(Container p) Returns 0.5f (centered). |
6 | float getLayoutAlignmentY(Container p) Returns 0.5f (centered). |
7 | void invalidateLayout(Container p) Invalidates the layout, indicating that if the layout manager has cached information it should be discarded. |
8 | void layoutContainer(Container parent) Lays out the specified container. |
9 | Dimension maximumLayoutSize(Container parent) Calculates the maximum size dimensions for the specified container, given the components it contains. |
10 | Dimension minimumLayoutSize(Container parent) Calculates the minimum size dimensions for the specified container, given the components it contains. |
11 | Dimension preferredLayoutSize(Container parent) Calculates the preferred size dimensions for the specified container, given the components it contains. |
12 | 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. |
13 | void putConstraint(String e1, Component c1, Spring s, String e2, Component c2) Links edge e1 of component c1 to edge e2 of component c2. |
14 | void removeLayoutComponent(Component c) Removes the constraints associated with the specified component. |
Methods inherited
This class inherits methods from the following classes:- java.lang.Object
SpringLayout Example
Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >SwingLayoutDemo.java
package com.tutorialspoint.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.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); } }Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingLayoutDemo.javaIf no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingLayoutDemoVerify the following output
SWING Menu Classes
As we know that every top-level window has a menu bar associated with it. This menu bar consist of various menu choices available to the end user. Further each choice contains list of options which is called drop down menus. Menu and MenuItem controls are subclass of MenuComponent class.Menu Hiearchy
SWING JMenuBar Class
Introduction
The JMenuBar class provides an implementation of a menu bar.Class declaration
Following is the declaration for javax.swing.JMenuBar class:public class JMenuBar extends JComponent implements Accessible, MenuElement
Class constructors
S.N. | Constructor & Description |
---|---|
1 | JMenuBar() Creates a new menu bar. |
Class methods
JMenu add(JMenu c)Appends the specified menu to the end of the menu bar.
S.N. | Method & Description |
---|---|
1 | void addNotify() Overrides JComponent.addNotify to register this menu bar with the current keyboard manager. |
1 | AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this JMenuBar. |
2 | Component getComponent() Implemented to be a MenuElement. |
3 | Component getComponentAtIndex(int i) Deprecated. replaced by getComponent(int i) |
4 | int getComponentIndex(Component c) Returns the index of the specified component. |
5 | JMenu getHelpMenu() Gets the help menu for the menu bar. |
6 | Insets getMargin() Returns the margin between the menubar's border and its menus. |
7 | JMenu getMenu(int index) Returns the menu at the specified position in the menu bar. |
8 | int getMenuCount() Returns the number of items in the menu bar. |
9 | SingleSelectionModel getSelectionModel() Returns the model object that handles single selections. |
10 | MenuElement[] getSubElements() Implemented to be a MenuElement -- returns the menus in this menu bar. |
11 | MenuBarUI getUI() Returns the menubar's current UI. |
12 | String getUIClassID() Returns the name of the L&F class that renders this component. |
13 | boolean isBorderPainted() Returns true if the menu bars border should be painted. |
14 | boolean isSelected() Returns true if the menu bar currently has a component selected. |
15 | void menuSelectionChanged(boolean isIncluded) Implemented to be a MenuElement -- does nothing. |
16 | protected void paintBorder(Graphics g) Paints the menubar's border if BorderPainted property is true. |
17 | protected String paramString() Returns a string representation of this JMenuBar. |
18 | protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) Subclassed to check all the child menus. |
19 | void processKeyEvent(KeyEvent e, MenuElement[] path, MenuSelectionManager manager) Implemented to be a MenuElement -- does nothing. |
20 | void processMouseEvent(MouseEvent event, MenuElement[] path, MenuSelectionManager manager) Implemented to be a MenuElement -- does nothing. |
21 | void removeNotify() Overrides JComponent.removeNotify to unregister this menu bar with the current keyboard manager. |
22 | void setBorderPainted(boolean b) Sets whether the border should be painted. |
23 | void setHelpMenu(JMenu menu) Sets the help menu that appears when the user selects the "help" option in the menu bar. |
24 | void setMargin(Insets m) Sets the margin between the menubar's border and its menus. |
25 | void setSelected(Component sel) Sets the currently selected component, producing a a change to the selection model. |
26 | void setSelectionModel(SingleSelectionModel model) Sets the model object to handle single selections. |
27 | void setUI(MenuBarUI ui) Sets the L&F object that renders this component. |
28 | void updateUI() Resets the UI property with a value from the current look and feel. |
Methods inherited
This class inherits methods from the following classes:- javax.swing.JComponent
- java.awt.Container
- java.awt.Component
- java.lang.Object
JMenuBar Example
Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >SwingMenuDemo.java
package com.tutorialspoint.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."); } } }Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingMenuDemo.javaIf no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingMenuDemoVerify the following output
SWING JMenuItem Class
Introduction
The JMenuItem class represents the actual item in a menu. All items in a menu should derive from class JMenuItem, or one of its subclasses. By default, it embodies a simple labeled menu item.Class declaration
Following is the declaration for javax.swing.JMenuItem class:public class JMenuItem extends AbstractButton implements Accessible, MenuElement
Class constructors
S.N. | Constructor & Description |
---|---|
1 | JMenuItem() Creates a JMenuItem with no set text or icon. |
2 | JMenuItem(Action a) Creates a menu item whose properties are taken from the specified Action. |
3 | JMenuItem(Icon icon) Creates a JMenuItem with the specified icon. |
4 | JMenuItem(String text) Creates a JMenuItem with the specified text. |
5 | JMenuItem(String text, Icon icon) Creates a JMenuItem with the specified text and icon. |
6 | JMenuItem(String text, int mnemonic) Creates a JMenuItem with the specified text and keyboard mnemonic. |
Class methods
S.N. | Method & Description |
---|---|
1 | protected void actionPropertyChanged(Action action, String propertyName) Updates the button's state in response to property changes in the associated action. |
2 | void addMenuDragMouseListener(MenuDragMouseListener l) Adds a MenuDragMouseListener to the menu item. |
3 | void addMenuKeyListener(MenuKeyListener l) Adds a MenuKeyListener to the menu item. |
4 | protected void configurePropertiesFromAction(Action a) Sets the properties on this button to match those in the specified Action. |
5 | protected void fireMenuDragMouseDragged(MenuDragMouseEvent event) Notifies all listeners that have registered interest for notification on this event type. |
6 | protected void fireMenuDragMouseEntered(MenuDragMouseEvent event) Notifies all listeners that have registered interest for notification on this event type. |
7 | protected void fireMenuDragMouseExited(MenuDragMouseEvent event) Notifies all listeners that have registered interest for notification on this event type. |
8 | protected void fireMenuDragMouseReleased(MenuDragMouseEvent event) Notifies all listeners that have registered interest for notification on this event type. |
9 | protected void fireMenuKeyPressed(MenuKeyEvent event) Notifies all listeners that have registered interest for notification on this event type. |
10 | protected void fireMenuKeyReleased(MenuKeyEvent event) Notifies all listeners that have registered interest for notification on this event type. |
11 | protected void fireMenuKeyTyped(MenuKeyEvent event) Notifies all listeners that have registered interest for notification on this event type. |
12 | KeyStroke getAccelerator() Returns the KeyStroke which serves as an accelerator for the menu item. |
13 | AccessibleContext getAccessibleContext() Returns the AccessibleContext associated with this JMenuItem. |
14 | Component getComponent() Returns the java.awt.Component used to paint this object. |
15 | MenuDragMouseListener[] getMenuDragMouseListeners() Returns an array of all the MenuDragMouseListeners added to this JMenuItem with addMenuDragMouseListener(). |
16 | MenuKeyListener[] getMenuKeyListeners() Returns an array of all the MenuKeyListeners added to this JMenuItem with addMenuKeyListener(). |
17 | MenuElement[] getSubElements() This method returns an array containing the sub-menu components for this menu component. |
18 | String getUIClassID() Returns the suffix used to construct the name of the L&F class used to render this component. |
19 | protected void init(String text, Icon icon) Initializes the menu item with the specified text and icon. |
20 | boolean isArmed() Returns whether the menu item is "armed". |
21 | void menuSelectionChanged(boolean isIncluded) Called by the MenuSelectionManager when the MenuElement is selected or unselected. |
22 | protected String paramString() Returns a string representation of this JMenuItem. |
23 | 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. |
24 | void processMenuDragMouseEvent(MenuDragMouseEvent e) Handles mouse drag in a menu. |
25 | void processMenuKeyEvent(MenuKeyEvent e) Handles a keystroke in a menu. |
26 | 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. |
27 | void removeMenuDragMouseListener(MenuDragMouseListener l) Removes a MenuDragMouseListener from the menu item. |
28 | void removeMenuKeyListener(MenuKeyListener l) Removes a MenuKeyListener from the menu item. |
29 | void setAccelerator(KeyStroke keyStroke) Sets the key combination which invokes the menu item's action listeners without navigating the menu hierarchy. |
30 | void setArmed(boolean b) Identifies the menu item as "armed". |
31 | void setEnabled(boolean b) Enables or disables the menu item. |
32 | void setModel(ButtonModel newModel) Sets the model that this button represents. |
33 | void setUI(MenuItemUI ui) Sets the look and feel object that renders this component. |
34 | void updateUI() Resets the UI property with a value from the current look and feel. |
Methods inherited
This class inherits methods from the following classes:- javax.swing.JAbstractButton
- javax.swing.JComponent
- java.awt.Container
- java.awt.Component
- java.lang.Object
JMenuItem Example
Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >SwingMenuDemo.java
package com.tutorialspoint.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."); } } }Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingMenuDemo.javaIf no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingMenuDemoVerify the following output. (Click on File Menu. Select any menu item.)
SWING JMenu Class
Introduction
The Menu class represents pull-down menu component which is deployed from a menu bar.Class declaration
Following is the declaration for javax.swing.JMenu class:public class JMenu extends JMenuItem implements Accessible, MenuElement
Field
Following are the fields for java.awt.Component class:- protected JMenu.WinListener popupListener -- The window-closing listener for the popup.
Class constructors
S.N. | Constructor & Description |
---|---|
1 | JMenu() Constructs a new JMenu with no text. |
2 | JMenu(Action a) Constructs a menu whose properties are taken from the Action supplied. |
3 | JMenu(String s) Constructs a new JMenu with the supplied string as its text. |
4 | 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. |
Class methods
S.N. | Method & Description |
---|---|
1 | JMenuItem add(Action a) Creates a new menu item attached to the specified Action object and appends it to the end of this menu. |
2 | Component add(Component c) Appends a component to the end of this menu. |
3 | Component add(Component c, int index) Adds the specified component to this container at the given position. |
4 | JMenuItem add(JMenuItem menuItem) Appends a menu item to the end of this menu. |
5 | JMenuItem add(String s) Creates a new menu item with the specified text and appends it to the end of this menu. |
6 | void addMenuListener(MenuListener l) Adds a listener for menu events. |
7 | void addSeparator() Appends a new separator to the end of the menu. |
8 | void applyComponentOrientation(ComponentOrientation o) Sets the ComponentOrientation property of this menu and all components contained within it. |
9 | protected PropertyChangeListener createActionChangeListener(JMenuItem b) Returns a properly configured PropertyChangeListener which updates the control as changes to the Action occur. |
10 | protected JMenuItem createActionComponent(Action a) Factory method which creates the JMenuItem for Actions added to the JMenu. |
11 | protected JMenu.WinListener createWinListener(JPopupMenu p) Creates a window-closing listener for the popup. |
12 | void doClick(int pressTime) Programmatically performs a "click". |
13 | protected void fireMenuCanceled() Notifies all listeners that have registered interest for notification on this event type. |
14 | protected void fireMenuDeselected() Notifies all listeners that have registered interest for notification on this event type. |
15 | protected void fireMenuSelected() Notifies all listeners that have registered interest for notification on this event type. |
16 | AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this JMenu. |
17 | Component getComponent() Returns the java.awt.Component used to paint this MenuElement. |
18 | int getDelay() Returns the suggested delay, in milliseconds, before submenus are popped up or down. |
19 | JMenuItem getItem(int pos) Returns the JMenuItem at the specified position. |
20 | int getItemCount() Returns the number of items on the menu, including separators. |
21 | Component getMenuComponent(int n) Returns the component at position n. |
22 | int getMenuComponentCount() Returns the number of components on the menu. |
23 | Component[] getMenuComponents() Returns an array of Components of the menu's subcomponents. |
24 | MenuListener[] getMenuListeners() Returns an array of all the MenuListeners added to this JMenu with addMenuListener(). |
25 | JPopupMenu getPopupMenu() Returns the popupmenu associated with this menu. |
26 | protected Point getPopupMenuOrigin() Computes the origin for the JMenu's popup menu. |
27 | MenuElement[] getSubElements() Returns an array of MenuElements containing the submenu for this menu component. |
28 | String getUIClassID() Returns the name of the L&F class that renders this component. |
29 | JMenuItem insert(Action a, int pos) Inserts a new menu item attached to the specified Action object at a given position. |
30 | JMenuItem insert(JMenuItem mi, int pos) Inserts the specified JMenuitem at a given position. |
31 | void insert(String s, int pos) Inserts a new menu item with the specified text at a given position. |
32 | void insertSeparator(int index) Inserts a separator at the specified position. |
33 | boolean isMenuComponent(Component c) Returns true if the specified component exists in the submenu hierarchy. |
34 | boolean isPopupMenuVisible() Returns true if the menu's popup window is visible. |
35 | boolean isSelected() Returns true if the menu is currently selected (highlighted). |
36 | boolean isTearOff() Returns true if the menu can be torn off. |
37 | boolean isTopLevelMenu() Returns true if the menu is a 'top-level menu', that is, if it is the direct child of a menubar. |
38 | void menuSelectionChanged(boolean isIncluded) Messaged when the menubar selection changes to activate or deactivate this menu. |
39 | protected String paramString() Returns a string representation of this JMenu. |
40 | protected void processKeyEvent(KeyEvent evt) Processes key stroke events such as mnemonics and accelerators. |
41 | void remove(Component c) Removes the component c from this menu. |
42 | void remove(int pos) Removes the menu item at the specified index from this menu. |
43 | void remove(JMenuItem item) Removes the specified menu item from this menu. |
44 | void removeAll() Removes all menu items from this menu. |
45 | void removeMenuListener(MenuListener l) Removes a listener for menu events. |
46 | void setAccelerator(KeyStroke keyStroke) setAccelerator is not defined for JMenu. |
47 | void setComponentOrientation(ComponentOrientation o) Sets the language-sensitive orientation that is to be used to order the elements or text within this component. |
48 | void setDelay(int d) Sets the suggested delay before the menu's PopupMenu is popped up or down. |
49 | void setMenuLocation(int x, int y) Sets the location of the popup component. |
50 | void setModel(ButtonModel newModel) Sets the data model for the "menu button" -- the label that the user clicks to open or close the menu. |
51 | void setPopupMenuVisible(boolean b) Sets the visibility of the menu's popup. |
52 | void setSelected(boolean b) Sets the selection status of the menu. |
53 | void updateUI() Resets the UI property with a value from the current look and feel. |
Methods inherited
This class inherits methods from the following classes:- javax.swing.JAbstractButton
- javax.swing.JComponent
- java.awt.Container
- java.awt.Component
- java.lang.Object
JMenu Example
Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >SwingMenuDemo.java
package com.tutorialspoint.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."); } } }Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingMenuDemo.javaIf no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingMenuDemoVerify the following output. (Click on File Menu.)
SWING JCheckboxMenuItem Class
Introduction
The JCheckboxMenuItem class represents a check box which can be included in a menu. Selecting the check box in the menu changes control's state from on to off or from off to on.Class declaration
Following is the declaration for javax.swing.JCheckBoxMenuItem class:public class JCheckBoxMenuItem extends JMenuItem implements SwingConstants, Accessible
Class constructors
S.N. | Constructor & Description |
---|---|
1 | JCheckboxMenuItem() Creates an initially unselected check box menu item with no set text or icon. |
2 | JCheckboxMenuItem(Action a) Creates a menu item whose properties are taken from the Action supplied. |
3 | JCheckboxMenuItem(Icon icon) Creates an initially unselected check box menu item with an icon. |
4 | JCheckboxMenuItem(String text) Creates an initially unselected check box menu item with text. |
5 | JCheckboxMenuItem(String text, boolean b) Creates a check box menu item with the specified text and selection state. |
6 | JCheckboxMenuItem(String text, Icon icon) Creates an initially unselected check box menu item with the specified text and icon. |
7 | JCheckboxMenuItem(String text, Icon icon, boolean b) Creates a check box menu item with the specified text, icon, and selection state. |
Class methods
S.N. | Method & Description |
---|---|
1 | AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this JCheckBoxMenuItem. |
2 | Object[] getSelectedObjects() Returns an array (length 1) containing the check box menu item label or null if the check box is not selected. |
3 | boolean getState() Returns the selected-state of the item. |
4 | String getUIClassID() Returns the name of the L&F class that renders this component. |
5 | protected String paramString() Returns a string representation of this JCheckBoxMenuItem. |
6 | void setState(boolean b) Sets the selected-state of the item. |
Methods inherited
This class inherits methods from the following classes:- javax.swing.JMenuItem
- javax.swing.JAbstractButton
- javax.swing.JComponent
- java.awt.Container
- java.awt.Component
- java.lang.Object
JCheckboxMenuItem Example
Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >SwingMenuDemo.java
package com.tutorialspoint.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."); } } }Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingMenuDemo.javaIf no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingMenuDemoVerify the following output. (Click on File Menu. Unselect "Show About" menu item.)
SWING JRadioButtonMenuItem Class
Introduction
The JRadioButtonMenuItem class represents a check box which can be included in a menu. Selecting the check box in the menu changes control's state from on to off or from off to on.Class declaration
Following is the declaration for javax.swing.JRadioButtonMenuItem class:public class JRadioButtonMenuItem extends JMenuItem implements Accessible
Class constructors
S.N. | Constructor & Description |
---|---|
1 | JRadioButtonMenuItem() Creates a JRadioButtonMenuItem with no set text or icon. |
2 | JRadioButtonMenuItem(Action a) Creates a radio button menu item whose properties are taken from the Action supplied. |
3 | JRadioButtonMenuItem(Icon icon) Creates a JRadioButtonMenuItem with an icon. |
4 | JRadioButtonMenuItem(Icon icon, boolean selected) Creates a radio button menu item with the specified image and selection state, but no text. |
5 | JRadioButtonMenuItem(String text) Creates a JRadioButtonMenuItem with text. |
6 | JRadioButtonMenuItem(String text, boolean selected) Creates a radio button menu item with the specified text and selection state. |
7 | JRadioButtonMenuItem(String text, Icon icon) Creates a radio button menu item with the specified text and Icon. |
8 | JRadioButtonMenuItem(String text, Icon icon, boolean selected) Creates a radio button menu item that has the specified text, image, and selection state. |
Class methods
S.N. | Method & Description |
---|---|
1 | AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this JRadioButtonMenuItem. |
2 | String getUIClassID() Returns the name of the L&F class that renders this component. |
3 | protected String paramString() Returns a string representation of this JRadioButtonMenuItem. |
Methods inherited
This class inherits methods from the following classes:- javax.swing.JMenuItem
- javax.swing.JAbstractButton
- javax.swing.JComponent
- java.awt.Container
- java.awt.Component
- java.lang.Object
JRadioButtonMenuItem Example
Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >SwingMenuDemo.java
package com.tutorialspoint.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."); } } }Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingMenuDemo.javaIf no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingMenuDemoVerify the following output. (Click on File Menu. Unselect "Show Link" menu item.)
SWING JPopupMenu Class
Introduction
Popup menu represents a menu which can be dynamically popped up at a specified position within a component.Class declaration
Following is the declaration for javax.swing.JPopupMenu class:public class JPopupMenu extends JComponent implements Accessible, MenuElement
Class constructors
S.N. | Constructor & Description |
---|---|
1 | JPopupMenu() Constructs a JPopupMenu without an "invoker". |
2 | JPopupMenu(String label) Constructs a JPopupMenu with the specified title. |
Class methods
S.N. | Method & Description |
---|---|
1 | JMenuItem add(Action a) Appends a new menu item to the end of the menu which dispatches the specified Action object. |
2 | JMenuItem add(JMenuItem menuItem) Appends the specified menu item to the end of this menu. |
3 | JMenuItem add(String s) Creates a new menu item with the specified text and appends it to the end of this menu. |
4 | void addMenuKeyListener(MenuKeyListener l) Adds a MenuKeyListener to the popup menu. |
5 | void addPopupMenuListener(PopupMenuListener l) Adds a PopupMenu listener. |
6 | void addSeparator() Appends a new separator at the end of the menu. |
7 | protected PropertyChangeListener createActionChangeListener(JMenuItem b) Returns a properly configured PropertyChangeListener which updates the control as changes to the Action occur. |
8 | protected JMenuItem createActionComponent(Action a) Factory method which creates the JMenuItem for Actions added to the JPopupMenu. |
9 | protected void firePopupMenuCanceled() Notifies PopupMenuListeners that this popup menu is cancelled. |
10 | protected void firePopupMenuWillBecomeInvisible() Notifies PopupMenuListeners that this popup menu will become invisible. |
11 | protected void firePopupMenuWillBecomeVisible() Notifies PopupMenuListeners that this popup menu will become visible. |
12 | AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this JPopupMenu. |
13 | Component getComponent() Returns this JPopupMenu component. |
14 | Component getComponentAtIndex(int i) Deprecated. replaced by Container.getComponent(int) |
15 | int getComponentIndex(Component c) Returns the index of the specified component. |
16 | static boolean getDefaultLightWeightPopupEnabled() Gets the defaultLightWeightPopupEnabled property, which by default is true. |
17 | Component getInvoker() Returns the component which is the 'invoker' of this popup menu. |
18 | String getLabel() Returns the popup menu's label |
19 | Insets getMargin() Returns the margin, in pixels, between the popup menu's border and its containees. |
20 | MenuKeyListener[] getMenuKeyListeners() Returns an array of all the MenuKeyListeners added to this JPopupMenu with addMenuKeyListener(). |
21 | PopupMenuListener[] getPopupMenuListeners() Returns an array of all the PopupMenuListeners added to this JMenuItem with addPopupMenuListener(). |
22 | SingleSelectionModel getSelectionModel() Returns the model object that handles single selections. |
23 | MenuElement[] getSubElements() Returns an array of MenuElements containing the submenu for this menu component. |
24 | PopupMenuUI getUI() Returns the look and feel (L&F) object that renders this component. |
25 | String getUIClassID() Returns the name of the L&F class that renders this component. |
26 | void insert(Action a, int index) Inserts a menu item for the specified Action object at a given position. |
27 | void insert(Component component, int index) Inserts the specified component into the menu at a given position. |
28 | boolean isBorderPainted() Checks whether the border should be painted. |
29 | boolean isLightWeightPopupEnabled() Gets the lightWeightPopupEnabled property. |
30 | boolean isPopupTrigger(MouseEvent e) Returns true if the MouseEvent is considered a popup trigger by the JPopupMenu's currently installed UI. |
31 | boolean isVisible() Returns true if the popup menu is visible (currently being displayed). |
32 | void menuSelectionChanged(boolean isIncluded) Messaged when the menubar selection changes to activate or deactivate this menu. |
33 | void pack() Lays out the container so that it uses the minimum space needed to display its contents. |
34 | protected void paintBorder(Graphics g) Paints the popup menu's border if the borderPainted property is true. |
35 | protected String paramString() Returns a string representation of this JPopupMenu. |
36 | protected void processFocusEvent(FocusEvent evt) Processes focus events occurring on this component by dispatching them to any registered FocusListener objects. |
37 | protected void processKeyEvent(KeyEvent evt) Processes key stroke events such as mnemonics and accelerators. |
38 | 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. |
39 | void processMouseEvent(MouseEvent event, MenuElement[] path, MenuSelectionManager manager) This method is required to conform to the MenuElement interface, but it not implemented. |
40 | void remove(int pos) Removes the component at the specified index from this popup menu. |
41 | void removeMenuKeyListener(MenuKeyListener l) Removes a MenuKeyListener from the popup menu. |
42 | void removePopupMenuListener(PopupMenuListener l) Removes a PopupMenu listener. |
43 | void setBorderPainted(boolean b) Sets whether the border should be painted. |
44 | static void setDefaultLightWeightPopupEnabled(boolean aFlag) Sets the default value of the lightWeightPopupEnabled property. |
45 | void setInvoker(Component invoker) Sets the invoker of this popup menu -- the component in which the popup menu menu is to be displayed. |
46 | void setLabel(String label) Sets the popup menu's label. |
47 | void setLightWeightPopupEnabled(boolean aFlag) Sets the value of the lightWeightPopupEnabled property, which by default is true. |
48 | void setLocation(int x, int y) Sets the location of the upper left corner of the popup menu using x, y coordinates. |
49 | void setPopupSize(Dimension d) Sets the size of the Popup window using a Dimension object. |
50 | void setPopupSize(int width, int height) Sets the size of the Popup window to the specified width and height. |
51 | void setSelected(Component sel) Sets the currently selected component, This will result in a change to the selection model. |
52 | void setSelectionModel(SingleSelectionModel model) Sets the model object to handle single selections. |
53 | void setUI(PopupMenuUI ui) Sets the L&F object that renders this component. |
54 | void setVisible(boolean b) Sets the visibility of the popup menu. |
55 | 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. |
56 | void updateUI() Resets the UI property to a value from the current look and feel. |
Methods inherited
This class inherits methods from the following classes:- javax.swing.JComponent
- java.awt.Container
- java.awt.Component
- java.lang.Object
JPopupMenu Example
Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >SwingMenuDemo.java
package com.tutorialspoint.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.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); } }Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingMenuDemo.javaIf no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingMenuDemoVerify the following output. (Click in the middle on the screen.)
SWING Containers
Containers are integral part of SWING GUI components. A container provides a space where a component can be located. A Container in AWT is a component itself and it adds the capability to add component to itself. Following are noticable points to be considered.- Sub classes of Container are called as Container. For example JPanel, JFrame and JWindow.
- Container can add only Component to itself.
- A default layout is present in each container which can be overridden using setLayout method.
SWING JPanel Class
Introduction
The class JPanel is a generic lightweight container.Class declaration
Following is the declaration for javax.swing.JPanel class:public class JPanel extends JComponent implements Accessible
Class constructors
S.N. | Constructor & Description |
---|---|
1 | JPanel() Creates a new JPanel with a double buffer and a flow layout. |
2 | JPanel(boolean isDoubleBuffered) Creates a new JPanel with FlowLayout and the specified buffering strategy. |
3 | JPanel(LayoutManager layout) Create a new buffered JPanel with the specified layout manager. |
4 | JPanel(LayoutManager layout, boolean isDoubleBuffered) Creates a new JPanel with the specified layout manager and buffering strategy. |
Class methods
S.N. | Method & Description |
---|---|
1 | AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this JPanel. |
2 | PanelUI getUI() Returns the look and feel (L&F) object that renders this component. |
3 | String getUIClassID() Returns a string that specifies the name of the L&F class that renders this component. |
4 | protected String paramString() Returns a string representation of this JPanel. |
5 | void setUI(PanelUI ui) Sets the look and feel (L&F) object that renders this component. |
6 | void updateUI() Resets the UI property with a value from the current look and feel. |
Methods inherited
This class inherits methods from the following classes:- javax.swing.JComponent
- java.awt.Container
- java.awt.Component
- java.lang.Object
JPanel Example
Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >SwingContainerDemo.java
package com.tutorialspoint.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("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 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); } }Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingContainerDemo.javaIf no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingContainerDemoVerify the following output
SWING JFrame Class
Introduction
The class JFrame is an extended version of java.awt.Frame that adds support for the JFC/Swing component architecture.Class declaration
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_CLOSE --The exit application default window close operation.
- protected JRootPane rootPane --The 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.
Class constructors
S.N. | Constructor & Description |
---|---|
1 | JFrame() Constructs a new frame that is initially invisible. |
2 | JFrame(GraphicsConfiguration gc) Creates a Frame in the specified GraphicsConfiguration of a screen device and a blank title. |
3 | JFrame(String title) Creates a new, initially invisible Frame with the specified title. |
4 | JFrame(String title, GraphicsConfiguration gc) Creates a JFrame with the specified title and the specified GraphicsConfiguration of a screen device. |
Class methods
S.N. | Method & Description |
---|---|
1 | protected void addImpl(Component comp, Object constraints, int index) Adds the specified child Component. |
2 | protected JRootPane createRootPane() Called by the constructor methods to create the default rootPane. |
3 | protected void frameInit() Called by the constructors to init the JFrame properly. |
4 | AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this JFrame. |
5 | Container getContentPane() Returns the contentPane object for this frame. |
6 | int getDefaultCloseOperation() Returns the operation that occurs when the user initiates a "close" on this frame. |
7 | Component getGlassPane() Returns the glassPane object for this frame. |
8 | Graphics getGraphics() Creates a graphics context for this component. |
9 | JMenuBar getJMenuBar() Returns the menubar set on this frame. |
10 | JLayeredPane getLayeredPane() Returns the layeredPane object for this frame. |
11 | JRootPane getRootPane() Returns the rootPane object for this frame. |
12 | TransferHandler getTransferHandler() Gets the transferHandler property. |
13 | static boolean isDefaultLookAndFeelDecorated() Returns true if newly created JFrames should have their Window decorations provided by the current look and feel. |
14 | protected boolean isRootPaneCheckingEnabled() Returns whether calls to add and setLayout are forwarded to the contentPane. |
15 | protected String paramString() Returns a string representation of this JFrame. |
16 | protected void processWindowEvent(WindowEvent e) Processes window events occurring on this component. |
17 | void remove(Component comp) Removes the specified component from the container. |
18 | void repaint(long time, int x, int y, int width, int height) Repaints the specified rectangle of this component within time milliseconds. |
19 | void setContentPane(Container contentPane) Sets the contentPane property. |
20 | void setDefaultCloseOperation(int operation) Sets the operation that will happen by default when the user initiates a "close" on this frame. |
21 | 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. |
22 | void setGlassPane(Component glassPane) Sets the glassPane property. |
23 | void setIconImage(Image image) Sets the image to be displayed as the icon for this window. |
24 | void setJMenuBar(JMenuBar menubar) Sets the menubar for this frame. |
25 | void setLayeredPane(JLayeredPane layeredPane) Sets the layeredPane property. |
26 | void setLayout(LayoutManager manager) Sets the LayoutManager. |
27 | protected void setRootPane(JRootPane root) Sets the rootPane property. |
28 | protected void setRootPaneCheckingEnabled(boolean enabled) Sets whether calls to add and setLayout are forwarded to the contentPane. |
29 | void setTransferHandler(TransferHandler newHandler) Sets the transferHandler property, which is a mechanism to support transfer of data into this component. |
30 | void update(Graphics g) Just calls paint(g). |
Methods inherited
This class inherits methods from the following classes:- java.awt.Frame
- java.awt.Window
- java.awt.Container
- java.awt.Component
- java.lang.Object
JFrame Example
Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >SwingContainerDemo.java
package com.tutorialspoint.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); } }Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingContainerDemo.javaIf no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingContainerDemoVerify the following output
SWING JWindow Class
Introduction
The class JWindow is a container that can be displayed but does not have the title bar or window-management buttons.Class declaration
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 accessibleContext --The accessible context property.
- protected JRootPane rootPane --The 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.
Class constructors
S.N. | Constructor & Description |
---|---|
1 | JWindow() Creates a window with no specified owner. |
2 | JWindow(Frame owner) Creates a window with the specified owner frame. |
3 | JWindow(GraphicsConfiguration gc) Creates a window with the specified GraphicsConfiguration of a screen device. |
4 | JWindow(Window owner) Creates a window with the specified owner window. |
5 | JWindow(Window owner, GraphicsConfiguration gc) Creates a window with the specified owner window and GraphicsConfiguration of a screen device. |
Class methods
S.N. | Method & Description |
---|---|
1 | protected void addImpl(Component comp, Object constraints, int index) Adds the specified child Component. |
2 | protected JRootPane createRootPane() Called by the constructor methods to create the default rootPane. |
3 | AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this JWindow. |
4 | Container getContentPane() Returns the Container which is the contentPane for this window. |
5 | Component getGlassPane() Returns the glassPane Component for this window. |
6 | Graphics getGraphics() Creates a graphics context for this component. |
7 | JLayeredPane getLayeredPane() Returns the layeredPane object for this window. |
8 | JRootPane getRootPane() Returns the rootPane object for this window. |
9 | TransferHandler getTransferHandler() Gets the transferHandler property. |
10 | protected boolean isRootPaneCheckingEnabled() Returns whether calls to add and setLayout are forwarded to the contentPane. |
11 | protected String paramString() Returns a string representation of this JWindow. |
12 | void remove(Component comp) Removes the specified component from the container. |
13 | void repaint(long time, int x, int y, int width, int height) Repaints the specified rectangle of this component within time milliseconds. |
14 | void setContentPane(Container contentPane) Sets the contentPane property for this window. |
15 | void setGlassPane(Component glassPane) Sets the glassPane property. |
16 | void setLayeredPane(JLayeredPane layeredPane) Sets the layeredPane property. |
17 | void setLayout(LayoutManager manager) Sets the LayoutManager. |
18 | protected void setRootPane(JRootPane root) Sets the new rootPane object for this window. |
19 | protected void setRootPaneCheckingEnabled(boolean enabled) Sets whether calls to add and setLayout are forwarded to the contentPane. |
20 | void setTransferHandler(TransferHandler newHandler) Sets the transferHandler property, which is a mechanism to support transfer of data into this component. |
21 | void update(Graphics g) Calls paint(g). |
22 | protected void windowInit() Called by the constructors to init the JWindow properly. |
Methods inherited
This class inherits methods from the following classes:- java.awt.Window
- java.awt.Container
- java.awt.Component
- java.lang.Object
JWindow Example
Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >SwingContainerDemo.java
package com.tutorialspoint.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); } } }Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingContainerDemo.javaIf no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingContainerDemo
No comments:
Post a Comment