How to populate a JTable using List<Object> - java

So I need to populate a JTable using data from
List<Object[]> results = query.getResultList();
I'm using NetBeans. I have tried many different things that haven't seemed to work for me.
This is my code:
public void login()
{
Query queryPK = CryptoCurrencyPUEntityManager.createNativeQuery("SELECT t.email, t.user_id FROM usertbl t");
Query queryFK = CryptoCurrencyPUEntityManager.createNativeQuery("SELECT t.curreny, t.amount FROM CURRENCY t WHERE user_fk=?1 ");
List<Object[]> results = queryPK.getResultList();
for(int i = 0; i < results.size(); i++)
{
if(results.get(i)[0].equals(loginEmail))
{
int fk = (int)(results.get(i)[1]);
System.out.println(fk);
queryFK.setParameter(1, fk);
List<Object[]> currencyTBLresluts = queryFK.getResultList();
Currency cur = new Currency();
String[] currTBLheadings = {"Currency","Amount"};
// This is where I would put the data into the table
// Not sure how I am meant to do that
// jTableCurr.setModel(); maybe?
}
}
}

This is an one of many example that you could use it:
//declaring columns
String col[] ={"Currency", "Amount"};
//TableModel
DefaultTableModel tableModel = new DefaultTableModel (col,0);
//Your awesome table with tableModel *injected*
JTable table = new JTable(tableModel);
public void login() {
Query queryPK = CryptoCurrencyPUEntityManager.createNativeQuery("SELECT t.email, t.user_id FROM usertbl t");
Query queryFK = CryptoCurrencyPUEntityManager.createNativeQuery("SELECT t.curreny, t.amount FROM CURRENCY t WHERE user_fk=?1 ");
List<Object[]> results = queryPK.getResultList();
for(int i = 0; i < results.size(); i++) {
if(results.get(i)[0].equals(loginEmail)) {
int fk = (int)(results.get(i)[1]);
System.out.println(fk);
queryFK.setParameter(1, fk);
List<Object[]> currencyTBLresluts = queryFK.getResultList();
if(currencyTBLresluts != null && !currencyTBLresluts.isEmpty()){
Object[] array = currencyTBLresluts.toArray(new Object[currencyTBLresluts.size()]);
((DefaultTableModel)table.getModel()).addRow(array);
}
}
}
}

I came right after looking though the api
public void whenUserLogsIn(){
Query queryPK = CryptoCurrencyPUEntityManager.createNativeQuery("SELECT t.email, t.user_id FROM usertbl t");
Query queryFK = CryptoCurrencyPUEntityManager.createNativeQuery("SELECT t.curreny, t.amount FROM CURRENCY t WHERE user_fk=?");
List<Object[]> results = queryPK.getResultList();
for(int i = 0; i < results.size(); i++)
{
Object[] userArr = results.get(i);
if(userArr[0].equals(loginEmail))
{
int userID = (int)(userArr[1]);
System.out.println(userID);
queryFK.setParameter(1, userID);
List<Object[]> currencyTBLresluts = queryFK.getResultList();
System.out.println("No of currency "+ currencyTBLresluts.size());
String[] currTBLheadings = {"Currency","Amount"};
DefaultTableModel model = new DefaultTableModel(currTBLheadings, currencyTBLresluts.size());
for (Object[] currencyTBLreslut : currencyTBLresluts)
{
model.addRow(currencyTBLreslut);
System.out.println(currencyTBLreslut[0]);
}
jTableCurr.setModel(model);
}
}
}

Related

Add elements to an entity list in java or create it from native query hibernate

I have a native hibernate query that returns a list of objects to me, with a for loop I would like to populate a class list, but I do not laugh because the list is always populated by the last element. Where's the error?
This the code:
...
List<Object[]> results = query.list();
List<PackDisTask> packageDistTasks = new ArrayList<PackDisTask>();
PackageDistributionTaskId taskId = new PackageDistributionTaskId();
Object[] result = null;
String r = "";
for (int i = 0; i < results.size(); i++) {
PackageDistributionTask pdt = new PackageDistributionTask();
result = results.get(i);
if (result[0] != null) {
r = result[0].toString();
taskId.setFkPackageDistribution(Integer.parseInt(r));
}
if (result[10] != null) {
r = result[10].toString();
taskId.setFkTaskType(Integer.parseInt(r));
}
pdt.setId(taskId);
packageDistTasks.add(pdt);
}

