Open JPopupMenu from opened JComboBox

2019-02-26 05:14发布

I'd like to change OOTB behaviour of combobox, to freeze it after right mouse button click (detecting which button was clicked is easy, so that's not the point) and open JPopupMenu istead of choosing that entry.

So - how to disable choosing entry on given condition and use custom behaviour then?

I tried to start by adding mouse listeners to all combobox components, but without success - nothing changed

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JComboBox;
import javax.swing.JFrame;

public class MainClass {

    public static void main(final String args[]) {

        final String labels[] = { "A", "B", "C", "D", "E" };
        JFrame frame = new JFrame("Selecting JComboBox");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JComboBox comboBox = new JComboBox(labels);
        frame.add(comboBox, BorderLayout.SOUTH);
        frame.setSize(400, 200);
        frame.setVisible(true);

        for (Component c : comboBox.getComponents()) {
            c.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                    System.out.println("cli");
                    super.mouseClicked(e);
                }
                public void mousePressed(MouseEvent e) {
                    System.out.println("pre");
                    super.mousePressed(e);
                }
            });
        }
    }
}

1条回答
贪生不怕死
2楼-- · 2019-02-26 05:32
  • in Swing is not possible to showing two lightweight popup containers in the same moment

  • example about JComboBox popup from JPopup

  • there are dirty hack about set JPopup to heavyweight

  • but I'd suggest to mixing AWT Container with Swing JComponents and to use AWT.Popup with Swing.JComponent (JMenuItem or JButton)

查看更多
登录 后发表回答