Geertjan is a DZone Zone Leader and has posted 466 posts at DZone. You can read more from them at their website. View Full User Profile

Binding a JTable to Swing Controls in NetBeans IDE

02.20.2008
| 142375 views |
  • submit to reddit

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.

  1. Create the application. Create a new Java Application called "TableBindingDemo". Delete the "Main.java" class that is created for you.
  2. Create the JFrame. Create a JFrame called "CustomerFrame".
  3. Create the JTable. Drag a table from the palette onto the CustomerFrame.
  4. Start the server. Under the Tools menu, choose Java DB Database | Start Server.
  5. 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.
  6. 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.
  7. 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:

  8. 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!

 

Published at DZone with permission of its author, Geertjan Wielenga.

Comments

Paul Woodruff replied on Fri, 2008/03/07 - 4:25pm

Is there a simple way of doing something like this example but using a jtable (in Netbeans) with a db4o database? Every example I find seems to focus on standard MySQL or Derby databases.

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 Karussell 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 Karussell 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):

 

jimstableList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(jimstableQuery.getResultList());

...

org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jimstableList, jTable1);

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

Please i'm trying to bind a JTable to a table in the database and anytime I right-click the JTable and select bind and then "Import to form" an error message prompts up saying i cannot import that it does not support this package..blah blah. Pls can anyone help on how i go about binding my tables. Thanks.

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

no comments

jayalal Chandana replied on Tue, 2009/09/15 - 7:57pm

I want you

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

Iam new in java swing and can anyone pls help me by giving the syntax to read value from a jtable and enter data to jtable plzzzzzzzzzzz

Akinwumi Ayotunde replied on Thu, 2010/12/23 - 2:13am

Pls am new here,can anyone help me on how to populate JTable from database and using "WHERE CLAUSE"to retrived a specific row in the database,using Netbean IDE.Thanks Akinwumi Ayotune

Jessica Chin replied on Wed, 2011/03/16 - 7:04am

Hi, i am using HSQLDB and i've followed your tutorial exactly. However, the following prompted out: [TopLink Info]: 2011.03.16 07:59:11.657--ServerSession(9142687)--TopLink, version: Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007)) [TopLink Info]: 2011.03.16 07:59:12.606--Not able to detect platform for vendor name [HSQL Database Engine]. Defaulting to [oracle.toplink.essentials.platform.database.DatabasePlatform]. The database dialect used may not match with the database you are using. Please explicitly provide a platform using property toplink.platform.class.name. [TopLink Info]: 2011.03.16 07:59:13.209--ServerSession(9142687)--file:/C:/Users/Jessica/Documents/NetBeansProjects/ADT/src/-databasePU login successful BUILD SUCCESSFUL (total time: 15 seconds) what should i do to fix this?

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

Once the connection is made, choose the EMPLOYEE table. Click OK. Close the Customizer Dialog.Luxury Phuket Resorts

Steve Sdas replied on Thu, 2012/11/29 - 3:26am

This website has very good content. Please let me know if you're looking for a article author for your weblog. frac plugs

Steve Sdas replied on Thu, 2012/11/29 - 9:41am

You will find a lot of approaches after visiting your post. Great work.New York criminal lawyer

Steve Sdas replied on Fri, 2012/11/30 - 3:42am

I like all information that you provide in your articles. arbeitstische

Steve Sdas replied on Sat, 2012/12/01 - 4:59am

Nice information, many thanks to the author. The usefulness and significance is overwhelming. Thanks again and good luck! avocat

Steve Sdas replied on Sat, 2012/12/01 - 5:54am

The two set out to create a workout studio and a new way of life.Stoker

Steve Sdas replied on Mon, 2012/12/03 - 11:36am

Hey great stuff nice info your passing on Brander Accounting

Steve Sdas replied on Tue, 2012/12/04 - 3:35am

It is a really good reading. I do appreciate that youve added relevant and intelligent commentary here thoughTop Rated Coffeemakers HQ

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.