Reputation: 73
I've got a situation where I would like to be able to know a JFrame's height and width as the user drags their mouse to resize the frame.
I researched this, and the answers provided at the following question helped me a tiny bit, but not all the way: Listen to JFrame resize events as the user drags their mouse?
My problem is: I have made my "HSFrame" class extend JFrame and implement ActionListener, MouseMotionListener (ActionListener is irrelevant to this question, however). What this question pertains to is MouseMotionListener.
I have a separate class called "CanvasPanel" that extends JPanel--this is where I use a graphics object to update real-time information by drawing strings.
public void mouseMoved(MouseEvent e)
{
}
public void mouseDragged(MouseEvent e)
{
validate();
canvas.repaint();
}
This is a code excerpt from my "HSFrame" class (extends JFrame, implements MouseMotionListener). In this code example, "canvas" is a CanvasPanel object, and I am calling its repaint() method whenever MouseDragged is called.
I chose to use a MouseMotionListener because this (supposedly) would give me real-time updates as opposed to ComponentListener's componentResized() method (which is tied to MouseReleased).
Everything updates 100% perfectly when I resize the frame from the top-left corner. The height, width, X, and Y values all repaint perfectly.
But it does not update in real-time when I resize from the bottom-right corner. And I don't know about you, but I prefer to resize things from the bottom-right.
In the "CanvasPanel" class itself, I extended ComponentListener and added a listener to an "HSFrame" object there--it does not update in real-time, which was fine, but it does repaint the height and width after the mouse is released, regardless of which corner the HSFrame was resized with.
Main question: Is it possible to get the MouseMostionListener to know that I am resizing the JFrame from the bottom-right? It hears when I move the frame around by clicking and dragging the title bar, and it hears when I resize from the top-left corner (which is also interacting with the title bar). It just doesn't hear when anything goes on to the other borders of the JFrame.
Upvotes: 4
Views: 1040
Reputation: 5133
You don't have to do this with the mouse! Do it the easy way:
Write a component listener. Have HSFrame implement ComponentListener
and put your resize code in public void componentResized(ComponentEvent e)
.
I think that the mouseListener won't work because when you're dragging from the bottom right your mouse is not in the JFrame
, so the event listener doesn't pick it up.
Upvotes: 3