Basically there is a JPanel on which I want to know when the mouse enters the area of the JPanel and exits the area of the JPanel. So I added a mouse listener, but if there are components on the JPanel and the mouse goes over one of them it is detected as an exit on the JPanel, even though the component is on the JPanel. I was wondering whether anyone knows any way to solve this problem without doing something like adding listeners onto all components on the JPanel?
There is a very easy solution for this problem that can work :
public class MyJPanel implements MouseListener {
public void mouseExited(MouseEvent e) {
java.awt.Point p = new java.awt.Point(e.getLocationOnScreen());
SwingUtilities.convertPointFromScreen(p, e.getComponent());
if(e.getComponent().contains(p)) {return;}
...//the rest of your code
}
...
}
This way you just ignore the mouseExited event when it occurs on a child element.
Here is one way to do it for a component that may contain other components:
Add a global AWT event listener to get all mouse events. For example:
Toolkit.getDefaultToolkit().addAWTEventListener(
new TargetedMouseHandler( panel ), AWTEvent.MOUSE_EVENT_MASK );
Implement the TargetedMouseHandler to ignore events that aren't sourced by the panel or by one of the panel's children (you can use SwingUtilities.isDescendingFrom to test for this).
Keep track of whether or not the mouse is already within the bounds of your panel. When you get a MouseEvent.MOUSE_ENTERED event in your panel or one of its children, set a flag to true.
When you get a MouseEvent.MOUSE_EXITED event, only reset the flag if the point in the MouseEvent is outside the bounds of your target panel. SwingUtilities.convertPoint and Component.getBounds().contains() will come in handy here.
This is sample code implementing Ash's solution. For me, the JFrame did not detect all exit events properly, but an inner JPanel did, so I passed in two components - one for testing descendants and one for testing the boundary.
Toolkit.getDefaultToolkit().addAWTEventListener(
new TargetedMouseHandler(this, this.jPanel),
AWTEvent.MOUSE_EVENT_MASK);
}
public class TargetedMouseHandler implements AWTEventListener
{
private Component parent;
private Component innerBound;
private boolean hasExited = true;
public TargetedMouseHandler(Component p, Component p2)
{
parent = p;
innerBound = p2;
}
#Override
public void eventDispatched(AWTEvent e)
{
if (e instanceof MouseEvent)
{
if (SwingUtilities.isDescendingFrom(
(Component) e.getSource(), parent))
{
MouseEvent m = (MouseEvent) e;
if (m.getID() == MouseEvent.MOUSE_ENTERED)
{
if (hasExited)
{
System.out.println("Entered");
hasExited = false;
}
} else if (m.getID() == MouseEvent.MOUSE_EXITED)
{
Point p = SwingUtilities.convertPoint(
(Component) e.getSource(),
m.getPoint(),
innerBound);
if (!innerBound.getBounds().contains(p))
{
System.out.println("Exited");
hasExited = true;
}
}
}
}
}
}
A simpeler solution with java 1.8+
public class MyJPanel implements MouseListener {
public void mouseExited(MouseEvent e) {
if(!this.contains(e.getPoint())) {
... //the rest of your code
}
}
...
}
If you want to get all events sent to a top-level window you can add a listener to the glass pane of the JFrame. See getGlassPane.
Related
There is one JPanel with attached MouseWheelListener. This panel has on top several other JPanels, and completely occupies parent JPanel area. I want to know if MouseWheelListener can receive events when the mouse is over this parent JPanel. If I attach MouseListener to parent JPanel - it is not receiving any events, because on top of it there are several other JPanels.
Maybe there is some method to find out when MouseWheelListener can receive events? I mean like if you standing on JScrollPane - only then you can move the scrollbar (and it is not important how many JPanels on it).
EDIT:
The AWTEventListener didn't helped also - the upper JPanels still blocking parent JPanel events.. :
AWTEventListener awt = new AWTEventListener() {
#Override
public void eventDispatched(AWTEvent e) {
if (MouseEvent.MOUSE_ENTERED == e.getID()) {
MouseEvent event = (MouseEvent) e;
for (Component c : getComponents()) {//get all parent JPanel components
if (event.getComponent().equals(c)) {
active = true;
scrollBar.repaint();
break;
}
}
} else if (MouseEvent.MOUSE_EXITED == e.getID()) {
MouseEvent event = (MouseEvent) e;
for (Component c : getComponents()) {
if (event.getComponent().equals(c)) {
active = false;
scrollBar.repaint();
break;
}
}
}
}
};
Toolkit.getDefaultToolkit().addAWTEventListener(awt, AWTEvent.MOUSE_EVENT_MASK);
Perhaps it is impossible to achieve that..
I added a JPanel to a JRadioButton - so that I may display whatever I want in the radio button.
This all worked as expected. But to allow for text wrapping, I used a JTextArea and added it to the JPanel contained within the radio button.
Now I have an issue where, if the user clicks on the JTextArea, then the JTextArea consumes the mouseEvent and as a result there is no response from the radio button (it doesn't 'select').
Is there a way get the JTextArea to ignore the mouse click, so that the parent may handle it instead?
I tried add the JTextArea's listeners to the radioButton instead.
I also tried to remove its listeners completely, but both these attempts failed.
Anyone have any suggestions?
Strong beware
Most JSomething are not meant to be used as containers even though it's possible - the outcome of doing it anyway is more or less visually and behaviourally undetermined!
That said, did it recently, to implement something similar to a Windows task dialog. If the requirement includes keeping the button clickable (and why else would you mis-use it as a container :-) the main problem (layout apart) is to make all added components completely mouse-transparent. Which is more difficult than can be expected. The minimum is to not allow adding of mouseListeners and disable the acceptance of mouseEvents:
final JTextArea area = new JTextArea("replacement ..") {
#Override
public synchronized void addMouseListener(MouseListener l) {
LOG.info("adding here ...?");
}
#Override
public synchronized void addMouseMotionListener(
MouseMotionListener l) {
}
#Override
public synchronized void addMouseWheelListener(
MouseWheelListener l) {
}
#Override
public void addNotify() {
disableEvents(AWTEvent.MOUSE_EVENT_MASK |
AWTEvent.MOUSE_MOTION_EVENT_MASK |
AWTEvent.MOUSE_WHEEL_EVENT_MASK);
super.addNotify();
}
};
Plus make sure it's not focusable
area.setEditable(false);
area.setFocusable(false);
area.setRequestFocusEnabled(false);
Plus unregister dragging and tooltips
ToolTipManager.sharedInstance().unregisterComponent(area);
area.setDragEnabled(false);
Nevertheless, there might still be surprises ahead, f.i. call the following twice (that is disable and enable again), which will internally re-enable mouseEvent:
area.setAutoscrolls(!area.getAutoscrolls());
So at the end of the day, we might get away with it - but never be entirely certain that we succeeded.
What about this? Create and add your own MouseListener to TextArea
JPanel p = new JPanel();
JTextArea t = new JTextArea("line \n line");
t.addMouseListener(new MyMouseListener());
p.add(t);
jRadioButton1.add(p);
jRadioButton1.addMouseListener(new MyRadioButtonMouseListener());
And in the MyMouseListener Dispatch event
private class MyMouseListener implements MouseListener {
#Override
public void mouseClicked(MouseEvent e) {
Component source = (Component) e.getSource();
source.getParent().getParent().dispatchEvent(e); // 2x getParent() because JTextArea->JPanel->JRadio
}
.
.
.
}
And finally RadioButtonMouseListener
private class MyRadioButtonMouseListener implements MouseListener {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("CLICK ON RADIOBUTTON !!");
}
.
.
.
}
I want to override the mouse wheel listener in Swing but only if they have the Control button pressed. The listener will be attached to a JPanel so that when they scroll the wheel it will scroll the JScrollPane and when they have the control button pressed and scroll the wheel it will zoom in. The default scroll of JScrollPane works (obviously) before I override it with my own listener. Here is my code:
mainPanel.addMouseWheelListener(new MouseWheelListener(){
#Override
public void mouseWheelMoved(MouseWheelEvent e) {
if ((e.getModifiers() & InputEvent.CTRL_MASK) == InputEvent.CTRL_MASK) {
int notches = e.getWheelRotation();
if (notches < 0) {
redrawOnZoom(true);
} else {
redrawOnZoom(false);
}
}
}
});
Is there a way of saying something like "If mouse is scrolled on its own then do default JScrollPane scrolling behaviour but If Ctrl is pressed then zoom"?
you can dispatch the event to its parent if you don't want to handle it:
final MouseWheelListener wheel = new MouseWheelListener() {
#Override
public void mouseWheelMoved(MouseWheelEvent e) {
// handle some events here and dispatch others
if (shouldHandleHere(e)) {
LOG.info("do-my-own-stuff");
} else {
LOG.info("dispatch-to-parent");
e.getComponent().getParent().dispatchEvent(e);
}
}
public boolean shouldHandleHere(MouseWheelEvent e) {
return (e.getModifiersEx() & InputEvent.CTRL_DOWN_MASK) != 0;
}
};
Hint:
Override the mouseWheelListener.
two functions : scroll() and other zoom.
Check for CTRL keyPress inside listener.
If pressed, call zoom() elsescroll()
refer tohow to write swing listener for guidence.
I've extended a JList to provide two separate functionalities, toolTipText for items, and right-click options. Both work separately, but when I try to use them together, the MouseMoved events aren't being recognized? Below are the guts of my new listener methods. How should I be negotiating these various events?
public class JListTT extends javax.swing.JList {
public JListTT() {
super();
addMouseListener(new ttListener());
...
class ttListener extends MouseAdapter {
public void mouseMoved(MouseEvent e) {
String nodeID = bldItemNodeID();
theList.setToolTipText(nodeID);
}
public void mousePressed(MouseEvent ev) {check(ev); }
public void mouseReleased(MouseEvent ev) {check(ev); }
public void mouseClicked(MouseEvent ev) {check(ev); }
public void check(MouseEvent ev) {
if (ev.isPopupTrigger()) {
theList.setSelectedIndex(theList.locationToIndex(ev.getPoint()));
menu.show(theList, ev.getX(), ev.getY());
}
}
}
You add the ttListener object as a MouseListener, but I don't see you adding the ttListener object as a MouseMotionListener. For example:
ttListener myMouseadapter = new ttListener();
addMouseListener(myMouseadapter);
addMouseMotionListener(myMouseadapter);
I did not test this myself, but looking at the javadoc of JList the tooltip functionality is available out of the box. The javadoc of JList#getTooltipText clearly states
Overrides JComponent's getToolTipText method in order to allow the
renderer's tips to be used if it has text set.
So if your ListCellRenderer returns a Component in the getListCellRendererComponent method which has a tooltip it will be displayed by the JList without the need of a listener.
there's not necessarily a need for a low-level approach as a custom mouse-/motionListener:
as to a per-cell tooltip, see #Robin's answer
as to a context menu, JComonent has a property componentPopupMenu: using that will cope with opening the menu on keyboard short-cut automatically
"not necessarily" because you seem to rely on the cell being selected on right click. If so, you would still need a MouseListener to trigger the selection (after decade long debates, Swing doesn't - which seems to be unusual in current native apps ;-)
You can achieve it by using mouseDragged
YourClass extends JPanel implements MouseListener{
......
#Override
public void mouseDragged(MouseEvent e) {
//code go here
}
}
I want to show a small popup menu when you right-click a tab, now this is working fine but when you right click it also selects that tab which is unwanted.
So my idea was to make a new class, extend JTabbedPane and recode those mouse events. Problem is that I have no idea where to start, I was browsing its source but I can't find what part is handeling the mouseEvents.
Tabs.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent me) {
if(me.getButton()==3){
int tabNr = ((TabbedPaneUI)Tabs.getUI()).tabForCoordinate(Tabs, me.getX(), me.getY());
Component clickedTab = EventsConfig.window.MainTabs.getComponentAt(tabNr);
newMenu(clickedTab, me.getX(), me.getY());
}
}
});
Beware: dirty hack ahead! The only reason I recommend it, is that I consider the behaviour (select on right press) a bug in the BasicTabbedPaneUI's Handler.
The basic idea is to grab the listener installed by the ui, remove it, wrap into a custom listener which delegates everything except a right pressed to the original and add that to the pane:
private void installMouseListenerWrapper(JComponent tabbedPane) {
MouseListener handler = findUIMouseListener(tabbedPane);
tabbedPane.removeMouseListener(handler);
tabbedPane.addMouseListener(new MouseListenerWrapper(handler));
}
private MouseListener findUIMouseListener(JComponent tabbedPane) {
MouseListener[] listeners = tabbedPane.getMouseListeners();
for (MouseListener l : listeners) {
if (l.getClass().getName().contains("$Handler")) {
return l;
}
}
return null;
}
public static class MouseListenerWrapper implements MouseListener {
private MouseListener delegate;
public MouseListenerWrapper(MouseListener delegate) {
this.delegate = delegate;
}
#Override
public void mouseClicked(MouseEvent e) {
delegate.mouseClicked(e);
}
#Override
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) return;
delegate.mousePressed(e);
}
#Override
public void mouseReleased(MouseEvent e) {
delegate.mouseReleased(e);
}
#Override
public void mouseEntered(MouseEvent e) {
delegate.mouseEntered(e);
}
#Override
public void mouseExited(MouseEvent e) {
delegate.mouseExited(e);
}
}
then you have to add JPopupMenu (or JToolTip on MouseHoverOver ) to the JTabbedPane
A possible workaround is to set your custom tab component for each tab - see JTabbedPane#setTabComponentAt(...). Add a mouse handler to your custom tab component and redispatch left click events to the tabbedPane as described at http://www.jyloo.com/news/?pubId=1315817317000.
The custom tab component can be a simple JLabel (used for the tab title) or a container for multiple components. Depending on your requirements you can e.g. add an arrow button which will open a popup menu by left clicking the related button.
This article will helpful for removing unwanted tab selection when you click right mouse button.
Stop right click Event on JTabbedPane
I liked to add more about removing Mouse Listeners.
Try to override the method rather than removing it. It's better for future code updates.
The problem is BasicTabbedPaneUI's have inner class called Handler. That handler class override Mouse Listener.
To stop right click tab selection and show pop up menu; we need to override this method in BasicTabbedPaneUI,
protected MouseListener createMouseListener() {
return getHandler();
}
To get better look and feel we should override SynthTabbedPaneUI class.
SynthTabbedPaneUI is extends BasicTabbedPaneUI.
So our inner class is like this,
private class SynthTabbedPaneUIWrapper extends SynthTabbedPaneUI
{
private MouseAdapter menuAdapter;
private MouseAdapter getMenuAdapter()
{
if (menuAdapter == null)
{
menuAdapter =
new MouseAdapter()
{
#Override
public void mouseReleased(final MouseEvent e)
{
//implement to stop right click tab selection
//implement to show pop up menu
}
};
}
}
#Override
protected MouseListener createMouseListener()
{
return getMenuAdapter();
}
}
After that we can set our custom UI object into TabbedPane.
tabbedPane.setUI(new SynthTabbedPaneUIWrapper());