Thursday, November 21, 2024
HomeComputer programmingJava programmingJava: Titlebar Menus and Context Menus (swing)

Java: Titlebar Menus and Context Menus (swing)

Create your own File, edit, etc menus as well as context menus (right-click viewable)


I will be using the new swing Java version, as it has more options, but non-swing (objects excluding the J prefix) is similar in most cases.

Titlebar Menus:
The first thing to note when constructing titlebar menus is that it must be applied directly to to the JFrame or Frame, and not to a Jpanel/Panel.
Each item to be added to the menubar must be created individually:
ex:
JMenuItem anItem = new JMenuItem(“item”);

Then the items must be added to a menu:
JMenu aMenu = new JMenu(“menu”);
aMenu.add(anItem);

Now the menu must be added to a menubar:
JMenubar abar = new JMenubar();
abar.add(aMenu);

Finally the Menubar must be initialized and added to the Frame:
setJMenuBar(abar);
//no operator is needed before as ‘this’ is assumed and in this case ‘this’ is the JFrame

Any button type can be added to a Menu, including checkboxes and radiobuttons as in the example below. Be sure when creating radiobuttons to add them to a buttongroup to enforce the rule of only 1 item selected at a time.

JMenuItems’ have many features that can be set, most common being the mnemonic:
anItem.setMnemonic(‘i’);
//this is the letter which reacts to the alt+ action, and this letter will appear underlined in the menu.
Each item will also need an action listener or in this case a single listener dispatching output based on the item clicked.

Context Menus:
These are made in a similar fasion, creating JMenuItems then they can be added to JMenus or added directly to the context menu as follows:
JPopupMenu pMenu = new JPopupMenu();
pMenu.add(anItem);
//NOTE this is only an example, a JMenuItem will not function properly if added to multiple sources.

Unless you understand actionlisteners, it may be easier to simply copy this segment of code.
Now apply the listener to look for the right click action:
getContentPane().addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent event){
if (event.isPopupTrigger())
pMenu.show(event.getComponent(), event.getX(), event.getY());
}
});

A Very basic CODE:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class FileMenuExample extends JFrame implements ActionListener {

// Use instance variables to keep track of menu items and popup menus
JMenuItem thinkItem = new JMenuItem(“Think”, new ImageIcon(“brain.gif”));
JMenuItem copyItem = new JMenuItem(“Copy”);
JMenuItem newItem = new JMenuItem(“New”);
JMenuItem openItem = new JMenuItem(“Open”);
JMenuItem saveAsItem = new JMenuItem(“Save As”);
JMenuItem findItem = new JMenuItem(“Find”);
JMenuItem replaceItem = new JMenuItem(“Replace”);

// Some items for use in the Settings menu
JMenuItem appleItem = new JRadioButtonMenuItem(“Apples”);
JMenuItem orangeItem = new JRadioButtonMenuItem(“Oranges”);
JMenuItem bannanaItem = new JRadioButtonMenuItem(“Bannanas”);

// Use instance variables to keep track of a popup menu and its items
JPopupMenu popupMenu = new JPopupMenu();
JMenuItem helpItem = new JMenuItem(“help”);
JMenuItem inspectItem = new JMenuItem(“inspect”);

// Add a constructor for our frame.
public FileMenuExample(String title) {

super(title);

// Create a menu bars and its pull-down menus
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu(“File”);
JMenu editMenu = new JMenu(“Edit”);
JMenu settingsMenu = new JMenu(“Settings”);
JMenu searchMenu = new JMenu(“Search”);

// set menu accelerators for Alt keys
fileMenu.setMnemonic(‘F’);
editMenu.setMnemonic(‘E’);
settingsMenu.setMnemonic(‘S’);
newItem.setMnemonic(‘N’);
openItem.setMnemonic(‘O’);

// set receiver as the object to handle menu item selection requests
newItem.addActionListener(this);
openItem.addActionListener(this);
saveAsItem.addActionListener(this);
thinkItem.addActionListener(this);
copyItem.addActionListener(this);
findItem.addActionListener(this);
replaceItem.addActionListener(this);
helpItem.addActionListener(this);
inspectItem.addActionListener(this);

ButtonGroup fruits = new ButtonGroup();
fruits.add(appleItem);
fruits.add(orangeItem);
fruits.add(bannanaItem);

// add menu items in the menus
fileMenu.add(newItem);
fileMenu.add(openItem);
fileMenu.add(saveAsItem);
editMenu.add(thinkItem);
editMenu.add(copyItem);
searchMenu.add(findItem);
searchMenu.add(replaceItem);
settingsMenu.add(appleItem);
settingsMenu.add(orangeItem);
settingsMenu.add(bannanaItem);

// add items to the popup menu
popupMenu.add(helpItem);
popupMenu.add(inspectItem);

//create the cascaded menu
editMenu.add(searchMenu);

// add menus to the menu bar
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(settingsMenu);

// add menu bar to window and popup menu to the window pane
setJMenuBar(menuBar);

// register the event handler for the popup menu
getContentPane().addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent event){
if (event.isPopupTrigger())
popupMenu.show(event.getComponent(), event.getX(), event.getY());
}
});

// Set the background of the frame
setBackground(Color.lightGray);

}
// dispatch menu selections
public void actionPerformed(ActionEvent event){

if (event.getSource() == newItem)
reactToNewMenuSelection();
else if (event.getSource() == openItem)
reactToOpenMenuSelection();
else if (event.getSource() == saveAsItem)
reactToSaveAsMenuSelection();
else if (event.getSource() == copyItem)
reactToCopyMenuSelection();
else if (event.getSource() == thinkItem)
reactToThinkMenuSelection();
else if (event.getSource() == findItem)
reactToFindMenuSelection();
else if (event.getSource() == replaceItem)
reactToReplaceMenuSelection();
else if (event.getSource() == helpItem)
reactToHelpMenuSelection();
else if (event.getSource() == inspectItem)
reactToInspectMenuSelection();

}
// Here are all the react methods for the menu items
public void reactToNewMenuSelection() {
System.out.println(“reacting to NEW selection from menu”);
}
public void reactToOpenMenuSelection() {
System.out.println(“reacting to OPEN selection from menu”);
}
public void reactToSaveAsMenuSelection() {
System.out.println(“reacting to SAVE AS selection from menu”);
}
public void reactToThinkMenuSelection() {
System.out.println(“reacting to THINK selection from menu”);
}
public void reactToCopyMenuSelection() {
System.out.println(“reacting to COPY selection from menu”);
}
public void reactToFindMenuSelection() {
System.out.println(“reacting to FIND selection from menu”);
}
public void reactToReplaceMenuSelection() {
System.out.println(“reacting to REPLACE selection from menu”);
}
public void reactToHelpMenuSelection() {
System.out.println(“reacting to HELP selection from popup menu”);
}
public void reactToInspectMenuSelection() {
System.out.println(“reacting to INSPECT selection from popup menu”);
}
public static void main(String args[]) {
FileMenuExample frame = new FileMenuExample(“FileMenu Example”);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
}

}

Questions/Comments always welcome: [email protected]
-William. § (marvin_gohan)

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

LATEST REVIEWS

Recent Comments

error: Content is protected !!