gpt4 book ai didi

java - 单击 JPopupMenu 时 JPopupPanel 关闭

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

我有一个 JPopupPanel 在单击按钮时显示。

这个 JPopupPanel 有一个 JPopupMenu,它在鼠标右键单击时显示,显示不同的选项。当按下左键在 PopupMenu 中选择此选项之一时,PopupPanel 关闭,暂时保留 PopupMenu,当释放按钮时,PopupMenu 也消失(如预期的那样),但在PopupPanel 因为它已经关闭。

在选择 JPopupMenu 的选项之一时,如何避免 JPopupPanel 关闭?

谢谢

最佳答案

抱歉,我没有使用 JPopupPanel 的经验。因此,我只能提供一个简单的hack

我怀疑您可以执行与我的示例(下方)类似的操作,在该示例中我“忽略”隐藏选项选择中的弹出菜单。

我这里的方法是重新显示选项选择的弹出菜单。因此,考虑到这一点,您可以尝试在面板隐藏时重新显示它。

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;

public class JPopupMenuIgnoreOptionCloseOnClick extends JPanel
{
private static final long serialVersionUID = 1L;
private JPopupMenu popup = new JPopupMenu("Oi I am popup");
private MouseListener mL = new MouseAdapter()
{
@Override
public void mousePressed(MouseEvent e)
{
System.out.println("mL mousePressed e.isP="+e.isPopupTrigger());
super.mousePressed(e);
showPopup(e);
}

@Override
public void mouseReleased(MouseEvent e)
{
System.out.println("mL mouseReleased e.isP="+e.isPopupTrigger());
super.mouseReleased(e);
showPopup(e);
}

private void showPopup(MouseEvent e)
{
if(e.isPopupTrigger())
{
prevLocation = e.getPoint();
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
};
private Point prevLocation = null;
private MouseListener optionML = new MouseAdapter()
{
@Override
public void mouseReleased(MouseEvent e)
{
System.out.println("optionML mouseReleased prevLocation="+prevLocation);
e.consume();
popup.show(JPopupMenuIgnoreOptionCloseOnClick.this, prevLocation.x,prevLocation.y);
}

};

public JPopupMenuIgnoreOptionCloseOnClick()
{
addMouseListener(mL);
JMenuItem opt1 =new JMenuItem("Option 1");
opt1.addMouseListener(optionML);
popup.add(opt1);
JMenuItem opt2 =new JMenuItem("Option 2");
opt2.addMouseListener(optionML);
popup.add(opt2);
JMenuItem opt3 =new JMenuItem("Option 3");
opt3.addMouseListener(optionML);
popup.add(opt3);
}

public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
JPopupMenuIgnoreOptionCloseOnClick p = new JPopupMenuIgnoreOptionCloseOnClick();
p.setPreferredSize(new Dimension(400, 400));
JPanel contentPane = new JPanel();
contentPane.setBackground(Color.CYAN);
contentPane.add(p);
JFrame f = new JFrame();
f.setContentPane(contentPane);
f.setSize(800, 600);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
});
}
}

关于java - 单击 JPopupMenu 时 JPopupPanel 关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5802139/

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