apache metamodel queryConstraints - java

DataSet dataSet = datacontext.query()
.from(table)
.select(colNameArr)
.where(frstCol).eq(dynamicval1).and("").eq("").or("").eq("")....etc
.execute();
Can this be achieved?, can I dynamically decide the constraint, starting from and(), or() ? if so how can we do it?

Example of dynamic SELECT and WHERE clauses:
// Prepare a data context based on plain old Java objects
List<TableDataProvider<?>> tableDataProviders = new ArrayList<TableDataProvider<?>>();
SimpleTableDef tableDef1 = new SimpleTableDef("snippetTableName1", new String[] {"id", "name"});
tableDataProviders.add(new ArrayTableDataProvider(tableDef1,
new ArrayList<Object[]>()));
PojoDataContext dataContext = new PojoDataContext("snippetSchemaName", tableDataProviders);
// Add some rows
dataContext.executeUpdate(new UpdateScript() {
public void run(UpdateCallback callback) {
callback.insertInto("snippetTableName1").value("id", "id1").value("name", "name1").execute();
callback.insertInto("snippetTableName1").value("id", "id2").value("name", "name2").execute();
}
});
// Prepare dynamic query
String[] selectArray = new String[2];
selectArray[0] = "id";
selectArray[1] = "name";
Map<String, Object> whereClauses = new HashMap<String, Object>();
whereClauses.put("id", "id1");
whereClauses.put("name", "name1");
SatisfiedSelectBuilder<?> queryBuilder = dataContext.query().from("snippetTableName1").select(selectArray);
SatisfiedWhereBuilder<?> whereBuilder = null;
int i = 0;
for (Map.Entry<String, Object> whereClause: whereClauses.entrySet()) {
if (i == 0) {
whereBuilder = queryBuilder.where(whereClause.getKey()).eq(whereClause.getValue());
} else {
whereBuilder = whereBuilder.and(whereClause.getKey()).eq(whereClause.getValue());
}
i++;
}
DataSet dataSet = whereBuilder.execute();
while (dataSet.next()) {
Row row = dataSet.getRow();
System.out.println("Row: " + row);
}

Related

How to optimize this Java JDBC code which selects many rows and columns

