In the past, when one made a JPopupMenu
visible it's first item would get selected by default: http://weblogs.java.net/blog/alexfromsun/archive/2008/02/jtrayicon_updat.html
Nowadays the default behavior is to pop up the menu without any item selected. I would like create a JPopupMenu
with a single item that will pop up selected and centered under the mouse pointer. I have managed to get the item to pop up centered under the mouse but I the JMenuItem
refuses to render as if it is selected. If I move the mouse out of the item and back in it selects properly.
Any ideas?
Here is my testcase:
import java.awt.Component;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
public class Test extends JFrame
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(800, 600);
frame.getContentPane().addMouseListener(new MouseAdapter()
{
@Override
public void mousePressed(MouseEvent e)
{
if (e.isPopupTrigger())
popupTriggered(e);
}
@Override
public void mouseReleased(MouseEvent e)
{
if (e.isPopupTrigger())
popupTriggered(e);
}
private void popupTriggered(MouseEvent e)
{
JPopupMenu menu = new JPopupMenu();
final JMenuItem item = new JMenuItem("This is a JMenuItem");
menu.add(item);
Point point = e.getPoint();
int x = point.x - (item.getPreferredSize().width / 2);
int y = point.y - (item.getPreferredSize().height / 2);
menu.show((Component) e.getSource(), x, y);
}
});
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With