Binding a JTable to Swing Controls in NetBeans IDE
Recently I blogged about the Beans Binding Framework and gave a few brief examples. Questions were asked about how those examples would be achieved in NetBeans IDE, via its tooling, instead of manual coding in the editor. Here is an outline of a scenario that binds Swing controls to columns in a JTable, via the tools that NetBeans IDE provides.
- Create the application. Create a new Java Application called "TableBindingDemo". Delete the "Main.java" class that is created for you.
- Create the JFrame. Create a JFrame called "CustomerFrame".
- Create the JTable. Drag a table from the palette onto the CustomerFrame.
- Start the server. Under the Tools menu, choose Java DB Database | Start Server.
- Bind the JTable to data. Right-click the table and choose "Table Contents". In the Customizer Dialog, click "Bound" in the "Table Model" tab. Click "Import Data to Form". In the "Import Data to Form" dialog, choose the last one of the three, "vir". Once the connection is made, choose the EMPLOYEE table. Click OK. Close the Customizer Dialog.
- Bind the columns to data. Right-click the table and choose Bind | elements. Click the arrow buttons to move the 'firstname' and 'lastname' from the 'Available' list to the 'Selected' list. Click OK.Let's now run the application! Right-click the project and choose Run Project. You should now see the JTable filled with data.
- Bind Swing controls to columns in the JTable. Drag and drop two JLabels and two JTextFields onto the JFrame. Remove the text in the JTextFields and change the text of the JLabels to "Name" and "Surname". Right-click the "Name" JTextField and choose Bind | text. In Binding Source, choose jTable1. in Binding Expression, choose selectedElement | firstName. Notice that the Binding Expression is now defined as ${selectedElement.firstname}. Click OK. Do the same for the other JTextField, so that the Binding Expression for the second JTextField is set as ${selectedElement.lastname}. Right-click the project and choose Run Project. You should now see that the JTable is synchronized with the JTextFields. When you change something in the JTextField, the JTable is updated and vice versa:

- Modify the update strategy. Not happy with the way the Swing controls are synchronized? Right-click the JTextField and choose Bind | elements again. Click Advanced. There you can set Update Properties to something different.
I hope this has answered some questions about the tooling that NetBeans IDE provides for the Beans Binding Framework. If not, feel free to leave questions here and I will try to answer them!





