tags:

views:

39

answers:

2

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?

+1  A: 

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)

vanza
Thank you for your answer. Actually, I'm trying to draw rectangles to represent table cell and put string inside the rectangle as data. The rectangle's size and their number are set inside paintComponent. Then the table is displayed in a panel in a frame. What i want to know is how to set the exact size of the panel based on the size of the table drawn by paintComponent. Thanks in advance
tsmakalagy
@tsmakalagy: As @vanza suggests, a suitable layout manager will do much of the work for you. Here is a "A Visual Guide to Layout Managers" http://download.oracle.com/javase/tutorial/uiswing/layout/visual.html
trashgod
+1  A: 

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.

trashgod
+1, don't reinvent the wheel, use a JTable. The Table Column Adjuster (http://tips4java.wordpress.com/2008/11/10/table-column-adjuster) can help you with the proper sizing of columns.
camickr