I used all kinds of database CURD by the Hibernate before. Actually, I have never used JDBC before Hibernate. So I don't know anything about JDBC. So the following code is working but I believe it can optimize a lot. This query returns join data from 2 tables and it is huge:-
private final String COL1 = "COL1";
private final String COL2 = "COL2";
private final String COL3 = "COL3";
private final String COL4 = "COL4";
private final String COL5 = "COL5";
private final String COL6 = "COL6";
private final String COL7 = "COL7";
private final String COL8 = "COL8";
private final String COL9 = "COL9";
private final String COL10 = "COL10";
public void getDataByPp(String pp) {
PreparedStatement pst = null;
ResultSet rset = null;
try {
pst = conn.prepareStatement(SELECT_MASTER_AND_FEATURE);
pst.setString(1, pp);
rset = pst.executeQuery();
ArrayList<String> data = new ArrayList<String>();
Map<Integer, Map<String, String>> mapMap = new HashMap<Integer, Map<String, String>>();
int index = 0;
while (rset.next()) {
Map<String, String> dataMap = new HashMap<String, String>();
dataMap.put(COL1, rset.getString("COL1"));
data.add(rset.getString("COL1"));
dataMap.put(COL2, rset.getString("COL2"));
data.add(rset.getString("COL2"));
dataMap.put(COL3, rset.getString("COL3"));
data.add(rset.getString("COL3"));
dataMap.put(COL4, rset.getString("COL4"));
dataMap.put(COL4, rset.getString("COL4"));
dataMap.put(pp, rset.getString("pp"));
data.add(rset.getString("pp"));
dataMap.put(COL5, rset.getString("COL5"));
data.add(rset.getString("COL5"));
dataMap.put(COL6, rset.getString("COL6"));
data.add(rset.getString("COL6"));
dataMap.put(COL7, rset.getString("COL7"));
data.add(rset.getString("COL7"));
dataMap.put(COL8, rset.getString("COL8"));
data.add(rset.getString("COL8"));
dataMap.put(COL9, rset.getString("COL9"));
data.add(rset.getString("STATE"));
dataMap.put(COL10, rset.getString("COL10"));
data.add(rset.getString("COL10"));
mapMap.put(index, dataMap);
index++;
}
for (String val : data) {
System.out.println("data : " + val);
}
for (Integer key : mapMap.keySet()) {
Map<String, String> dataMap = mapMap.get(key);
for (String key2 : dataMap.keySet()) {
System.out.println("key: " + key2 + " val: " + dataMap.get(key2));
}
}
} catch (SQLException e) {
System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
} catch (Exception e) {
System.out.println("Exception when insert into INTERIOR_ROOMS_FEATURES");
}
}
Well, I notice a fairly long while loop which appears to iterate a set number of "COL"(s) and add them in a consistent way (except "STATE" / "COL9") which may require an if - but otherwise, all of those fields could be read from an array. Also, I would prefer the diamond operator <> for initializing the generic collections. Like,
String[] cols = { COL1, COL2, COL3, COL4, "pp", //
COL5, COL6, COL7, COL8, COL9, "STATE", COL10 };
List<String> data = new ArrayList<>();
Map<Integer, Map<String, String>> mapMap = new HashMap<>();
int index = 0;
while (rset.next()) {
Map<String, String> dataMap = new HashMap<>();
for (String c : cols) {
String s = rset.getString(c);
dataMap.put(c, s);
data.add(s);
}
mapMap.put(index, dataMap);
index++;
}

Arraylist contain, & retain all not giving the same result as Sql inner join

