Combining JMenu with JList - MenuList

JMenu and JList Combined together!


Let us now combine JMenu with JList and name it MenuList. As you've seen in my previous post, Combining JMenu with Again, i'm using my own MenuButton to create MenuList instead of menu bar for  more space and ease access.


Let's combine!


Combining JMenu with JList - MenuList

import javax.swing.*;
import java.awt.*;
import java.util.Vector;
import java.awt.event.*;
class MenuList extends JFrame
{
JMenuBar mbar;
JMenu menu;
JList<String> jl;
public MenuList()
{
// Set frame properties
setTitle("Menu List");
setSize(400,400);
setVisible(true);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);

// Create menubar
mbar=new JMenuBar();

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

// Add menu to menubar
mbar.add(menu);

// Create a vector that stores String objects
Vector<String> v=new Vector<String>();

// Add items to vector
v.add("Item 1");
v.add("Item 2");
v.add("Item 3");
v.add("Item 4");
v.add("Item 5");
v.add("Item 6");

// Create a JList with the above vector
jl=new JList<String>(v);

// Set foreground color for selected item
jl.setSelectionForeground(Color.white);

// Set background color for selected item
jl.setSelectionBackground(new Color(0,153,255));

// Set a preferred size to jlist, so that it appears quite fat
jl.setPreferredSize(new Dimension(200,200));

// Create a JScrollPane for JList jl
JScrollPane js=new JScrollPane(jl);

// Add JScrollPane to menu
menu.add(js);

// Add menubar to frame. Don't set.
add(mbar);

// Make the frame maximized
setExtendedState(MAXIMIZED_BOTH);
}
public static void main(String args[])
{
new MenuList();
}
}

That's it everything is explained within the program itself and nothing is there to say except that it is a swing hack. However, you've came till here, so take time to look at other swing hacks. 

No comments: