OpenImaj - Using a MouseListener with JFrame - java

I'm attempting to add mouse listening capabilities to a JFrame that displays an MBFImage and the mouse events do absolutely nothing. I'm not sure if the events are not firing or if they are and not being caught because I am doing something wrong...
The image shows up in the JFrame just fine, however moving the mouse around over the image, clicking, moving, dragging, etc. does not result in any activity.
NOTE 1 I've discovered that if I add the mouselistener to a JPanel and then (in this specific order) draw the image and then add the the JPanel to the JFrame, that the mouse listener catches the events, but ONLY listens outside of the image. It draws a minimum size window which I need to resize. Any mouse movement over the image does not seem to fire / catch any events.
NOTE 2 If I add the panel to the JFrame and then draw the image, the window size is just fine, however the mouse listener no longer work.
Can anyone shed any light?
Here is the relevant portion of my code:
private JFrame displayImage(final MyAppImage image, final MyAppImage.DetectLevel level, String title) {
MBFImage mbfImg = image.drawDetections(level); //draws face detection boxes
JFrame imgFrame = new JFrame(title);
DisplayUtilities.display(mbfImg, imgFrame);
imgFrame.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
System.out.println("here");
if (level == MyAppImage.DetectLevel.filtered) {
if (image.checkPoints(e.getX(), e.getY(), level) != null) {
System.out.println("YES");
}
else {
System.out.println("NO!");
}
}
else {
System.out.println("Huh?");
}
}
#Override
public void mouseExited(MouseEvent e) {
}
});
imgFrame.addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent e) {
System.out.println("hello");
}
#Override
public void mouseMoved(MouseEvent e) {
System.out.println("here");
if (level == MyAppImage.DetectLevel.filtered) {
if (image.checkPoints(e.getX(), e.getY(), level) != null) {
System.out.println("YES");
}
else {
System.out.println("NO!");
}
}
else {
System.out.println("Huh?");
}
}
});
return imgFrame;
}

Exactly what #MadProgrammer commented - when you call DisplayUtilities.display(mbfImg, imgFrame); it creates an ImageComponent inside your JFrame that is itself a MouseListener.
You should be able to add a MouseListener to the ImageComponent directly however.

Related

Java - Cursor position relative to JFrame

Trying to have an object follow the cursor using:
int mx =(int) MouseInfo.getPointerInfo().getLocation().getX()-50;
Player.setX(mx);
in my tick method. However, this returns cursor position on screen, how can I make it relative to the JFrame itself? Is there maybe a way to read the position of the top-left point in the canvas so i can add an offset ?
Create a mouse listener, and fetch the coordinates from there:
public class SimpleFrame extends JFrame {
public static void main(String[] args) {
SimpleFrame frame = new SimpleFrame();
frame.setSize(new Dimension(200, 300));
frame.setLocation(new Point(500, 600));
frame.setVisible(true);
frame.addMouseListener(new MouseListener() {
#Override
public void mouseReleased(MouseEvent e) {
System.out.println(e.getX() + " / " + e.getY());
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseClicked(MouseEvent e) {
}
});
}
}
When you test this, you probably realize that you want to have the coordinates relative to something else, for example the main panel of your application. Then you create the mouselistener for that component:
SimpleFrame frame = new SimpleFrame();
JPanel mainPanel = new JPanel();
frame.add(mainPanel, ...);
mainPanel.addMouseListener(...
It is much better to do it this way, than to start substracting constants from the coordinates you get from the JFrame's mouseListener, since those "constants" will differ depending on OS etc.
And if you want to have event whenever the user moves the mouse, not only when he/she clicks it, use this:
frame.addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseMoved(MouseEvent e) {
System.out.println(e.getX() + " / " + e.getY());
}
#Override
public void mouseDragged(MouseEvent e) {
});

How do I make a JPopupMenu appear when any one of 3 JButtons is clicked, right-clicked, or dragged upon?

I am trying to make a set of navigation buttons for a file browser. I want it so that if the user clicks the dedicated history button, a JPopupMenu appears. However, I also want that exact same menu to appear when the user right-clicks or drags the cursor down the back or forward button. How can I make that exact same JPopupMenu (not a copy, but the same exact one) appear for multiple GUI components for different gestures?
So far I've tried the following:
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());
}
});
All components are added and display correctly, and debugging shows me that they register the events, but no menu appears.
Bringing Up a Popup Menu shows the traditional implementation using mousePressed(), mouseReleased() and isPopupTrigger(). Note that "The exact gesture that should bring up a popup menu varies by look and feel." You might compare what's shown with your implementation, which uses mousePressed().
Addendum: For reference, #mKorbel recalls this client property that may prove useful.
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();
}
});
}
}

