Pop up menus java

How to Create Popup Menu in Java Swing

A popup menu is a free-floating menu which associates with an underlying component. This component is called the invoker. Most of the time, popup menu is linked to a specific component to display context-sensitive choices.

In order to create a popup menu, you use the class JPopupMenu. You then can add menu itemsJMenuItem to popup menu like normal menu. To display the popup menu, you call method show().Normally popup menu is called in response to a mouse event. Here is the code to show the poup menu:

private void showPopup(MouseEvent e) < if (e.isPopupTrigger()) < popup.show(e.getComponent(), e.getX(), e.getY()); >>
Code language: JavaScript (javascript)

In the code above, we check to see whether the popup is triggered. If not we pass the component and location where the popup menu is being displayed to the show() method of JPopupMenu instance.

Here is the JPopupMenu demo application screenshot:

package jpopupmenudemo; import javax.swing.*; import java.awt.event.*; public class Main < public static void main(String[] args) < final JFrame frame = new JFrame("Popup Menu Demo"); // build poup menu final JPopupMenu popup = new JPopupMenu(); // New project menu item JMenuItem menuItem = new JMenuItem("New Project. ", new ImageIcon("images/newproject.png")); menuItem.setMnemonic(KeyEvent.VK_P); menuItem.getAccessibleContext().setAccessibleDescription( "New Project"); menuItem.addActionListener(new ActionListener() < public void actionPerformed(ActionEvent e) < JOptionPane.showMessageDialog(frame, "New Project clicked!"); > >); popup.add(menuItem); // New File menu item menuItem = new JMenuItem("New File. ", new ImageIcon("images/newfile.png")); menuItem.setMnemonic(KeyEvent.VK_F); menuItem.addActionListener(new ActionListener() < public void actionPerformed(ActionEvent e) < JOptionPane.showMessageDialog(frame, "New File clicked!"); > >); popup.add(menuItem); // add mouse listener frame.addMouseListener(new MouseAdapter() < @Override public void mousePressed(MouseEvent e) < showPopup(e); >@Override public void mouseReleased(MouseEvent e) < showPopup(e); >private void showPopup(MouseEvent e) < if (e.isPopupTrigger()) < popup.show(e.getComponent(), e.getX(), e.getY()); >> >); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); frame.setVisible(true); > >
Code language: JavaScript (javascript)

Источник

Читайте также:  Метод contains list java

Pop up menus java

An implementation of a popup menu — a small window that pops up and displays a series of choices. A JPopupMenu is used for the menu that appears when the user selects an item on the menu bar. It is also used for «pull-right» menu that appears when the selects a menu item that activates it. Finally, a JPopupMenu can also be used anywhere else you want a menu to appear. For example, when the user right-clicks in a specified area. For information and examples of using popup menus, see How to Use Menus in The Java Tutorial. Warning: Swing is not thread safe. For more information see Swing’s Threading Policy. Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeans™ has been added to the java.beans package. Please see XMLEncoder .

Nested Class Summary

Nested classes/interfaces inherited from class javax.swing.JComponent

Nested classes/interfaces inherited from class java.awt.Container

Nested classes/interfaces inherited from class java.awt.Component

Field Summary

Fields inherited from class javax.swing.JComponent

Fields inherited from class java.awt.Component

Fields inherited from interface java.awt.image.ImageObserver

Constructor Summary

Method Summary

Returns a properly configured PropertyChangeListener which updates the control as changes to the Action occur.

Returns true if the MouseEvent is considered a popup trigger by the JPopupMenu ‘s currently installed UI.

Processes focus events occurring on this component by dispatching them to any registered FocusListener objects.

Processes a key event forwarded from the MenuSelectionManager and changes the menu selection, if necessary, by using MenuSelectionManager ‘s API.

Sets the invoker of this popup menu — the component in which the popup menu menu is to be displayed.

Methods inherited from class javax.swing.JComponent

Methods inherited from class java.awt.Container

Methods inherited from class java.awt.Component

Methods inherited from class java.lang.Object

Constructor Detail

JPopupMenu

JPopupMenu

Method Detail

setDefaultLightWeightPopupEnabled

public static void setDefaultLightWeightPopupEnabled(boolean aFlag)

getDefaultLightWeightPopupEnabled

public static boolean getDefaultLightWeightPopupEnabled()

getUI

setUI

updateUI

getUIClassID

processFocusEvent

  • A FocusListener object is registered via addFocusListener .
  • Focus events are enabled via enableEvents .

processKeyEvent

getSelectionModel

setSelectionModel

add

add

add

createActionComponent

protected JMenuItem createActionComponent(Action a)

createActionChangeListener

protected PropertyChangeListener createActionChangeListener(JMenuItem b)

Returns a properly configured PropertyChangeListener which updates the control as changes to the Action occur.

remove

public void remove(int pos)

setLightWeightPopupEnabled

public void setLightWeightPopupEnabled(boolean aFlag)

Sets the value of the lightWeightPopupEnabled property, which by default is true . By default, when a look and feel displays a popup, it can choose to use a lightweight (all-Java) popup. Lightweight popup windows are more efficient than heavyweight (native peer) windows, but lightweight and heavyweight components do not mix well in a GUI. If your application mixes lightweight and heavyweight components, you should disable lightweight popups. Some look and feels might always use heavyweight popups, no matter what the value of this property.

isLightWeightPopupEnabled

public boolean isLightWeightPopupEnabled()

getLabel

Источник

Как создать всплывающее меню в Java

Как создать всплывающее меню в Java

Всплывающее, или контекстные, меню (pop-up menu) — это меню, не связанные со строкой, а отображающейся в произвольно выбранной позиции на экране.

Всплывающее меню создается так же, как и обычное, за одним исключением — оно не имеет заголовка:

Пункты меню добавляются, как обычно:

Как создать всплывающее меню в Java

В отличие от строки меню, которая всегда находится в верхней части фрейма, всплывающее меню нужно принудительно выводить на экран с помощью метода show(). При этом задается родительский компонент и расположение всплывающего меню в его системе координат.

Часто приходится размещать компонент внутри другого компонента, с которым связано выплывающее меню. Для этого чтобы дочерний компонент наследовал меню родительского компонента, надо вызвать метод:

Приведенные выше методы были реализованы в Java SE 5.0 для того, чтобы исключить зависимость программиста от особенностей работы с контекстным меню в конкретной системе. В предшествующих версиях Java SE приходилось устанавливать обработчик событий, связанных с мышью, и задавать представленный ниже код как в методе mousePressed(), так и методе mouseReleased():

Источник

Оцените статью