我正在尝试为文件浏览器制作一组导航按钮。我想要它,以便如果用户单击专用历史记录按钮,则会出现JPopupMenu。但是,当用户右键单击或向下拖动光标向后或向前按钮时,我还希望显示完全相同的菜单。 如何针对不同的手势为多个GUI组件显示完全相同的JPopupMenu(不是副本,但是相同的副本)?
到目前为止,我已经尝试了以下内容:
histButton.addMouseListener(new MouseAdapter()
{
@Override public void mouseClicked(MouseEvent e)
{
showPopup(e);
}
@Override public void mouseDragged(MouseEvent e)
{
showPopup(e);
}
private void showPopup(MouseEvent e)
{
histPopupMenu.show(e.getComponent(), e.getX(), e.getY());
}
});
forwardButton.addMouseListener(new MouseAdapter()
{
@Override public void mouseClicked(MouseEvent e)
{
if (e.isPopupTrigger())
showPopup(e);
}
@Override public void mouseDragged(MouseEvent e)
{
showPopup(e);
}
private void showPopup(MouseEvent e)
{
histPopupMenu.show(e.getComponent(), e.getX(), e.getY());
}
});
backButton.addMouseListener(new MouseAdapter()
{
@Override public void mouseClicked(MouseEvent e)
{
if (e.isPopupTrigger())
showPopup(e);
}
@Override public void mouseDragged(MouseEvent e)
{
showPopup(e);
}
private void showPopup(MouseEvent e)
{
histPopupMenu.show(e.getComponent(), e.getX(), e.getY());
}
});
所有组件都已添加并正确显示,调试显示他们注册了事件,但没有显示任何菜单。
答案 0 :(得分:2)
Bringing Up a Popup Menu显示了使用mousePressed()
,mouseReleased()
和isPopupTrigger()
的传统实现。请注意“应该显示弹出菜单的确切手势因外观而异。”您可以将显示的内容与使用mousePressed()
的实现进行比较。
附录:作为参考,@ mKorbel回忆起可能有用的client property。
import java.awt.Component;
import java.awt.event.*;
import javax.swing.*;
/** @author mKorbel */
public class ComboBoxAction extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JComboBox comboBox;
private JFrame frame;
public ComboBoxAction() {
comboBox = new JComboBox();
comboBox.addActionListener(this);
comboBox.addItem("Item 1");
comboBox.addItem("Item 2");
comboBox.addItem("Item 3");
comboBox.addItem("Item 4");
for (Component component : comboBox.getComponents()) {
if (component instanceof AbstractButton) {
if (component.isVisible()) {
comboBox.remove(component);
}
}
}
//This prevents action events from being fired when the
//up/down arrow keys are used on the dropdown menu
comboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
comboBox.firePopupMenuWillBecomeVisible();
frame = new JFrame();
frame.add(comboBox);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(comboBox.getSelectedItem());
//make sure popup is closed when 'isTableCellEditor' is used
comboBox.hidePopup();
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new ComboBoxAction();
}
});
}
}