Moving undecorated window by clicking on JPanel

Is there a possibility to move window by clicking on one of the panels in the window when that window is undecorated?
I have a main panel with matte border 40 pixels size, and few panels with controls inside, and I would like to move the window when clicking on that border. Is that possible?
You can place another panel over the panel with the border, leaving the border visible.Use the following code to move your window.
public class MotionPanel extends JPanel{
private Point initialClick;
private JFrame parent;
public MotionPanel(final JFrame parent){
this.parent = parent;
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
initialClick = e.getPoint();
getComponentAt(initialClick);
}
});
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
// get location of Window
int thisX = parent.getLocation().x;
int thisY = parent.getLocation().y;
// Determine how much the mouse moved since the initial click
int xMoved = e.getX() - initialClick.x;
int yMoved = e.getY() - initialClick.y;
// Move window to this position
int X = thisX + xMoved;
int Y = thisY + yMoved;
parent.setLocation(X, Y);
}
});
}
}
I've been working with this code for a while now to make a custom titlebar for undecorated windows.
P.S.:You can generalize this example by extending JComponent instead of JPanel.
I have a main panel with matte border 40 pixels size, and few panels with controls inside, and I would like to move the window when clicking on that border
I think that ComponetMover by #camickr is right class for you
Yes, it is very possible. You need a MouseListener to listen on mouse events. you start moving on mousedown and stop moving on mouseup. Then you simply translate the window position by the same amount the mouse translates during that phase (calculate the delta bewteen old mouse position and new mouse position and add that to the frames position). You should be able to do this with a mouse listener fairly easily.
I have a simple solution from my project. Here is my undecorated JDialog class.
public class TimerDialog extends JDialog {
// some fields here
private Point mouseClickPoint; // Will reference to the last pressing (not clicking) position
private TimerDialog() {
initComponents();
addEventsForDragging();
}
private void addEventsForDragging() {
// Here is the code does moving
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
mouseClickPoint = e.getPoint(); // update the position
}
});
addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
Point newPoint = event.getLocationOnScreen();
newPoint.translate(-mouseClickPoint.x, -mouseClickPoint.y); // Moves the point by given values from its location
setLocation(newPoint); // set the new location
}
});
}
private void initComponents() {
setLayout(new FlowLayout());
// adding components
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setAlwaysOnTop(true);
setUndecorated(true);
setResizable(false);
pack();
}
}
int xMoved = (thisX + e.getX()) - (thisX + initialClick.x);
thisX + -thisX = 0
int xMoved = e.getX()-initialClick.x;
What i'm using.
public class MouseLiestenerX implements MouseListener,MouseMotionListener{
private theFrame;
public MouseLiestenerX(Frame theFrame){
this.theFrame = theFrame;
}
private Point startClick;
public void mouseDragged(MouseEvent e) {
int deltaX = e.getX()-startClick.x;
int deltaY = e.getY()-startClick.y;
Core.getSp().setLocation(theFrame.getLocation().x+deltaX, theFrame.getLocation().y+deltaY);
}
public void mousePressed(MouseEvent e) {
startClick = e.getPoint();
}
public void mouseMoved(MouseEvent e){
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
}
}
and in your Frame constructor
MouseLiestenerX IMove = new MouseLiestenerX(this);
addMouseListener(IMove);
addMouseMotionListener(IMove);

JButton breaks my Keylistener

