6 Replies - 6176 Views - Last Post: 08 May 2012 - 07:04 PM Rate Topic: -----

#1 mlariossr  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 08-May 12

Get data to/from DB to array to Jtable using custom TableModel

Posted 08 May 2012 - 05:24 PM

Hi all,

I'm new to java and the gui world, not so from coding; though. I've made a couple of "background" scripts from R in order to do some math and statistics, I've perfected them over the years and now they're practically a program of their own, although now I'm trying to put them a "shiny face" in order to be more user-friendly, and thought Java would be a good headstart since we have multiple OS's.

Anyway, the scripts save and uses data from a DB, which I can get acces, I've never done GUI's before so if I'm comceptually wrong please do say so. I'm thinking of having my R-scripts doing their dirty job in one place, then source the result to a java class handling some math (addition, substraction, and very simple math), then when that class has the data into an array, it should pass it to a Swing GUI JTable which should be aware of changes done by the user and pass them to the DB, the JTable uses a custom TableModel I've done, so as you can see there's plenty of room for error. :P

But I can't manage to get the data from MontlyData to the Jtable, which is why I'm posting this..

So, this is the first class called MonthlyData, for now it only has to go to the DB, get the data and put it in an array.

package RiskAnalysis;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;


public class Mensual {
    
    public static void main (String[] args) {
        
        Object[] SGTdata = null;
        Object[] etiquetas = null;
        ArrayList arSGT=new ArrayList();
        
        try {
            String host = "jdbc:derby://localhost:1527/DatosPF";
            String uName = "user";
            String uPass= "password";
            Connection DatosPFG = DriverManager.getConnection( host, uName, uPass );
            Statement stmtPFG = DatosPFG.createStatement( );
            String sql = "SELECT * FROM SEASONGROWTH";
            ResultSet SGT = stmtPFG.executeQuery(sql);
            ResultSetMetaData mdSGT = SGT.getMetaData();            
            int numeroColumnas = mdSGT.getColumnCount();
            etiquetas = new Object[numeroColumnas];
            for (int i = 0; i < numeroColumnas; i++)
                {
                    etiquetas[i] = mdSGT.getColumnLabel(i + 1);
                }
            while (SGT.next())
                {
                    SGTdata = new Object[numeroColumnas];
                    for (int i=0;i<numeroColumnas;i++);
                    SGTdata[i] = SGT.getObject(i+1);
                    arSGT.add(SGTdata);
                }

            }
        catch ( SQLException err ) {
            System.out.println( err.getMessage( ) );
        }
        
    }


}



Now this is my TableModel in order to use it in the JTable:

package RiskAnalysis;

import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;

public class TablaModelo extends AbstractTableModel {

    private ArrayList datalist = new ArrayList();

    private String[] columns={"Concepto", "Valor", 
  "Volúmen", "Porcentaje", "Mes 1", "Mes 2", "Mes 3", "Mes 4", "Mes 5",
  "Mes 6", "Mes 7", "Mes 8", "Mes 9", "Mes 10", "Mes 11", "Mes 12", "Anual"    
    };
    
    @Override
  public int getRowCount() {
   return datalist.size();
  }
    
    @Override
    public int getColumnCount() {
   return columns.length;
  }
   
    @Override
    public Object getValueAt(int row, int col) {
   Widget widget = (Widget) datalist.get(row);
   switch (col) {
    case 0:
     return widget.getName();
    case 1:
     return String.valueOf(widget.getValue());
    case 2:
     return widget.getLocation();
    case 3:
     return String.valueOf(widget.getQuantity());
    default:
     return null;
   }
  }
    
    @Override
    private String getColumnName(int col) {
  return columns[col];
}
    public void addWidget(Widget w) {
   datalist.add(w);
   fireTableDataChanged();
  }
  
  public void addWidgetList(List l) {
   datalist.addAll(l);
   fireTableDataChanged();
  }
  
  public Widget getWidgetAt(int row) {
   return (Widget)datalist.get(row);
  }
  
  public Widget removeRechnungAt(int row) {
        Widget r = (Widget) datalist.remove(row);
        fireTableDataChanged();
        return r;
  }
  
}



The Widget class is this:

package RiskAnalysis;

public class Widget {
     private String name;
     private double value;
     private String location;
     private int quantity;
     public String getName() { 
         return name; 
     }
     public void setName(String s) {
         name = s;
     } 
     public double getValue() {
         return value;
     } 
     public void setValue(double d) {
         value = value; 
     } 
     public String getLocation() {
         return location; 
     } 
     public void setLocation(String d) {
         location = d;
     } 
     public int getQuantity() {
         return quantity;
     } 
     public void setQuantity(int i) {
         quantity = i;
     }
}


