Combining JMenu with JPanel - MenuPanel

Fine, now. Till now we've seen,

1. Create Menu Buttons in Swing
2. Combinig JSlider with JMenu to create Volume component

Now, let us combine JMenu and JPanel, so that it let us combine JMenu with various components. Again, in this below example, i've used my MenuButton instead of Menu because it occupies less space and gets mixed up with other components in the JFrame.

Combine now!

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MenuPanel extends JFrame
JMenuBar mbar;
JMenu menu;
JPanel jp;
JTextField jc;
JButton jb;
public MenuPanel()
setTitle("Menu Panel");
setLayout(new FlowLayout());

 // Create menubar
mbar=new JMenuBar();

 // Create menu
menu=new JMenu("Menu");

 // Create JPanel
jp=new JPanel();

 // Create JTextField with capacity of 20 chars to show
jc=new JTextField(20);

 // Create JButton with text Set
jb=new JButton("Set");

 // Add JTextField jc to JPanel

 // Add JButton jb to JPanel

 // Add JPanel jp to JMenu

 // Add menu to menu bar

 // Add JMenuBar mbar to JFrame

 // Add KeyListener to JTextField jc
jc.addKeyListener(new KeyAdapter(){

  // Do things when key is pressed
public void keyPressed(KeyEvent ke)

// Control enters this if() when user presses either backspace or Delete because these 2 actions could only modify the text.
// Set JButton jb enabled. It will be disabled when user clicks on it and enabled when he modifies text.

// Add ActionListener to JButton jb
jb.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
   // Check if text in JTextField length is >0, you can alternatively call isEmpty()
   // Set text in JTextArea jc as title of the frame. Title is not set, if jc has no text.
   // Set JButton jb disabled, so that user may not click on it until the text is modified.

public static void main(String args[])
new MenuPanel();

I've explained all the important steps above, and there is nothing more to say and it is just simply a swing hack. Hope you understand, if you don't feel free to drop a comment. I'll definitely respond to it if it is not a spam.

See more under Swing Hacks category.

Posted by at on

Tags: Swing Hacks,