Real-time JFrame height and width listening

I have a situation where I would like to know the height and width of the JFrame, when the user drags with the mouse to resize the frame.

I researched this, and the answers provided on the following question helped me a little, but not completely: Listen to JFrame resize events when the user drags them?

My problem: I made my "HSFrame" class a JFrame extension and implemented an ActionListener, MouseMotionListener (ActionListener is not relevant to this, however). This issue is MouseMotionListener.

I have a separate class called "CanvasPanel" that extends JPanel - this is where I use a graphics object to update information in real time by drawing lines.

public void mouseMoved(MouseEvent e) { } public void mouseDragged(MouseEvent e) { validate(); canvas.repaint(); } 

This is a piece of code from my "HSFrame" class (extends JFrame, implements MouseMotionListener). In this code example, "canvas" is a CanvasPanel object, and I call its repaint () method whenever MouseDragged is called.

I decided to use MouseMotionListener because it (presumably) will give me real-time updates, not the ComponentListener componentResized () method (which is attached to MouseReleased).

Everything updates 100% perfectly when I resize the frame in the upper left corner. The values ​​for height, width, X and Y are completely redrawn.

But it does not update in real time when I resize from the lower right corner. And I do not know about you, but I prefer to resize from the bottom right.

In the "CanvasPanel" class itself, I expanded the ComponentListener and added a listener to the "HSFrame" object there - it does not update in real time, which was fine, but it redrawn the height and width after the mouse freed up, no matter in which corner it was changed HSFrame size.

Main question: Is it possible to make MouseMostionListener 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 in the upper left corner (which also interacts with the title). It just doesn't hear when something happens on other JFrame borders.

+4
source share
1 answer

You do not need to do this with the mouse! Make it easy: Write a component listener . The HSFrame implements the ComponentListener and puts the resize code in public void componentResized(ComponentEvent e) .

I think that mouseListener will not work, because when you drag from bottom to right, your mouse is not in the JFrame , so the event listener does not raise it.

+3
source

Source: https://habr.com/ru/post/1388218/


All Articles