And at last, but not least, the Java class which contains the Swing GUI, most of the code was auto-generated, but I managed to edit it:

package RiskAnalysis;

import javax.swing.JTable;

public class TablasMensual extends javax.swing.JPanel {

    /**
     * Creates new form TablasMensual
     */
    public TablasMensual() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        MesTabSeason = new JTable(new TablaModelo());

        jLabel1.setFont(new java.awt.Font("Lucida Sans", 1, 18)); // NOI18N
        jLabel1.setText("Estacionalidad o Crecimiento Mensual de las Ventas");

        MesTabSeason.setModel(new TablaModelo(arSGT)); //It should get the data but it doesn't
        jScrollPane1.setViewportView(MesTabSeason);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addContainerGap(740, Short.MAX_VALUE))
            .addComponent(jScrollPane1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(386, Short.MAX_VALUE))
        );
    }// </editor-fold>
    // Variables declaration - do not modify
    private javax.swing.JTable MesTabSeason;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration

}


Could any of you help me?

Thanks in advanced.

Is This A Good Question/Topic? 0
  • +

Replies To: Get data to/from DB to array to Jtable using custom TableModel

#2 farrell2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 851
  • View blog
  • Posts: 2,598
  • Joined: 29-July 11

Re: Get data to/from DB to array to Jtable using custom TableModel

Posted 08 May 2012 - 05:46 PM

Tutorial here may help.
Was This Post Helpful? 0
  • +
  • -

#3 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8342
  • View blog
  • Posts: 31,880
  • Joined: 06-March 08

Re: Get data to/from DB to array to Jtable using custom TableModel

Posted 08 May 2012 - 06:12 PM

That one may also interest you. It is closer to your problem :)

http://www.dreaminco...snippet6437.htm

If you want to keep your headers it would be easy to add a setHeader() method to the TableModel

This post has been edited by pbl: 08 May 2012 - 06:12 PM

Was This Post Helpful? 0
  • +
  • -

#4 mlariossr  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 08-May 12

Re: Get data to/from DB to array to Jtable using custom TableModel

Posted 08 May 2012 - 06:18 PM

View Postfarrell2k, on 08 May 2012 - 05:46 PM, said:



Thanks for the quick answer, but I already read that tutorial; which gave me a few ideas, but I can't seem to figure it out on my own, as to how it could be applied to my specific problem, if you could please show me how it applies to my problem, I'd be greatefull.
Was This Post Helpful? 0
  • +
  • -

#5 mlariossr  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 08-May 12

Re: Get data to/from DB to array to Jtable using custom TableModel

Posted 08 May 2012 - 06:34 PM

View Postpbl, on 08 May 2012 - 06:12 PM, said:

That one may also interest you. It is closer to your problem :)

http://www.dreaminco...snippet6437.htm

If you want to keep your headers it would be easy to add a setHeader() method to the TableModel


Hi thank you for the link, one question; though: How do I add a setHeader() method?? This is my second day coding in Java, so I'm quite a noob, but I like reading, so please do post some links that show me how to do it, because the link you put shows how to get them from the ResultSet, but I don't need the result set, since I wanna do some math with the data, that's why my model uses an array.
Was This Post Helpful? 0
  • +
  • -

#6 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8342
  • View blog
  • Posts: 31,880
  • Joined: 06-March 08

Re: Get data to/from DB to array to Jtable using custom TableModel

Posted 08 May 2012 - 06:50 PM

View Postmlariossr, on 08 May 2012 - 09:34 PM, said:

This is my second day coding in Java, so I'm quite a noob,

Second day in Java and you already play with JDBC and JTable ?!?!?!
Congratulations, hard to beleive :)

class MyTableModel extends AbtractTableModel {
   String[] header;

   void setHeader(String[] header) {
        this.header = header;
   }

   Object getValueAt(...


Was This Post Helpful? 0
  • +
  • -

#7 mlariossr  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 08-May 12

Re: Get data to/from DB to array to Jtable using custom TableModel

Posted 08 May 2012 - 07:04 PM

View Postpbl, on 08 May 2012 - 06:50 PM, said:

View Postmlariossr, on 08 May 2012 - 09:34 PM, said:

This is my second day coding in Java, so I'm quite a noob,

Second day in Java and you already play with JDBC and JTable ?!?!?!
Congratulations, hard to beleive :)

class MyTableModel extends AbtractTableModel {
   String[] header;

   void setHeader(String[] header) {
        this.header = header;
   }

   Object getValueAt(...



I'm NOT saying it's been easy... But this forum helped me a lot into getting things working... I'll try your code, with some luck tomorrow I'll have good news... Cheers.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1