开发者

how to get size of panel based on the size of graphics put on it

I am writing program which draw table by drawing multiple开发者_开发知识库 rectangles. The row and col of the table are set at run-time. So how do i know the size of the jpanel to display the table?


I don't know if I fully understood your question, but I'll try. If I understand correctly, you want to know what size to set the JPanel so that it can show your table.

That's the opposite of how you generally do things in Swing: instead, the component you add to the panel advertises its constraints (see getPreferredSize(), getMinimumSize() and getMaximumSize() in java.awt.COmponent). Then the layout manager you set in the panel will take care of resizing the components inside the container according to those contraints, and the current size of the window.

After you add all components to the JPanel instance, you can also use its getPreferredSize() method to get the "preferred size" of the panel with all child components laid out. (IIRC)


What you're asking can be done using methods of the graphics context's FontMetrics, but it seems tedious and error prone. As an alternative, consider the examples in the tutorial How to Use Tables.

Addendum: As suggested in @camickr's comment, the article Table Column Adjuster is a good example of how a versatile foundation component like JTable may be functionally enhanced to meet evolving needs. In contrast, drawing multiple rectangles may become progressively more difficult to maintain.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