Updating a JPanel of queried results from a database

When a user clicks a button initially, a query is run and each row is put into a JPanel and added to the display for the user to view. Which works fine.
My problem is, I want the user to be able to filter these results according to values that they provide ( through a JTextField ) , and I want the displayed records to update as the value of the JTextField changes. My queries are formed and executed each time the JTextField is changed, but I can't find a way to update the records displayed.
Any help would be appreciated.
The code took a while to edit to the satisfaction of stackoverflow, but here it is. Hopefully you can follow the logic. This is the method that deals with formation and execution of the queries, which works(again).
The problem is displaying the new results.
private void processSearch(){
int count = 0;
double width;
remove(allInfo);
allInfo = new JPanel();
allInfo.setLayout(new GridLayout(0, 1, 5, 10));
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
width = screenSize.getWidth();
try {
DatabaseConnetor connect = new DatabaseConnetor();
Connection conn = connect.connect();
String query = "";
String whereClause = "";
int unEmpty = 0;
String [] searches ={searchNameTxt.getText(), searchMailTxt.getText(), searchContactTxt.getText(), (String) searchGender.getSelectedItem()};
String [][] keys = {{"first_name", "middle_name", "family_name", "surname"}, {"email"}, {"contact", "contact2"}, {"gender"}};
for(int i=0; i < searches.length; i++){
if(!searches[i].trim().isEmpty()){
unEmpty++;
}
for(int i=0; i < searches.length; i++){
int counter = 0;
if(!searches[i].trim().isEmpty()){
whereClause += " AND ";
int len = keys[i].length;
if(len == 1){
whereClause += " ("+keys[i][0]+" LIKE '%"+searches[i]+"%') ";
}else if(len > 1){
whereClause += " ( ";
while(counter < len){
if(counter == len-1)
whereClause += keys[i][counter]+" LIKE '%"+searches[i]+"%'";
else
whereClause += keys[i][counter]+" LIKE '%"+searches[i]+"%' OR ";
counter++;
}
whereClause += " ) ";
}
}
}
query = "SELECT photo, first_name, middle_name, family_name, surname, gender, email, contact, contact2 FROM user WHERE rights = 2" + whereClause;
PreparedStatement preparedStatement = conn.prepareStatement(query);
String gen = "", middle = "", family = "", cont = "", phot = "";
ResultSet result = preparedStatement.executeQuery();
while(result.next()){
JPanel data = new JPanel();
data.setPreferredSize(new Dimension((int)(width*0.75), 50));
data.setLayout(new GridLayout(1, 0, 5, 10));
if(result.getString(1) == "NULL")
phot = "";
data.add(new JLabel(phot)); //Photo
data.add(new JLabel(result.getString(2))); //First Name
if(result.getString(3) == "NULL")
middle = "";
data.add(new JLabel(middle)); //Middle Name
if(result.getString(4) == "NULL")
family = "";
data.add(new JLabel(family)); //Family Name
data.add(new JLabel(result.getString(5))); //Surname
if(result.getString(6).equals("M"))
gen = "Male";
else
gen = "Female";
data.add(new JLabel(gen)); //Gender
data.add(new JLabel(result.getString(7))); //E-Mail
data.add(new JLabel(result.getString(8))); //Contact1
if(result.getString(9) == "NULL")
cont = "";
data.add(new JLabel(cont)); //Contact 2
allInfo.add(data);
}
add(allInfo);
connect.disconnect(conn);
connect = null;
conn = null;
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
a query is run and each row is put into a JPanel and added to the display for the user to view
I would suggest you use a JTable to display the data from a database. A JTable is designed to display data in a row/column format.
Read the section from the Swing tutorial on How to Use Tables for more information and examples.
I want the user to be able to filter these results according to values that they provide ( through a JTextField ) , and I want the displayed records to update as the value of the JTextField changes.
A JTable supports dynamic filtering of the data displayed in the table. The above tutorial has a section on Sorting and Filtering that shows how to filter as text is entered into a text field. Filtering the table is more efficient then redoing the SQL query.
Adding data to the table is straight forward. Instead of creating a panel with each column of data you can add a new row of data to the TableModel:
String sql = "Select * from ???";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery( sql );
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
{
columnNames.addElement( md.getColumnName(i) );
}
// Get row data
while (rs.next())
{
Vector<Object> row = new Vector<Object>(columns);
for (int i = 1; i <= columns; i++)
{
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
// Create table with database data
DefaultTableModel model = new DefaultTableModel(data, columnNames)
{
#Override
public Class getColumnClass(int column)
{
for (int row = 0; row < getRowCount(); row++)
{
Object o = getValueAt(row, column);
if (o != null)
{
return o.getClass();
}
}
return Object.class;
}
};
JTable table = new JTable( model );
JScrollPane scrollPane = new JScrollPane( table );

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;
}

jTable in GUI (java) does not show all data from database! error in TableModel?

This is a last resort. I'm studying development of Information Systems and even my teachers can't solve this... this is a nut for you to crack!!
This is the problem: My jTable in GUI gives me this:
This is what Microsoft Management Studio shows me:
As you can tell the jTable (GUI) has got 2 main problems:
The columnname "Name" does not contain any information. And it should? Why isn't it showing?
Since as you can tell, the table contains several columns, too many to even show. I therefore want to "add a restriction" that changes so that the jTable only shows the first 6 columns.
This is the code for the "creation of the table", in the DataAccessLayer:
private TableModel getResultSetAsDefaultTableModel(ResultSet rs) {
try {
String[] columnHeadings = new String[0];
Object[][] dataArray = new Object[0][0];
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
String columnName = md.getColumnName(i);
columnHeadings = Arrays.copyOf(columnHeadings, columnHeadings.length + 1);
columnHeadings[i - 1] = columnName;
}
int r = 0;
while (rs.next()) {
Object[] row = new Object[columnCount];
for (int i = 1; i <= columnCount; i++) {
row[i - 1] = rs.getObject(i);
}
dataArray = Arrays.copyOf(dataArray, dataArray.length + 1);
dataArray[r] = row;
r++;
}
DefaultTableModel dtm = new DefaultTableModel(dataArray, columnHeadings) {
public boolean isCellEditable(int row, int column) {
return false;
}
};
return dtm;
} catch (SQLException ex) {
Logger.getLogger(Dataaccesslayer.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
If you want me to show you the path of the code (frame, controller) just say so and I'll post it.
I would be so thankful if anyone can solve this...
Regards,
Christian
I think it is because in your for loop it should say i = 0; and not i = 1; since the first information (the name) is at index 0 right ?
In your case it could be enough to just leave the for-loop as it is and change this line to:row[i - 1] = rs.getObject(i-1);
To hide or show columns you could call setMin setMax and setPreferredWidth on your TableColumn.
Change your method like next, I think it helps you:
private TableModel getResultSetAsDefaultTableModel(ResultSet rs) {
try {
List<String> columnHeadings = new ArrayList<String>();
Object[][] dataArray = new Object[0][0];
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
columnHeadings.add(md.getColumnName(i));
}
int r = 0;
while (rs.next()) {
Object[] row = new Object[columnCount];
for (int i = 1; i <= columnCount; i++) {
row[i-1] = rs.getObject(i);
}
dataArray = Arrays.copyOf(dataArray, dataArray.length + 1);
dataArray[r] = row;
r++;
}
DefaultTableModel dtm = new DefaultTableModel(dataArray,columnHeadings.toArray(new Object[columnHeadings.size()])) {
public boolean isCellEditable(int row, int column) {
return false;
}
};
return dtm;
} catch (SQLException ex) {
Logger.getLogger(Dataaccesslayer.class.getName()).log(Level.SEVERE,null, ex);
}
return null;
}
For showing not all columns use dtm.setColumnCount(2);. Here 2 is column count to show.

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