JAVA USING NETBEANS
Hello stackoverflow, i have a problem i would like help with. In a nutshell, I have a mouselistener and a keylistener on a jpanel, everything works fine except when i press one of my jbuttons, then the keylistener goes AWOL. Can any1 explain the problem, is the panels focus now on the buttons instead of the keyboard, im at a lost.
Here is the code, if somethings are not reference, assume its are there the entire panel code was 500+ long so i cut quite a bit.
Thanks in advance for any help.
package tankgame;
public class TankPanel extends JPanel implements KeyListener,
MouseListener,MouseMotionListener
{
JButton back,shop, menu, health, speed, rapidfire, shootradius;
TankPanel()
{
setLayout( null );
addMouseListener(this);
addMouseMotionListener(this);
addKeyListener(this);
setFocusable(true);
shop= new JButton("SHOP");
shop.addMouseListener(this);
shop.setBounds(400,0, 80,15);
add(shop);
}
public void keyPressed(KeyEvent k)
{
char c = k.getKeyChar();
if(c=='u')
{
u++;
System.out.println(u+" = u");
}
if(c=='i')
{
i++;
System.out.println(i+" = i");
}
if( c == 'd' )
{
if(Ptank.pic==PlayerTankE)
{
if(Ptank.move==true)
{
Pbarrel.x+=Ptank.speed;
Ptank.x+=Ptank.speed;
}
}
else
{
if(Ptank.pic==PlayerTankN || Ptank.pic==PlayerTankS)
{
Ptank.x = Ptank.x - 5;
Ptank.y=Ptank.y+5;
}
Ptank.setPic(PlayerTankE);
Ptank.width=35;
Ptank.height = 23;
}
}
setFocusable(true);
repaint();
}
public void keyReleased(KeyEvent k)
{
}
public void keyTyped(KeyEvent k)
{
}
public void mouseClicked(MouseEvent e)
{
//Invoked when the mouse button has been clicked (pressed and released)
}
public void mouseEntered(MouseEvent e)
{//Invoked when the mouse enters a component.
}
public void mouseExited(MouseEvent e)
{ //Invoked when the mouse exits a component.
}
public void mousePressed(MouseEvent e)
{//Invoked when a mouse button has been pressed on a component.
if(e.getSource()==back)
{
System.out.println(456);
System.out.println(back.getLocation().x + " "+back.getLocation().y);
}
else if(e.getSource() == menu)
{
changebuttons("menu");
System.out.println(456);
System.out.println(menu.getLocation().x + " "+menu.getLocation().y);
}
else if(e.getSource() == shop)
{
changebuttons("shop");
System.out.println(456);
System.out.println(shop.getLocation().x + " "+shop.getLocation().y);
}
else if(e.getButton() == MouseEvent.BUTTON1)
{
destpoint= new Point();
destpoint.setLocation(mousex, mousey);
origin = new Point();
}
for(int i = 0; i< Ptank.rapidfire; i++)
{
if (origin.distance(destpoint) <= 100 && origin.distance(destpoint) >= 50)
{
Bullet add = new Bullet(this,destpoint);
add.getOrigin(origin);
add.setPic(PlayerBullet);
add.width=4;
add.height=4;
bulletList.add(add);
}
}
}
}
public void mouseReleased(MouseEvent e)
{//Invoked when a mouse button has been released on a component.
}
public void mouseDragged(MouseEvent e)
{//Invoked when a mouse button is pressed on a component and then dragged.
}
public void mouseMoved(MouseEvent e)
{
//Invoked when the mouse cursor has been moved onto a component but no buttons
Cursor cursor = Cursor.getDefaultCursor();
//you have a List<Polygon>, so you can use this enhanced for loop
cursor = Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR);
setCursor(cursor);
mousex=e.getX();
mousey=e.getY();
}
public void changebuttons(String x)
{
if(x.equals("shop"))
{
menu.setBounds(720, 0, 80, 15);
health.setBounds(0, 0, 125, 15);
speed.setBounds(150, 0, 125, 15);
shootradius.setBounds(300, 0, 200, 15);
rapidfire.setBounds(500, 0, 150, 15);
shop.setBounds(1000, 0, 150, 15);
}
}
KeyEvents are only generated on a component that has focus. When you click on the button is now has focus to key events won't be generated on the panel. You need to add:
panel.requestFocusInWindow()
in your ActionListener to give focus back to the panel.
However the better solution is to use Key Bindings as you can add bindings to a KeyStroke even when the component doesn't have focus.
Don't use a KeyListener which requires the component be focused to work. Instead consider using Key Bindings. You can find out how to use these guys at the Swing tutorial: How To Use Key Bindings. If you need more specific help, you will want to post a much smaller bit of code than you show above, code that is self-contained and will actually compile and run for us, an SSCCE.

Making a component less sensitive to Dragging in Swing

