Я работаю с JPopupMenu в Java Swing, и мне нужно разрешить пользователям перемещаться по меню с помощью клавиш со стрелками вверх/вниз. Однако я устанавливаю JPopupMenu как не фокусируемый (popupMenu.setFocusable(false)) чтобы он не получал фокус сам.
Когда JPopupMenu не фокусируется, я не могу для захвата событий клавиатуры (например, клавиш со стрелками вверх/вниз) для навигации между JMenuItems. Клавиши вверх/вниз, похоже, не работают, и я могу взаимодействовать с меню только с помощью мыши.
Как включить навигацию с помощью клавиатуры для JPopupMenu, которое не фокусируется? В частности, как я могу разрешить навигацию и выбор клавиш со стрелками вверх/вниз (с помощью Enter) для пунктов меню в JPopupMenu, не делая все меню фокусируемым?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PopupMenuExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("PopupMenu Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
// Create a right-click menu (JPopupMenu)
JPopupMenu popupMenu = new JPopupMenu();
JMenuItem menuItem1 = new JMenuItem("Option 1");
JMenuItem menuItem2 = new JMenuItem("Option 2");
JMenuItem menuItem3 = new JMenuItem("Option 3");
popupMenu.add(menuItem1);
popupMenu.add(menuItem2);
popupMenu.add(menuItem3);
popupMenu.setFocusable(false);
// Add action listeners to menu items for demonstration
menuItem1.addActionListener(e -> System.out.println("Option 1 selected"));
menuItem2.addActionListener(e -> System.out.println("Option 2 selected"));
menuItem3.addActionListener(e -> System.out.println("Option 3 selected"));
// Mouse listener to show the popup menu on right-click
frame.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
popupMenu.show(frame, e.getX(), e.getY());
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
popupMenu.show(frame, e.getX(), e.getY());
}
}
});
// Register keyboard actions on each menu item
KeyStroke downKey = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false);
KeyStroke upKey = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false);
// Register keyboard actions for the menu items
menuItem1.registerKeyboardAction(e -> navigateMenu(popupMenu, 1), downKey, JComponent.WHEN_FOCUSED);
menuItem2.registerKeyboardAction(e -> navigateMenu(popupMenu, 1), downKey, JComponent.WHEN_FOCUSED);
menuItem3.registerKeyboardAction(e -> navigateMenu(popupMenu, 1), downKey, JComponent.WHEN_FOCUSED);
menuItem1.registerKeyboardAction(e -> navigateMenu(popupMenu, -1), upKey, JComponent.WHEN_FOCUSED);
menuItem2.registerKeyboardAction(e -> navigateMenu(popupMenu, -1), upKey, JComponent.WHEN_FOCUSED);
menuItem3.registerKeyboardAction(e -> navigateMenu(popupMenu, -1), upKey, JComponent.WHEN_FOCUSED);
// Open the menu and focus the first item
SwingUtilities.invokeLater(() -> {
popupMenu.show(frame, 100, 100);
menuItem1.requestFocusInWindow();
});
frame.setFocusable(true);
frame.setVisible(true);
});
}
// Method to navigate through the menu items
private static void navigateMenu(JPopupMenu popupMenu, int direction) {
Component[] components = popupMenu.getComponents();
JMenuItem focusedItem = null;
// Find the currently focused menu item
for (Component component : components) {
if (component instanceof JMenuItem && component.isFocusOwner()) {
focusedItem = (JMenuItem) component;
break;
}
}
// If a focused item is found, move focus up or down
if (focusedItem != null) {
int currentIndex = -1;
for (int i = 0; i < components.length; i++) {
if (components == focusedItem) {
currentIndex = i;
break;
}
}
if (currentIndex != -1) {
// Calculate the next index based on the direction
int nextIndex = (currentIndex + direction + components.length) % components.length;
JMenuItem nextItem = (JMenuItem) components[nextIndex];
nextItem.requestFocusInWindow(); // This will give focus to the next item
}
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/792 ... java-swing
Как включить навигацию с клавиатуры в нефокусируемом JPopupMenu в Java Swing? ⇐ JAVA
Программисты JAVA общаются здесь
1733061592
Anonymous
Я работаю с JPopupMenu в Java Swing, и мне нужно разрешить пользователям перемещаться по меню с помощью клавиш со стрелками вверх/вниз. Однако я устанавливаю JPopupMenu как не фокусируемый (popupMenu.setFocusable(false)) чтобы он не получал фокус сам.
Когда JPopupMenu не фокусируется, я не могу для захвата событий клавиатуры (например, клавиш со стрелками вверх/вниз) для навигации между JMenuItems. Клавиши вверх/вниз, похоже, не работают, и я могу взаимодействовать с меню только с помощью мыши.
Как включить навигацию с помощью клавиатуры для JPopupMenu, которое не фокусируется? В частности, как я могу разрешить навигацию и выбор клавиш со стрелками вверх/вниз (с помощью Enter) для пунктов меню в JPopupMenu, не делая все меню фокусируемым?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PopupMenuExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("PopupMenu Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
// Create a right-click menu (JPopupMenu)
JPopupMenu popupMenu = new JPopupMenu();
JMenuItem menuItem1 = new JMenuItem("Option 1");
JMenuItem menuItem2 = new JMenuItem("Option 2");
JMenuItem menuItem3 = new JMenuItem("Option 3");
popupMenu.add(menuItem1);
popupMenu.add(menuItem2);
popupMenu.add(menuItem3);
popupMenu.setFocusable(false);
// Add action listeners to menu items for demonstration
menuItem1.addActionListener(e -> System.out.println("Option 1 selected"));
menuItem2.addActionListener(e -> System.out.println("Option 2 selected"));
menuItem3.addActionListener(e -> System.out.println("Option 3 selected"));
// Mouse listener to show the popup menu on right-click
frame.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
popupMenu.show(frame, e.getX(), e.getY());
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
popupMenu.show(frame, e.getX(), e.getY());
}
}
});
// Register keyboard actions on each menu item
KeyStroke downKey = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false);
KeyStroke upKey = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false);
// Register keyboard actions for the menu items
menuItem1.registerKeyboardAction(e -> navigateMenu(popupMenu, 1), downKey, JComponent.WHEN_FOCUSED);
menuItem2.registerKeyboardAction(e -> navigateMenu(popupMenu, 1), downKey, JComponent.WHEN_FOCUSED);
menuItem3.registerKeyboardAction(e -> navigateMenu(popupMenu, 1), downKey, JComponent.WHEN_FOCUSED);
menuItem1.registerKeyboardAction(e -> navigateMenu(popupMenu, -1), upKey, JComponent.WHEN_FOCUSED);
menuItem2.registerKeyboardAction(e -> navigateMenu(popupMenu, -1), upKey, JComponent.WHEN_FOCUSED);
menuItem3.registerKeyboardAction(e -> navigateMenu(popupMenu, -1), upKey, JComponent.WHEN_FOCUSED);
// Open the menu and focus the first item
SwingUtilities.invokeLater(() -> {
popupMenu.show(frame, 100, 100);
menuItem1.requestFocusInWindow();
});
frame.setFocusable(true);
frame.setVisible(true);
});
}
// Method to navigate through the menu items
private static void navigateMenu(JPopupMenu popupMenu, int direction) {
Component[] components = popupMenu.getComponents();
JMenuItem focusedItem = null;
// Find the currently focused menu item
for (Component component : components) {
if (component instanceof JMenuItem && component.isFocusOwner()) {
focusedItem = (JMenuItem) component;
break;
}
}
// If a focused item is found, move focus up or down
if (focusedItem != null) {
int currentIndex = -1;
for (int i = 0; i < components.length; i++) {
if (components[i] == focusedItem) {
currentIndex = i;
break;
}
}
if (currentIndex != -1) {
// Calculate the next index based on the direction
int nextIndex = (currentIndex + direction + components.length) % components.length;
JMenuItem nextItem = (JMenuItem) components[nextIndex];
nextItem.requestFocusInWindow(); // This will give focus to the next item
}
}
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79241725/how-to-enable-keyboard-navigation-in-a-non-focusable-jpopupmenu-in-java-swing[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия