We help IT Professionals succeed at work.

How to align a textfield in a jpanel to jtable columns

neverton
neverton asked
on
Hi,
  I'm creating an application and I'm having issues getting a jpanel with textfields to align to columns in a jtable.

  The application is basically a jtable with 9 columns, from left to right they are;
Description,MonthSales,SameMonthLastYear,Difference,Percentage,YearSales,LastYearSales,Difference,Percentage.

 Beneath the jtable i have created a jpanel of the same width as the table. and in this I have placed 9 textfields, to act as total boxes for the respective columns (the textfield below the Description column just says Totals). I can get the textfields to display the correct values, the only thing I cannot do is get the textfields to line up directly below the corresponding jtable column.

 I have a function which gets the width of the Description column, and sets the first jtextfield to the same width, the problem I have got is that the width of the jtextfield doesnt match the width of the jtable column, its out by almost half.

  I've checked the font and font size, they're all the same, so I'm baffled why my textfield.setWidth function isnt setting the textfield to the same width as the jtable column.

  The application was created using Netbeans, and I've just created a panel and dragged in the textfields.

 I've tried Free Layout and Box Layout, so I've not sure if its a layout issue, netbeans and me not understanding the width on a jtable is different to a width on a textfield
Comment
Watch Question

Top Expert 2016

Commented:
Wouldn't it perhaps be better to use another single-row table?

Author

Commented:
Hi,
  I did quickly try that, but couldnt see an option in netbeans to to disable the table header from displaying. Thats when I moved onto doing it as a series of textfields, will have to look to see if I can remove the header, more speed, less haste I believe the phrase is!!
Top Expert 2016
Commented:
Well actually, if you don't add the table to a scroll pane, the header shouldn't show
Mick BarryJava Developer
Top Expert 2010

Commented:
make your totals a part of JTable in an extra row
heres an example
http://www.java2s.com/Code/Java/Swing-Components/TotalCalculateRowExample.htm

Author

Commented:
Hi objects,
   I did consider this, but the hassle of freezing the bottom row on screen (there's sometimes several thousand results) was too much for my current java skills
Mick BarryJava Developer
Top Expert 2010

Commented:
its actually quite easy. and better than having columns that don't consistently align as you'll get with using two tables. using two tables is just a poor workaround.

Author

Commented:
Hi objects, thanks for the reply, I'll look into it for the next revision of the software, or later if I get the chance.

Top Expert 2016

Commented:
:-)
Mick BarryJava Developer
Top Expert 2010

Commented:
sure, let me know when you want to do it properly :)