Comments
Paul Woodruff replied on Fri, 2008/03/07 - 4:25pm
Todd Blume replied on Tue, 2008/04/01 - 4:18pm
in response to:
Patrick Keegan
Thanks for these instructions Patrick. I haven't been able to find much on the web about binding tables to collections of POJOs.
I'm trying to do the same thing as Richard Osbaldeston - except that I want to bind a JTable (or JXTable) to a List of POJOs using NetBeans tooling. I don't want to bind to a data base directly. I just want to bind to a result list. I gather from this thread that its possible to do this without hand coding special binding, but I haven't been able to reproduce the steps to do it.
Would you please provide an explicit set of steps for this use case?
Patrick wrote:
[quote]Regarding tables and column headers, you can do this in the UI without doing a special binding. In the Design view, right-click the table header and choose Table Columns. Then select the Columns tab. You can then type in the label text that you want for each of the columns.[/quote]and [quote]Actually, in this case, I'm talking about doing that *after* you have already done the binding. The use case I'm thinking of is that you have done your binding already, but that the generated column titles (based on column names in the entity class) don't look exactly how you would want your user to encounter them.[/quote]
I've created a MyPojoList class that extends ArrayList<myEntityClass> and added it to the Palette. Then I placed an instance of this class on the form so that it would appear in the Binding Source pull-down in the elements binding dialog. The default constructor creates an empty list.
Question: Is this the only/best way to make a List available for binding? What interfaces must MyPojoList implement to work with the tooling - ie. any special design-time suport? Or should any collection implementation do?
Next I select my JTable and set Binding | elements. I set the Binding Source to my instance of MyPojoList. I do not use "Import Data to Form..." because I don't want to bind directly to the database. When I set the binding the JTable disappers. I think that the table model generation is failing.
Anyone like to share a simple example of using Netbeans tooling to bind a JTable to a List<myPOJO> where the list is populated at runtime?
Peter ___ replied on Tue, 2008/04/29 - 4:17pm
in response to:
Paul Woodruff
Hi Paul,
is jpox: http://www.jpox.org that what you need??
Regards.
Peter ___ replied on Tue, 2008/04/29 - 4:31pm
in response to:
Todd Blume
Hi Todd,
if you want to create a list (e.g. consumerList) in NetBeans that you can easily bind (without knowing the db schema), you can try the following. Go to the Form Inspector. Right click 'Other Components'->'add from palette'->Java Persistence->Query Result. Change the name to consumerList. Then you only need to call:
createColumnsFromDB(Consumer.class, consumerList, consumerTable);
after initComponents(). Hope this helps.
Regards,
Peter.
public static void createColumnsFromDB(Class<?> clazz, List list, JTable table, BindingListener bl) {
BindingGroup myBindingGroup = new BindingGroup();
JTableBinding tableBinding =
SwingBindings.createJTableBinding(UpdateStrategy.READ_WRITE, list, table);
JTableBinding.ColumnBinding columnBinding;
Field fields[] = clazz.getDeclaredFields();
for (Field f : fields) {
// include only primitive types and String
Class<?> clazzOfField = toWrapper(f.getType());
String name = f.getName();
if (clazzOfField == null || f.getName().toLowerCase().equals("id")) {
continue;
}
columnBinding = tableBinding.addColumnBinding(ELProperty.create("${" + name + "}"));
columnBinding.setColumnName(name);
columnBinding.setColumnClass(clazzOfField);
}
//One example:
//columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${customerId}"));
//columnBinding.setColumnName("Customer Id");
//columnBinding.setColumnClass(Integer.class);
// observe changes to every single property
myBindingGroup.addBindingListener(bl);
myBindingGroup.addBinding(tableBinding);
myBindingGroup.bind();
}
public static Class toWrapper(Class clazz) {
if (Number.class.isAssignableFrom(clazz)) {
return clazz;
} else if (clazz.equals(int.class)) {
return Integer.class;
} else if (clazz.equals(long.class)) {
return Long.class;
} else if (clazz.equals(boolean.class)) {
return Boolean.class;
} else if (clazz.equals(float.class)) {
return Float.class;
} else if (clazz.equals(double.class)) {
return Double.class;
} else if (clazz.equals(short.class)) {
return Short.class;
} else if (clazz.equals(String.class)) {
return String.class;
} else {
return null;
}
}
Joshua Kafeero replied on Fri, 2008/05/02 - 7:45am
When a POJO collection is bound to a table, it seems to kill the event processing of any components that are in any of the table columns. Is there a solution to this problem?
This also occurs in the Visual Web components at least with NetBeans 6.1. When one uses a DataProvider everything works fine but on using a List<PojoClass>, the list gets displayed but any buttons that might be in a column don't fire events.
Any advice would extremely welcome.
Thanks.
Josh.
Bruno Lopes replied on Sun, 2008/05/18 - 7:57pm
I've been readind a lot about data binding in Netbeans and I'm wondering if someone could please help me and tell me how do I bind a two table query into a jTable?
How do I bind this query "Select * From Trip, TripType" to a jTable?
Thank you!
jason woo replied on Mon, 2008/06/09 - 5:45pm
Any help here is seriously appreciated, in fact I'd be happy to paypal someone $10 USD if they can figure this out. To make it "easy", I've posted my issue as a video. All I'm trying to do is have a collection of Plain-Old-Objects (POJs) sync up with a database (in fact, I'd rather sync up with the local file system, but that doesn't seem to be an option) and a JTable. Anyway, the link is below, login as 'randomjavahelper' with password 'bringerofjava'
http://www.youtube.com/watch?v=7Lp9aR1-mtI
If you figure it out, shoot me an e-mail, take my username and append the gmail domain to get my e-mail address.
jason woo replied on Tue, 2008/06/10 - 9:17am
in response to:
jason woo
after some 'extreme' head banging on desk, I found out netbeans wasn't auto-generating the "right" code! Here is the list to which my JTableBinding must be bound, everything works perfectly now! (the new code creates the jimstableList from the ObservableCollections method):
jawad arshad replied on Sat, 2008/06/21 - 6:53am
hi thanks for your post
can you guide me how can i dynamically bind the jtable with a resultset or rowset object and how can i dynamically update the data in the resultset or rowset through jtable. thanks a lot
Siamak sarmady replied on Thu, 2008/10/09 - 4:10am
Sorry, but after I edit table data, the data is not synchronized with the database (even though my binding settings is read/write i.e. in advanced settings of table bind).
What should I do to make it update database ?
thanks
Ken Li replied on Wed, 2008/11/19 - 6:19pm
Thank you for the blog, which is very useful.
I have a question relating to JPA and the JTable binding. Suppose I add two columns in the database table, say dateTimeCreated, and dateTimeModified, and the two properties will add into the generated entity class of course. I will change the dateTimeModified if the action is an update, and add those two, if the I want add a new entry. but I don't want to do that manually, instead, I'd like to set a new Date() into the object(s) when a save button is clicked.
My question is: is there a simple way to find out which object from the binding list(or the persistent context) is an update one and which one is a new?
Thank you very much for your attention.
Regards,
Ken
Alban Abulime replied on Fri, 2008/11/21 - 8:14pm
priya gurnani replied on Thu, 2009/01/15 - 4:39am
actualy i need help
i m making a software in java swing
i hv a problem in retriving values from database in JTable,
i m inserting values in database ms access it works,
following is my code one is for database another one for table
.....................................................................................................................................
import java.sql.*;
public class JDta
{
public void putz(String x,String y)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:pproject","","");
PreparedStatement stmt=con.prepareStatement("insert into data values(?,?)");
stmt.setString(1,x);
stmt.setString(2,y);
stmt.executeUpdate();
stmt.close();
con.close();
}
catch(Exception er)
{
}
}
public boolean checking(String x,String y)
{
int coun=0;
boolean bb;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:exams","","");
PreparedStatement stmt=con.prepareStatement("select * from data where name=? and pass=?");
stmt.setString(1,x);
stmt.setString(2,y);
ResultSet rs=stmt.executeQuery();
while(rs.next())
{
coun++;
}
stmt.close();
con.close();
}
catch(Exception er)
{
}
if(coun>0)
bb=true;
else
bb=false;
return bb;
}
}
......................................................................................................................................
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Logger extends JFrame implements ActionListener
{
JButton jb1,jb2;
JLabel jl1,jl2,jl3;
JTextField jtf;
JPasswordField jp;
String x;
String y;
public Logger()
{
jl1=new JLabel("<html><center><font face=Maiandra GD size=5><u>Welcome to</u><p>School Management System</font></html>");
Container cont=getContentPane();
jl2=new JLabel("Enter Name");
jl3=new JLabel("Enter Password");
JPanel jpp=new JPanel();
jpp.setLayout(null);
jtf=new JTextField(10);
jp=new JPasswordField(10);
jpp.add(jl1);
jpp.add(jl2);
jpp.add(jl3);
jpp.add(jtf);
jpp.add(jp);
jb1=new JButton("Save");
jb1.addActionListener(this);
jpp.add(jb1);
jl1.setBounds(80,5,300,80);
jl2.setBounds(100,75,120,10);
jl3.setBounds(100,78,300,80);
jtf.setBounds(205,75,120,20);
jp.setBounds(205,105,120,20);
jb1.setBounds(205,135,70,29);
cont.add(jpp);
setTitle("Log In");
setSize(500,200);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
x=jtf.getText();
y=jp.getText();
JDta jxy=new JDta();
jxy.putting(x,y);
dispose();
}
public static void main(String aa[])
{
new Logger();
}
}
......................................................................................................................................
rani mudaly replied on Sun, 2009/03/22 - 11:48am
Hello
I am currently working with netbeans and ms access - I want my program to do the following :
- connect to the database from Netbeans
- display records in table form(in netbeans) from the database
- bind the table
- use of a radio button
- the option to listen to music
If someone could help me with a sample program I would be very grateful.
NB : database has to be MS Access.
Thanks
Rani
Muthu Raj replied on Wed, 2009/08/05 - 2:09am
jayalal Chandana replied on Tue, 2009/09/15 - 7:57pm
Somenath Roy replied on Tue, 2009/09/22 - 4:21am
While doing a database programming through NetBeans I can not find bind option in NetBeans 5.5.1. Please tell me how can I do it. I have come to know that there is "bound" option in it but still I can't find it.
Sreenath Ganga replied on Tue, 2010/07/13 - 1:37am
Akinwumi Ayotunde replied on Thu, 2010/12/23 - 2:13am
Jessica Chin replied on Wed, 2011/03/16 - 7:04am
Matt Coleman replied on Tue, 2012/06/12 - 1:32am
in response to:
priya gurnani
this codes solved my problems...thanks for sharing Priya
website design buffalo
Mateo Gomez replied on Tue, 2012/06/12 - 11:59pm
wonderful tutorials..and the swing controls makes it a lot better! mexican dip recipes
Steve Sdas replied on Mon, 2012/11/26 - 4:04am
Steve Sdas replied on Thu, 2012/11/29 - 3:26am
Steve Sdas replied on Thu, 2012/11/29 - 9:41am
Steve Sdas replied on Fri, 2012/11/30 - 3:42am
Steve Sdas replied on Sat, 2012/12/01 - 4:59am
Steve Sdas replied on Sat, 2012/12/01 - 5:54am
Steve Sdas replied on Mon, 2012/12/03 - 11:36am
Steve Sdas replied on Tue, 2012/12/04 - 3:35am