Sql output : 312
Sql Script inner join:
SELECT count(*) FROM COST_TYPE_SELECTION CST
LEFT JOIN GBL_HYPACCT_RSLV_TBL_NEW_CA GBL
ON GBL.TREE_NODE = CST.GL_TREE_NODE
AND GBL.TREE_LEVEL = CST.GL_TREE_LEVEL
LEFT JOIN DIM_HYP_PCCODE_FLATTEN DIM
ON CST.PC_TREE_LEVEL = DIM.TREE_LEVEL
AND CST.PC_TREE_NODE = DIM.TREE_LEVEL_NODE
AND DIM.LEGAL_ENTITY='007'
AND DIM.PC_CODE='0200'
and CST.COST_TYPE='Direct_Expenses'
INNER JOIN EPM_CONSOLIDATED_LEDGER_M EPM
ON EPM.LEGAL_ENTITY = DIM.LEGAL_ENTITY
AND EPM.gl_profit_centre_cd = DIM.PC_CODE
AND EPM.GL_ACCOUNT_NUMBER = GBL.TREE_LEAF
WHERE EPM.sourcedataloccd='SG'
Jdbc Script 1 : storing the GLaccount in arraylist Gllishive
SELECT GBL.TREE_LEAF FROM COST_TYPE_SELECTION CST
LEFT JOIN GBL_HYPACCT_RSLV_TBL_NEW_CA GBL
ON GBL.TREE_NODE = CST.GL_TREE_NODE
AND GBL.TREE_LEVEL = CST.GL_TREE_LEVEL
LEFT JOIN DIM_HYP_PCCODE_FLATTEN DIM
ON CST.PC_TREE_LEVEL = DIM.TREE_LEVEL
AND CST.PC_TREE_NODE = DIM.TREE_LEVEL_NODE
AND DIM.LEGAL_ENTITY='007'
AND DIM.PC_CODE='0200'
Jdbc Script 2 : storing the GLaccount in arraylist GllistMaria
select gl_account from EPM_CONSOLIDATED_LEDGER_M EPM
ON EPM.LEGAL_ENTITY ='007' AND EPM.gl_profit_centre_cd = '7482'
WHERE EPM.sourcedataloccd='SG'
Then comparing the using below code
System.out.println("size of hive: " + Gllishive.size());
System.out.println("size of maria join: " + GllistMaria.size());
List<String> joins = new ArrayList<String>(GllistMaria);
joins.retainAll(Gllishive);
System.out.println("after retailall: " + joins.size());
ArrayList<String> MatchingGL = new ArrayList<String>();
for(int i=0;i<GllistMaria.size();i++){
if(Gllishive.contains(GllistMaria.get(i))){
MatchingGL.add(GllistMaria.get(i));
}
}
System.out.println("after contains using for loop :"+MatchingGL);
Output I'm getting : 873 in both retain all and contains method was not matching with sql output : 312
Complete Code below
public void Script1(String ss) {
try{
String consolm = "SELECT * FROM COST_TYPE_SELECTION CST\n" +
"LEFT JOIN GBL_HYPACCT_RSLV_TBL_NEW_CA GBL ON GBL.TREE_NODE = CST.GL_TREE_NODE AND GBL.TREE_LEVEL = CST.GL_TREE_LEVEL\n" +
"LEFT JOIN DIM_HYP_PCCODE_FLATTEN DIM ON CST.PC_TREE_LEVEL = DIM.TREE_LEVEL AND CST.PC_TREE_NODE = DIM.TREE_LEVEL_NODE\n" +
"AND DIM.LEGAL_ENTITY='007'\n" +
"AND DIM.PC_CODE=?" +
"and CST.COST_TYPE='Direct_Expenses'\n";
PreparedStatement sta2 = con.prepareStatement(consolm);
sta2.setString(1, ss);
ResultSet result3 = sta2.executeQuery();
HashMap<String, List<String>> map = new HashMap<>();
HashMap<String, List<String>> map5 = new HashMap<>();
HashMap<String, List<String>> map6 = new HashMap<>();
List<String> glAcs = new ArrayList<>();
List<String> glAcs2 = new ArrayList<>();
List<String> glAcs3 = new ArrayList<>();
List<String> glAcs4 = new ArrayList<>();
while(result3.next()){
String de = result3.getString("gbl.descr");
if(map.get(de)!=null){
glAcs = map.get(de);
glAcs.add(result3.getString("gbl.tree_leaf"));
map.put(de,glAcs);
data.add(result3.getString("gbl.tree_leaf"));
}else{
List<String> glAcs1 = new ArrayList<>();
glAcs1.add(result3.getString("gbl.tree_leaf"));
map.put(de,glAcs1);
data.add(result3.getString("gbl.tree_leaf"));
}
String pe = result3.getString("gbl.descr");
if(map5.get(pe)!=null){
glAcs3 = map5.get(pe);
glAcs3.add(result3.getString("cst.legal_entity"));
map5.put(pe,glAcs3);
data22.add(result3.getString("cst.legal_entity"));
}
else{ List<String> glAcs13 = new ArrayList<>();
glAcs13.add(result3.getString("cst.legal_entity"));
map5.put(pe,glAcs13);
data22.add(result3.getString("cst.legal_entity"));
}
String he = result3.getString("gbl.descr");
if(map6.get(he)!=null){
glAcs4 = map6.get(he);
glAcs4.add(result3.getString("dim.pc_code"));
map6.put(he,glAcs4);
data33.add(result3.getString("dim.pc_code"));
}
else{
List<String> glAcs14 = new ArrayList<>();
glAcs14.add(result3.getString("dim.pc_code"));
map6.put(he,glAcs14);
data33.add(result3.getString("dim.pc_code"));
}
}
Set<String> hs = map.keySet();
Iterator itr = hs.iterator();
while(itr.hasNext()){
String key = itr.next().toString();
Glac.addAll(map.get(key));
}
System.out.println(" Final count of hive was :"+Glac.size());
System.out.println(" Final count of hive was :"+data.size());
Set<String> hs22 = map5.keySet();
Iterator itr22 = hs22.iterator();
while(itr22.hasNext()){
String key = itr22.next().toString();
legen.addAll(map5.get(key));
}
System.out.println(" Final count of hive was :"+legen.size());
System.out.println(" Final count of hive was :"+data22.size());
Set<String> hs33 = map6.keySet();
Iterator itr33 = hs33.iterator();
while(itr33.hasNext()){
String key = itr33.next().toString();
pc.addAll(map6.get(key));
}
System.out.println(" Final count of hive was :"+pc.size());
System.out.println(" Final count of hive was :"+data33.size());
con.close();
}catch(ClassNotFoundException |IOException e){
}catch (SQLException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
System.out.println(e.toString());
}
}
public void script2(String ss) {
try{
String consolm = "select * from EPM_CONSOLIDATED_LEDGER_M EPM\n" +
"WHERE EPM.sourcedataloccd='SG'AND EPM.primarysourcesyscd NOT IN('EPMCA','EPMTX','EPMOS')\n" +
"AND EPM.businessdt='20181130' AND EPM.rundt='20181204' AND EPM.GL_BU_CD IN ('DBU','ACU')\n" +
"AND EPM.LEGAL_ENTITY = '007'\n" +
"AND EPM.gl_profit_centre_cd = ?";
PreparedStatement sta2 = con.prepareStatement(consolm);
sta2.setString(1, ss);
ResultSet result3 = sta2.executeQuery();
HashMap<String, List<String>> map = new HashMap<>();
HashMap<String, List<String>> map3 = new HashMap<>();
HashMap<String, List<String>> map4 = new HashMap<>();
List<String> glAcs2 = new ArrayList<>();
List<String> glAcs3 = new ArrayList<>();
List<String> glAcs4 = new ArrayList<>();
while(result3.next())
{
String de = result3.getString("epm.product_cd_hyperion");
if(map.get(de)!=null){
glAcs2 = map.get(de);
glAcs2.add(result3.getString("epm.gl_account_number"));
map.put(de,glAcs2);
data2.add(result3.getString("epm.gl_account_number"));
}else{
List<String> glAcs12 = new ArrayList<>();
glAcs12.add(result3.getString("epm.gl_account_number"));
map.put(de,glAcs12);
data2.add(result3.getString("epm.gl_account_number"));
}
String pe = result3.getString("epm.product_cd_hyperion");
if(map3.get(pe)!=null){
glAcs3 = map3.get(pe);
glAcs3.add(result3.getString("epm.legal_entity"));
map3.put(pe,glAcs3);
data3.add(result3.getString("epm.legal_entity"));
}
else{ List<String> glAcs13 = new ArrayList<>();
glAcs13.add(result3.getString("epm.legal_entity"));
map3.put(pe,glAcs13);
data3.add(result3.getString("epm.legal_entity"));
}
String he = result3.getString("epm.product_cd_hyperion");
if(map4.get(he)!=null){
glAcs4 = map4.get(he);
glAcs4.add(result3.getString("epm.gl_profit_centre_cd"));
map4.put(he,glAcs4);
data4.add(result3.getString("epm.gl_profit_centre_cd"));
}
else{
List<String> glAcs14 = new ArrayList<>();
glAcs14.add(result3.getString("epm.gl_profit_centre_cd"));
map4.put(he,glAcs14);
data4.add(result3.getString("epm.gl_profit_centre_cd"));
}
}
Set<String> hs = map.keySet();
Iterator itr = hs.iterator();
while(itr.hasNext()){
String key = itr.next().toString();
Glac2.addAll(map.get(key));
}
System.out.println(" Final count of hive2 was :"+Glac2.size());
System.out.println(" Final count of hive2 was :"+data2.size());
Set<String> hs2 = map3.keySet();
Iterator itr2 = hs2.iterator();
while(itr2.hasNext()){
String key = itr2.next().toString();
legen2.addAll(map3.get(key));
}
System.out.println(" Final count of hive3 was :"+legen2.size());
System.out.println(" Final count of hive3 was :"+data3.size());
Set<String> hs3 = map4.keySet();
Iterator itr3 = hs3.iterator();
while(itr3.hasNext()){
String key = itr3.next().toString();
pc2.addAll(map4.get(key));
}
System.out.println(" Final count of hive4 was :"+pc2.size());
System.out.println(" Final count of hive4 was :"+data4.size());
con.close();
}catch(ClassNotFoundException |IOException e){
}catch (SQLException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
System.out.println(e.toString());
}
}
#Test
public void Innerjoin() throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException {
Script1("0200");
script2("0200");
ArrayList<String> MatchingGL = new ArrayList<String>();
for (int i = 0; i < Glac2.size(); i++) {
if (Glac.contains(Glac2.get(i))) {
MatchingGL.add(Glac2.get(i));
}
}
System.out.println("after contains using for loop :" + MatchingGL.size());
ArrayList<String> MatchingGL2 = new ArrayList<String>();
for (int i = 0; i < Glac2.size(); i++) {
if (legen.contains(legen2.get(i))&&pc.contains(pc2.get(i))
&&Glac.contains(Glac2.get(i))) {
MatchingGL2.add(Glac2.get(i));
}
}
System.out.println("after contains using for loop :" + MatchingGL2.size());
}
Lets assume for the 1st query that COST_TYPE_SELECTION contains 10 valid rows and that the LEFT JOIN with DIM_HYP_PCCODE_FLATTEN returns 5 rows from DIM.
This means the inner join with EPM_CONSOLIDATED_LEDGER_M will be done against 5 rows so if even if all rows are matched in this join the total number of rows for the query will be 5.
With the same data the first jdbc query will return all 10 rows since there is no inner join, how many rows the second jdbc query will return can not be determined but it feels safe to say from your results that it would be much more than 5 rows.
So to solve this in java you need to include all columns used in the inner join and then perform the same match as in the inner join between the lists for all those columns.

