Reputation: 352
I have a JPanel
, within a JScrollPanel
and when the whole program is compiled and run, a gui is displayed containing the JPanel
and the JScrollPanel
(and other components as well). Whenever a user draws something at the edge of the JPanel
(say within n pixels near the lower or left edge) then the gui should automatically resize the JPanel
, that is, increase the size of the JPanel
.
I have used mouse event listeners (MouseDragged
, MouseClicked
, MousePressed
; used for drawing) and within these listeners I set the new increased size for the JPanel
. So whenever something is drawn at the edge the JPanel
's size should be increased (and as it is within the JScrollPane
, if the increase is substantial, then a scroll bar should appear). But the resizing is not happening.
Upvotes: 0
Views: 415
Reputation: 324118
The scrollbar will appear automatically when the preferred size of the component added to the viewport of the scrollpane is greater than the size of the scrollpane. So, you need to override the getPreferrredSize()
method of you JPanel to dynamically recalculate the preferred size.
The preferred size calculation will need to take into account:
the size of all the components being painted on the panel. So yo will probably use an ArayList to track all the components. Then you just loop through the list to determine the largest width/heigh position of any component.
the mouse location when the mouse is being dragged. If this value is greater than the width/height of the above calculation then you need to use this value. You will also need to invoke revalidate()
for every mouseDragged event to make sure the layout of the component is done.
Upvotes: 1