开发者

Read JFrame size from JPanel

I have a Layout class which extends JFrame. Later I am adding RoadPanel which extends JPanel. At run-time is it possible to know Layout frame size in RoadPanel?

Code

class Layout extends JFrame{
    ...Something...
    RoadPanel rp = new RoadPanel();
    this.add(rp);
}

class RoadPanel extends JPanel{
    ...graphics and components...
}

Both are implemented in different Class.


What I tried so far is to send frame size into the constructor of RoadPanel. Yeah, that is so lame as it will send only once while initiated. :(

How to make this dynamic so it updates continuously?


Why I want to do this? It because...

Purpose of knowing frame size is to scale down my L开发者_JS百科ines and Arcs of RoadPanel :) But I didn't wanted scale up though. So now I can check if frame size is less than my path.getBounds2D than repaint all line and arc and fit into visible area. But when you increase frame size, RoadPanel drawing should remain same and can be zoomed-in by manually using zoom button.

Special pointer towards Andrew Thompson's answer, For better practise.


..is it possible to know Layout frame size in RoadPanel?

Use a layout (or layouts). Then it won't be necessary to know the size of the parent container.

See Laying Out Components Within a Container for details.

Update 1

How to make this dynamic so it updates continuously?

The layouts will update the sizes and positions of components automatically. For custom painting, simply call Container.getSize() at time of paintComponent().

Update 2

However purpose of knowing frame size is to scale down my Lines and Arcs of RoadPanel

In case I was not clear enough above: For custom painting, simply call Container.getSize() at time of paintComponent(). In this instance, the Container would be RoadPanel. Incidentally, this will work correctly irrespective of:

  • RoadPanel having a Border.
  • Not being in a Frame or not being the root component.


You can either pass the frame itself to the panel constructor and later query the size, or you might use getParent() which should return the direct parent of the panel. In that case it might be necessary to move further up the hierarchy until you reach the frame.

Edit: depending on what you want to achieve, I'd suggest you first try and use Andrew's suggestions and use layout managers. You should use the parent's size directly only if the layout manager doens't provide the functionality you need (note that the way that functionality is provided might be different than what you expect).


From RoadPanel try:

this.getParent().getSize();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