java - How to implement database search in JTable if I'm using VOs and DAOs? -
everyone. decided contribute topic after racking brains exhaustively.
most part of filtering code got from:
- search jtable repeatedly using jtextfield text
- http://swingdepot.blogspot.com.br/2010/08/text-search-in-jtable.html
software used:
- mysql 14.14
- jdk 7
- netbeans 7.1.2
suppose have following example table called "table":
+-----------+-------------+------+-----+---------+----------------+ | field | type | null | key | default | | +-----------+-------------+------+-----+---------+----------------+ | id | int(11) | no | pri | null | auto_increment | | name | varchar(50) | yes | | null | | | phone | varchar(20) | yes | | null | | | birthdate | datetime | yes | | null | | | status | int(1) | yes | | null | | +-----------+-------------+------+-----+---------+----------------+
creating view called "vtable", considering list display id, name , birth date:
create view vtable select id, name, birthdate table status not null;
i'm using mvc pattern, there packages "model", "view" , "controller".
creating data access object tabledao:
package model.dao; import java.sql.preparedstatement; import java.sql.resultset; import java.sql.sqlexception; import java.util.arraylist; import java.util.list; import java.util.vector; import java.util.logging.level; import java.util.logging.logger; import model.vo.tabledao; import model.vo.vtablevo; public class tabledao extends connectiondao { public list<vinstituicaovo> list() throws classnotfoundexception { list<vtablevo> listtable = new arraylist<>(); try { openconnection(); con.setautocommit(false); preparedstatement stmt = con.preparecall( "select id, name, birthdate vtable"); resultset record = stmt.executequery(); while(record.next()) { vtablevo vo = new vtablevo(); vo.setid(record.getint(1)); vo.setname(record.getstring(2)); vo.setbirthdate(record.getdate(3)); listtable.add(vo); } closeconnection(); } catch (sqlexception ex) { logger.getlogger(tabledao.class.getname()).log(level.severe, null, ex); } return listtable; }
creating value-object (don't forget generate getters , setters) tablevo:
package model.vo; import java.sql.date; public class tablevo { private integer id; private string name; private string phone; private date birthdate; private int status; public tablevo() {} public tablevo(itablevo vo) { id = vo.getid(); name = vo.getname(); phone = vo.getphone(); birthdate = vo.getbirthdate(); status = vo.getstatus(); } // generate getters , setters }
vtablevo class:
package model.vo; import java.sql.date; public class vtablevo { private integer id; private string name; private date birthdate; // generate getters , setters }
itabledao interface:
package model.dao; import java.util.list; import model.vo.tablevo; public interface itabledao { public list<tablevo> list(); }
itablevo interface:
package model.vo; import java.sql.date; public interface itablevo { public integer getid(); public void setid(integer set_id); public string getname(); public void setname(string set_nome); public string getphone(); public void setphone(string set_phone); public date getbirthdate(); public void setbirthdate(date set_birthdate); public integer getstatus(); public void setstatus(integer set_status); }
with structure, how implement search function in jtable?
inside form data must displayed, create 2 jpanels:
- where we'll put 3 jtextfields ("txtid", "txtname" , "txtbirthdate")
- where we'll put jtable "tableexample"
i'll first jtextfield, is, "txtid".
frmexample form (note: there's internal class called customrenderer @ end - color border of cell found):
package view; import java.awt.color; import java.awt.component; import java.awt.font; import java.awt.rectangle; import java.awt.event.actionevent; import java.awt.event.actionlistener; import java.sql.date; import java.sql.sqlexception; import java.text.parseexception; import java.text.simpledateformat; import java.util.list; import java.util.logging.level; import java.util.logging.logger; import javax.swing.*; import javax.swing.table.*; import model.dao.tabledao; import model.vo.vtablevo; public class frmexample extends javax.swing.jinternalframe { public frmexample() throws sqlexception, classnotfoundexception { initcomponents(); gettablemodel(); gettable(); txtid.addactionlistener(new actionlistener() { @override public void actionperformed(actionevent e) { searchid(); } }); tableexample.setautocreaterowsorter(true); } private void gettablemodel() { // configure columns of jtable tablecolumnmodel columnmodel = this.tableexample.getcolumnmodel(); columnmodel.getcolumn(0).setheadervalue("id"); columnmodel.getcolumn(0).setpreferredwidth(60); columnmodel.getcolumn(1).setheadervalue("name"); columnmodel.getcolumn(1).setpreferredwidth(180); columnmodel.getcolumn(2).setheadervalue("birth date"); columnmodel.getcolumn(2).setpreferredwidth(180); } private jtable gettable() throws classnotfoundexception { string[] columntitles = { "id", "name", "birth date" }; list<vtablevo> listexample = new tabledao().list(); object[][] data = new object[listexample.size()][columntitles.length]; for(vtablevo vo : list) { data[list.indexof(vo)][0] = "" + vo.getid(); data[list.indexof(vo)][1] = vo.getname(); data[list.indexof(vo)][2] = "" + vo.getbirthdate(); } // there way code become more dynamic? writing 1 line instead of 3 defaulttablemodel model = new defaulttablemodel(data, columntitles) { @override public class getcolumnclass(int col) { object obj = getvalueat(0, col); if(obj == null) return object.class; else return obj.getclass(); } }; tableexample.setdefaultrenderer(string.class, new customrenderer()); tableexample.setrowselectionallowed(true); tableexample.setcolumnselectionallowed(true); tableexample.setselectionmode(listselectionmodel.single_selection); tableexample.setmodel(model); tablemodel model = tableexample.getmodel(); final tablerowsorter<tablemodel> sorter = new tablerowsorter<>(model); tableexample.setrowsorter(sorter); return tableexample; } private void searchid() { string target = txtid.gettext(); for(int row = 0; row < tableexample.getrowcount(); row++) { string next = (string)tableexample.getvalueat(row, 0); // first row if(next.equals(target)) { displayresultsearch(row, 0); return; } } customrenderer renderer = (customrenderer)tableexample.getdefaultrenderer(string.class); renderer.settargetcell(-1, -1); tableexample.repaint(); } private void displayresultsearch(int row, int column) { customrenderer renderer = (customrenderer)tableexample.getcellrenderer(row, column); renderer.settargetcell(row, column); rectangle rect = tableexample.getcellrect(row, column, false); tableexample.scrollrecttovisible(rect); tableexample.repaint(); } class customrenderer implements tablecellrenderer { jlabel label; int targetrow, targetcolumn; public customrenderer() { label = new jlabel(); label.sethorizontalalignment(jlabel.center); label.setopaque(true); targetrow = -1; targetcolumn = -1; } @override public component gettablecellrenderercomponent(jtable table, object value, boolean isselected, boolean hasfocus, int row, int column) { if(isselected) { label.setbackground(table.getselectionbackground()); label.setforeground(table.getselectionforeground()); } else { label.setbackground(table.getbackground()); label.setforeground(table.getforeground()); } if(row == targetrow && column == targetcolumn) { label.setborder(borderfactory.createlineborder(color.red)); // color in red! label.setfont(table.getfont().derivefont(font.bold)); // , bold! } else { label.setborder(null); label.setfont(table.getfont()); } label.settext((string)value); return label; } public void settargetcell(int row, int column) { targetrow = row; targetcolumn = column; } } }
to search must type in selected field, hit enter. i'm not using jbutton in example.
to implement same other columns, biggest hint give changing following lines:
- string next = (string)tableexample.getvalueat(row, column number here);
- displayresultsearch(row, column number here);
i hope lot of people. if find worth changing, reason @ all, please answer considerations. thanks!
Comments
Post a Comment