gpt4 book ai didi

java - 将 JMenu 添加到 JPanel

转载 作者:行者123 更新时间:2023-11-30 06:26:10 25 4
gpt4 key购买 nike

我需要在JPanel 中有一个JMenu(右边带箭头的可以显示JMenuItem)。问题是,当我这样做时,JMenu 不会在鼠标悬停时激活...我不知道该怎么做以及是否可能。

最佳答案

如果将 JMenu 包装在 JMenuBar 中,它会按预期工作。

这是一个演示示例:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class TestMenus {

private JMenuBar createMenuBar(String name, int depth) {
JMenuBar bar = new JMenuBar();
bar.add(createMenu(name, depth));
return bar;
}

private JMenu createMenu(String name, int depth) {
JMenu menu = new JMenu(name);
for (int i = 0; i < 5; i++) {
if (depth > 0) {
menu.add(createMenu("sub-" + name, depth - 1));
}
}
for (int i = 0; i < 5; i++) {
menu.add(createMenuItem("Menu item " + (i + 1)));
}
return menu;
}

private JMenuItem createMenuItem(String name) {
final JMenuItem jMenuItem = new JMenuItem(name);
jMenuItem.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(jMenuItem, "Successfully pressed a menu item");
}
});
return jMenuItem;
}

protected void initUI() {
JFrame frame = new JFrame(TestMenus.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMenuBar("Root menu", 3));
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
new TestMenus().initUI();
}
});
}

}

结果:

Result of menus added to a JFrame content pane

关于java - 将 JMenu 添加到 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14771437/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com