Parse String to get grouped parameters

My String looks like this
http://localhost:8080/HospitalServer/files/file?id=34&firstname=alex&lastname=ozouf&age=33&firstname=kevin&lastname=gerfild&age=27
I use this code to parse the parameters
final Map<String, List<String>> query_pairs = new LinkedHashMap<String, List<String>>();
final String[] pairs = query.split("&");
for (String pair : pairs) {
final int idx = pair.indexOf("=");
final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair;
if (!query_pairs.containsKey(key)) {
query_pairs.put(key, new LinkedList<String>());
}
final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null;
query_pairs.get(key).add(value);
}
System.out.println(query_pairs);
The result is
{id=[34], firstname=[alex, kevin], lastname=[ozouf, gerfild], age=[33, 27]}
The result is not too bad but I want to group the parameters by person.
{id=[34], 1=[alex,ozouf,33 ], 2=[kevin, gerfild,27]}
I can create it from the previous result but I have the feeling that the job is done twice. What do you think I shall do ?
Here's how you can do it without using any library:
import java.util.Map;
import java.util.HashMap;
public class MyUrlParser {
private static final String SEPARATOR = ",";
public static void main(String[] args) {
final String URL = "http://localhost:8080/HospitalServer/files/file?id=34&firstname=alex&lastname=ozouf&age=33&firstname=kevin&lastname=gerfild&age=27";
MyUrlParser mup = new MyUrlParser();
try {
Map<String, String> parsed = mup.parse(URL);
System.out.println(parsed);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
public Map<String, String> parse(String url) throws Exception {
Map<String, String> retMap = new HashMap<>();
int queryStringPos = url.indexOf("?");
if (-1 == queryStringPos) {
throw new Exception("Invalid URL");
}
String queryString = url.substring(queryStringPos + 1);
String[] parameters = queryString.split("&");
if (parameters.length > 0) {
retMap.put("id", parameters[0]);
int personCounter = 0;
for (int minSize = 4; minSize <= parameters.length; minSize += 3) {
StringBuilder person = new StringBuilder();
person.append(parameters[minSize-3]);
person.append(SEPARATOR);
person.append(parameters[minSize-2]);
person.append(SEPARATOR);
person.append(parameters[minSize-1]);
personCounter++;
retMap.put("person" + personCounter, person.toString());
}
}
return retMap;
}
}

DefaultTableModel set column class at creation

Currently I got the following problem:
I load the TableModel data from a H2 database like so:
public static DefaultTableModel loadTableModel(ResultSet rs)
throws SQLException {
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = Definitions.COLUMN_NAMES.length;
for (String string : Definitions.COLUMN_NAMES) {
columnNames.add(string);
}
// data of table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
if (rs.getObject(columnIndex).getClass() == Integer.class) {
if ((int) rs.getObject(columnIndex) == 0) {
vector.add(null);
} else {
vector.add(rs.getObject(columnIndex));
}
} else {
vector.add(rs.getObject(columnIndex));
}
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}
By doing so I pass over the data from my database and columnNames to the constructor of the DefaulTableModel. The problem is, that not all my columns contain the same data type (seemingly the default type seems to be String), so I need to set the data type for all columns directly while creating the DefaultTableModel. How can this be don? I did not find a method to change the column class later on.
If I create my own "TableModelClass" that extends DefaultTableModel, how do I need to create a constructor that works something like this:
TableModelClass(data, columnNames, columnType)
columnType should be a vector containing the Class types like
String.class, Boolean.class etc.
ResultSetMetaData md = rs.getMetaData();
probably is info You expected. Call only once while openning, metadata is ok when zero rows is in query result too.
BTW I usually
build kind of "table metadata" like human readable column captions (Polish language).
be aware at null in some rows (You are ok)
I use traditionally Map< String,OBject > but vector is good to.
copy & paste from my real code, this sample is from web (Wicket) but data modelling is the same.
protected Map<String, Object> move_fields() {
Map<String, Object> rec = new HashMap<String, Object>();
// MathContext mc = new MathContext(2);
for (int i = 0; i < columns; i++) {
String key;
try {
key = md.getColumnName(i + 1).toLowerCase();
int type = md.getColumnType(i + 1);
Object o;
switch (type) {
case java.sql.Types.DOUBLE:
case java.sql.Types.DECIMAL:
case java.sql.Types.FLOAT:
case java.sql.Types.NUMERIC:
BigDecimal bd = rs.getBigDecimal(i + 1);
if (bd != null) {
// bd = bd.round(mc);
bd = bd.setScale(2, RoundingMode.HALF_EVEN);
}
o = bd;
break;
default:
o = rs.getObject(i + 1);
break;
}
rec.put(key, o);
} catch (SQLException e) {
e.printStackTrace();
}
}
for (Entry<String, DynamicField> v : virtuals.entrySet()) {
v.getValue().prepare(rs, record, _my_has_next);
Object o = v.getValue().getValue(rs, record, _my_has_next);
rec.put(v.getValue().getNameInTemplate(), o);
}
for (Entry<String, String> f: rest.entrySet()) {
String kolumna = f.getKey();
String prawo = f.getValue();
if(prawa.contains(prawo)){
int c=1;
}
else{
record.put(kolumna, "");
}
}
return rec;
}

Java Swing - Unable access jTable from different function

I've created jTable as per below:
public void refTable(String jobNo) {
Report rp = new Report();
final String noJob = jobNo;
Map<Integer, String> jMap = rp.getReportInfo(jobNo);
Map<Integer, String> sortedMap = new TreeMap<Integer, String>(jMap);
String[] row = new String[sortedMap.size()];
Integer[] no = new Integer[sortedMap.size()];
String[] stat = new String[sortedMap.size()];
Boolean[] dev = new Boolean[sortedMap.size()];
String[] remark = new String[sortedMap.size()];
Boolean[] rem = new Boolean[sortedMap.size()];
String userRemark[] = new String[sortedMap.size()];
tabSize = sortedMap.size();
int i = 0;
for (Integer key : sortedMap.keySet()) {
no[i] = key;
String []val = sortedMap.get(key).split("###");
if (val[0].trim().equals("DEV")) {
stat[i] = "FAIL";
} else {
stat[i] = val[0].trim();
}
String []strRemark = val[1].split("No");
//tempRemark = strRemark[0];
RemarkDropDownList.devTempValue =val[1].split("No");
row[i] = strRemark[0].trim().replaceAll("Yes", "");//
//row[i] = val[1].trim();
if(strRemark.length<2)
dev[i] = false;
else
dev[i] = true;
remark[i] = "";
if(strRemark.length<2)
userRemark[i] = "";
else
if(RemarkDropDownList.userOthersReamrk!=null)
userRemark[i] = RemarkDropDownList.userSelectedItem;
else
userRemark[i] = strRemark[1];
//remark[i] = false;
/*if(userRemark1[i]!=null)
userRemark[i] = userRemark1[i];//RemarkDropDownList.userOthersReamrk;
else
userRemark[i] =""; Use when drop down*/
rem[i] = false;
i++;
}
DefaultTableModel model = new DefaultTableModel();
model.fireTableDataChanged();
jTable1.setModel(model);
model.addColumn("No:", no);
model.addColumn("Status:", stat);
model.addColumn("Details:", row);
model.addColumn("Non-Deviation", dev);
model.addColumn("Remarks", remark);
model.addColumn("Remove", rem);
model.addColumn("UR", testRemark);
TableColumn col1 = jTable1.getColumnModel().getColumn(0);
col1.setPreferredWidth(30);
TableColumn col2 = jTable1.getColumnModel().getColumn(1);
col2.setPreferredWidth(30);
TableColumn col3 = jTable1.getColumnModel().getColumn(2);
TextRenderer renderer = new TextRenderer();
col3.setCellRenderer(renderer);
col3.setPreferredWidth(350);
CellRenderer cellRender = new CellRenderer();
TableColumn col4 = jTable1.getColumnModel().getColumn(3);
col4.setCellEditor(jTable1.getDefaultEditor(Boolean.class));
col4.setCellRenderer(cellRender);
col4.setPreferredWidth(50);
TableButton buttonEditor = new TableButton("Button");
buttonEditor.addTableButtonListener(new TableButtonListener() {
//#Override
public void tableButtonClicked(int row, int col) {
RemarkDropDownList rmk = new RemarkDropDownList(noJob, row);
}
});
TableColumn col5 = jTable1.getColumnModel().getColumn(4);
col5.setCellRenderer(buttonEditor);
col5.setCellEditor(buttonEditor);
TableColumn col6 = jTable1.getColumnModel().getColumn(5);
col6.setCellEditor(jTable1.getDefaultEditor(Boolean.class));
col6.setCellRenderer(jTable1.getDefaultRenderer(Boolean.class));
col6.setPreferredWidth(50);
jTable1.setShowGrid(true);
jTable1.setGridColor(Color.BLACK);
jTable1.setAutoCreateRowSorter(true);
}
I tried to clear jTable from different function in same class like this.
public void clear()
{
jTable1.setModel(new DefaultTableModel());
}
The jTable is not cleared as per expected. When i try to move jTable1.setModel(new DefaultTableModel()); to main function refTable() the jTable cleared. To add on, I not only able to clear the jTable, it looks like I don't have access to jTable at all.Please advice.
This will clear the table for you. You must first create the new default table model, then set it, and finally set the row count to 0.
public void clear(){
DefaultTableModel tm=new DefaultTableModel();
jTable1.setModel(tm);
tm.setRowCount(0);
}
Hope this helped.

Categories