A JComponent of mine is firing a mouseDragged event too vigorously. When the user is trying to click, it interprets is as a drag even if the mouse has only moved 1 pixel.
How would I add a rule for a particular component that amounted to:
Do not consider it a drag event unless
the mouse has moved 10 pixels from the
point at which is was pressed down.
Note: I know it's not a system setting in my OS, since only events on that component suffer from this over sensitivity.
Thank you.
Previous answers combined together, with proper event type:
public class DragInsensitiveMouseClickListener implements MouseInputListener {
protected static final int MAX_CLICK_DISTANCE = 15;
private final MouseInputListener target;
public MouseEvent pressed;
public DragInsensitiveMouseClickListener(MouseInputListener target) {
this.target = target;
}
#Override
public final void mousePressed(MouseEvent e) {
pressed = e;
target.mousePressed(e);
}
private int getDragDistance(MouseEvent e) {
int distance = 0;
distance += Math.abs(pressed.getXOnScreen() - e.getXOnScreen());
distance += Math.abs(pressed.getYOnScreen() - e.getYOnScreen());
return distance;
}
#Override
public final void mouseReleased(MouseEvent e) {
target.mouseReleased(e);
if (pressed != null) {
if (getDragDistance(e) < MAX_CLICK_DISTANCE) {
MouseEvent clickEvent = new MouseEvent((Component) pressed.getSource(),
MouseEvent.MOUSE_CLICKED, e.getWhen(), pressed.getModifiers(),
pressed.getX(), pressed.getY(), pressed.getXOnScreen(), pressed.getYOnScreen(),
pressed.getClickCount(), pressed.isPopupTrigger(), pressed.getButton());
target.mouseClicked(clickEvent);
}
pressed = null;
}
}
#Override
public void mouseClicked(MouseEvent e) {
//do nothing, handled by pressed/released handlers
}
#Override
public void mouseEntered(MouseEvent e) {
target.mouseEntered(e);
}
#Override
public void mouseExited(MouseEvent e) {
target.mouseExited(e);
}
#Override
public void mouseDragged(MouseEvent e) {
if (pressed != null) {
if (getDragDistance(e) < MAX_CLICK_DISTANCE) return; //do not trigger drag yet (distance is in "click" perimeter
pressed = null;
}
target.mouseDragged(e);
}
#Override
public void mouseMoved(MouseEvent e) {
target.mouseMoved(e);
}
}
I've had to do exactly this before. Here's my mouse event processing code, cut down to just the bits relating to making drag require a few pixels before being treated as a drag.
public void mousePressed(int mod, Point loc) {
pressLocation=copyLocation(loc,pressLocation);
dragLocation=null;
}
public void mouseReleased(int mod, Point loc) {
if(pressLocation!=null && dragLocation!=null) {
// Mouse drag reverted to mouse click - not dragged far enough
// action for click
pressLocation=null;
}
else if(dragLocation!=null) {
// action for drag completed
}
else {
// do nothing
}
pressLocation=null;
dragLocation=null;
}
public void mouseDragged(int mod, Point loc) {
if(pressLocation!=null) { // initial drag actions following mouse press
dragLocation=pressLocation; // consider dragging to be from start point
if(Math.abs(loc.x-pressLocation.x)<dragMinimum && Math.abs(loc.y-pressLocation.y)<dragMinimum) {
return; // not dragged far enough to count as drag (yet)
}
// action drag from press location
pressLocation=null;
}
else {
// action drag from last drag location
dragLocation=copyLocation(loc,dragLocation);
}
}
And note, I also had problems with Java some JVM's generating click events after dragging, which I had to detect and suppress.
If I read your question correctly, you're tracking both click and mousedrag events. Can you track the coordinates upon mousedown, followed by a short computation in mousedrag to see if the mouse has moved your desired minimum numbers of pixels? Of course, you then also want to cancel/reset on mouseup or when the mouse is dragged outside the bounds of your JComponent.
Caveat: I haven't done this myself, but I think it's where I'd start if it were me.
Software Monkey's code seemed to be missing some code, so I wrote this solution:
navigationTree.addMouseListener(new DragInsensitiveMouseClickListener(10) {
#Override
public void mouseClicked(MouseEvent e) {
TreePath treePath = navigationTree.getPathForLocation(e.getX(), e.getY());
if(treePath != null) {
processChoice();
}
}
});
This will still fire the mouseClicked() event when the user produces at most 10 pixels of "drag travel".
The code for the click listener:
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class DragInsensitiveMouseClickListener extends MouseAdapter {
private final int allowedTravel;
public Point mouseDownPoint;
public DragInsensitiveMouseClickListener(int allowedTravel) {
this.allowedTravel = allowedTravel;
}
#Override
public void mousePressed(MouseEvent e) {
mouseDownPoint = e.getPoint();
}
#Override
public void mouseReleased(MouseEvent e) {
double horizontalTravel = Math.abs(mouseDownPoint.getX() - e.getX());
double verticalTravel = Math.abs(mouseDownPoint.getY() - e.getY());
if (horizontalTravel < allowedTravel && verticalTravel < allowedTravel) {
mouseClicked(e);
}
}
}

Categories

Resources