database content on a table in java with a column for checkboxes

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 3886 Views - Last Post: 20 September 2012 - 01:42 PM Rate Topic: -----

#1 uzzi7862  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 28-February 12

database content on a table in java with a column for checkboxes

Posted 12 September 2012 - 01:48 PM

Hello. i have a table in which i need to display the database contents. i got that part right but i need to add a checkbox to the last column on the java table. i don't know what i am doing wrong since i cant seem to get it to display. all it shows is it writes out the component in the table cell instead of showing the checkbox.here is the code


//librarys used
import java.awt.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.table.*;

public class JTableDatabase {
    
public static void main(String[] args) {
Vector columnNames = new Vector();
Vector data = new Vector();
JPanel p=new JPanel();
//connection to database
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:td");
String sql = "Select * from Table1";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery( sql );

ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement( md.getColumnName(i) );
}
while (rs.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++){
    
row.addElement( rs.getObject(i) );
}

data.addElement( row );
}
rs.close();
stmt.close();
}
catch(Exception e){
System.out.println(e);
}
JTable table = new JTable(data, columnNames);
TableColumn col;
for (int i = 0; i < table.getColumnCount(); i++) {
col = table.getColumnModel().getColumn(i);
col.setMaxWidth(250);
}
JScrollPane scrollPane = new JScrollPane( table );
p.add( scrollPane );
JFrame f=new JFrame();
f.add(p);
f.setSize(600,400);
f.setVisible(true);
}
}



Is This A Good Question/Topic? 0
  • +

Replies To: database content on a table in java with a column for checkboxes

#2 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2794
  • View blog
  • Posts: 11,830
  • Joined: 20-September 08

Re: database content on a table in java with a column for checkboxes

Posted 12 September 2012 - 01:56 PM

You need, at the very least, a custom TableModel returning column type Boolean to get a checkbox in a column

This post has been edited by g00se: 12 September 2012 - 01:56 PM

Was This Post Helpful? 0
  • +
  • -

#3 uzzi7862  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 28-February 12

Re: database content on a table in java with a column for checkboxes

Posted 12 September 2012 - 02:01 PM

View Postg00se, on 12 September 2012 - 01:56 PM, said:

You need, at the very least, a custom TableModel returning column type Boolean to get a checkbox in a column

do you perhaps have a framework of the code for me for the custom table model. so i can get an idea since i cant seem to get it right because i am using vectors
Was This Post Helpful? 0
  • +
  • -

#4 CasiOo  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1408
  • View blog
  • Posts: 3,123
  • Joined: 05-April 11

Re: database content on a table in java with a column for checkboxes

Posted 12 September 2012 - 02:03 PM

You will need to set the cellRenderer for the column. When you do this you will be able to show a JComboBox :)

Quote

i need to add a checkbox to the last column on the java table.


Oh god I can never read lines like these again without laughing because of The Daily WTF.....
It makes me think of this quote

Quote

Because on ‘big data’ procession you should to avoid creation of many objects in the Java!

This post has been edited by CasiOo: 12 September 2012 - 02:05 PM

Was This Post Helpful? 0
  • +
  • -

#5 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2794
  • View blog
  • Posts: 11,830
  • Joined: 20-September 08

Re: database content on a table in java with a column for checkboxes

Posted 13 September 2012 - 03:54 AM

Actually you don't even need a custom TableModel. Fit the following in your own class and run it
	public static void main(String[] args) {
		Object[] columnNameArray = { "column0", "column1", "column2" };

		Object[][] dataArray = {
				{ Boolean.FALSE, "string1a", "string2a" },
				{ Boolean.FALSE, "string1b", "string2b" },
				{ Boolean.FALSE, "string1c", "string2c" },
				{ Boolean.FALSE, "string1d", "string2d" },
			};

		final MyJTable myJTable = new MyJTable(dataArray, columnNameArray);

		JPanel jPanel = new JPanel();
		jPanel.add(new JScrollPane(myJTable));

		final JFrame frame = new JFrame();
		frame.getContentPane().add(jPanel);
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frame.setLocation(300, 200);
		frame.pack();
		frame.setVisible(true);
	}


This post has been edited by g00se: 13 September 2012 - 03:55 AM
Reason for edit:: trim

Was This Post Helpful? 0
  • +
  • -

#6 uzzi7862  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 28-February 12

Re: database content on a table in java with a column for checkboxes

Posted 15 September 2012 - 11:29 AM

View Postuzzi7862, on 12 September 2012 - 02:01 PM, said:

View Postg00se, on 12 September 2012 - 01:56 PM, said:

You need, at the very least, a custom TableModel returning column type Boolean to get a checkbox in a column

do you perhaps have a framework of the code for me for the custom table model. so i can get an idea since i cant seem to get it right because i am using vectors


Hello. i have created a default table model like you said i should do. I am now having a problem populatint the table with data from the database.
i managed to get and display the column names but the roes i cant seem to get right could you please tell me what i am doing wrong.


public class Check extends JFrame {
Connection con;
Statement st;
ResultSet rs;
 ResultSetMetaData metaData;
// Vector columnNames = new Vector();
   //    Vector data = new Vector();
    private static final int CHECK_COL = 3;

    public Check()throws SQLException {
        
        connect();
        a();
    }
    public void connect(){
        try{
             String driver="sun.jdbc.odbc.JdbcOdbcDriver";
        Class.forName(driver);
       //database used 
        String db="jdbc:odbc:td";
        con=DriverManager.getConnection(db);
        st=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
      //sql query
        String sql="select * from Table1 ";
        rs=st.executeQuery(sql);

        
        }catch(Exception ex){}
    }
        public void a() throws SQLException{
            setTitle("MARKING OF TARGET HABITATION");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        metaData=rs.getMetaData();
        
        int columns = metaData.getColumnCount();
         String[] columnNames= new String[columns+1];
         int num=0;
        for (int i = 1; i <= columns; i++) {
         columnNames[num]=metaData.getColumnName(i);
         
       num=num+1;
         }
        
        
        
        rs.last();
        
        int numrows=rs.getRow();
        int numcols=rs.getMetaData().getColumnCount();
        rs.first();
        
        Object[][] data=new Object[numcols][numrows];
        for(int c=1;c<numcols;c++){
            for(int r=1;r<numrows;r++){
                int x=1;
                while(rs.next()){
            
                  data[c][r]=rs.getObject(r);
                
                }
            }
        }
        
        
        
        
        
        
        
        
       int numRows, numCols;
        rs.last();     
      numRows=rs.getRow();
       
      numCols = rs.getMetaData().getColumnCount();
      System.out.println(numRows+" "+numCols);
		
                   
			
		
			rs.first();
       Object data[][] = new Object[numRows][numCols];
    
			
                	while(rs.next()){
		
			for (int i=0; i <numRows; i++)
			{
                         
				for (int j=1; j < numCols-1; j++) // populate the test data array
				{
				
                                //  data[i][j] =rs.getString(i); 
                              
                             
				}
				
			}
                        }
        
     
        
   
        
  
        
        
        DefaultTableModel dtm = new DefaultTableModel(data, columnNames) {

            @Override
            public Class getColumnClass(int col) {
                return getValueAt(0, col).getClass();
            }

            @Override
            public boolean isCellEditable(int rowIndex, int colIndex) {
                return (colIndex == CHECK_COL);
            }
        };
        final JTable table = new JTable(dtm);
        JScrollPane scrollPane = new JScrollPane(table);
        JButton button = new JButton("check");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                for (int row = 0; row < table.getRowCount(); row++) {
                    Boolean b = ((Boolean) table.getValueAt(row, CHECK_COL));
                    if (b.booleanValue()) {
                        System.out.print("row " + row + " is " + b + ": ");
                        for (int col = 0; col < table.getColumnCount(); col++) {
                            System.out.print(table.getValueAt(row, col) + " ");
                        }
                        System.out.println();
                    }
                }
            }
        });
        JPanel buttonpanel = new JPanel();
        buttonpanel.add(button);
        add(scrollPane, BorderLayout.CENTER);
        add(buttonpanel, BorderLayout.SOUTH);
        pack();
        setLocationByPlatform(true);
        setVisible(true);
    
}

       

    public static void main(String args[])throws SQLException {
        

         
          
                new Check();
    }
}



Was This Post Helpful? 0
  • +
  • -

#7 uzzi7862  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 28-February 12

Re: database content on a table in java with a column for checkboxes

Posted 18 September 2012 - 01:21 PM

how can i do it such that it is not hard coded i want it to come straight from database
Was This Post Helpful? 0
  • +
  • -

#8 pbl  Icon User is offline

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

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

Re: database content on a table in java with a column for checkboxes

Posted 18 September 2012 - 01:28 PM

Would be easier with a TableModel
When you have your rows on N columns from the database
have the getNbColumns() method to return N+1
have an array of boolean[NB_ROWS]
have the getObjectAt(int row, int col) to return the boolean[row] if col == 0
else return your actual database element at ]row,col-1]
Was This Post Helpful? 0
  • +
  • -

#9 uzzi7862  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 28-February 12

Re: database content on a table in java with a column for checkboxes

Posted 18 September 2012 - 01:42 PM

hello i have this code but cant seem to get it right could you perhaps help me with finding my error

public class Check extends JFrame {
Connection con;
Statement st;
ResultSet rs;
 ResultSetMetaData metaData;
// Vector columnNames = new Vector();
   //    Vector data = new Vector();
    private static final int CHECK_COL = 3;

    public Check()throws SQLException {
        
        connect();
        a();
    }
    public void connect(){
        try{
             String driver="sun.jdbc.odbc.JdbcOdbcDriver";
        Class.forName(driver);
       //database used 
        String db="jdbc:odbc:td";
        con=DriverManager.getConnection(db);
        st=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
      //sql query
        String sql="select * from Table1 ";
        rs=st.executeQuery(sql);
     
        }catch(Exception ex){}
    }
        public void a() throws SQLException{
            setTitle("MARKING OF TARGET HABITATION");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        metaData=rs.getMetaData();
        
        int columns = metaData.getColumnCount();
         String[] columnNames= new String[columns+1];
         int num=0;
        for (int i = 1; i <= columns; i++) {
         columnNames[num]=metaData.getColumnName(i);
         
       num=num+1;
         }
        
        
        
        rs.last();
        
        int numrows=rs.getRow();
        int numcols=rs.getMetaData().getColumnCount();
        rs.first();
        
        Object[][] data=new Object[numcols][numrows];
       
        
          while(rs.next()){
        for(int c=1;c<numcols;c++){
            for(int r=1;r<numrows;r++){
               
              
            
                  data[c][r]=rs.getObject(c);
                
                }
            }
        }
        
        
        
        
        
     
  
        
        
        DefaultTableModel dtm = new DefaultTableModel(data, columnNames) {

            @Override
            public Class getColumnClass(int col) {
                return getValueAt(0, col).getClass();
            }

            @Override
            public boolean isCellEditable(int rowIndex, int colIndex) {
                return (colIndex == CHECK_COL);
            }
        };
        final JTable table = new JTable(dtm);
        JScrollPane scrollPane = new JScrollPane(table);
        JButton button = new JButton("check");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                for (int row = 0; row < table.getRowCount(); row++) {
                    Boolean b = ((Boolean) table.getValueAt(row, CHECK_COL));
                    if (b.booleanValue()) {
                        System.out.print("row " + row + " is " + b + ": ");
                        for (int col = 0; col < table.getColumnCount(); col++) {
                            System.out.print(table.getValueAt(row, col) + " ");
                        }
                        System.out.println();
                    }
                }
            }
        });
        JPanel buttonpanel = new JPanel();
        buttonpanel.add(button);
        add(scrollPane, BorderLayout.CENTER);
        add(buttonpanel, BorderLayout.SOUTH);
        pack();
        setLocationByPlatform(true);
        setVisible(true);
    
}

       

    public static void main(String args[])throws SQLException {
        

         
          
                new Check();
    }
}


Was This Post Helpful? 0
  • +
  • -

#10 pbl  Icon User is offline

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

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

Re: database content on a table in java with a column for checkboxes

Posted 18 September 2012 - 01:57 PM

A lot complicated for nothing

Take that one
http://www.dreaminco...snippet6437.htm

just make sure to add a column to the number of columns and an array of boolean for your first column
Was This Post Helpful? 0
  • +
  • -

#11 uzzi7862  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 28-February 12

Re: database content on a table in java with a column for checkboxes

Posted 18 September 2012 - 03:42 PM

View Postpbl, on 18 September 2012 - 01:57 PM, said:

A lot complicated for nothing

Take that one
http://www.dreaminco...snippet6437.htm

just make sure to add a column to the number of columns and an array of boolean for your first column


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

i know i must be irritating you but i am new to this and was wondering if you could tell me where exactly to put the boolean array (and how to create it)in the model im proving which is implemented from the snap you gave me the link to.and can you tell me if i added the column correctly


public class Check extends JFrame {
Connection con;
Statement st;
ResultSet rs;
 ResultSetMetaData metaData;
// Vector columnNames = new Vector();
   //    Vector data = new Vector();
    private static final int CHECK_COL = 3;

    public Check() {
        
        connect();
       a();
    }
    public void connect(){
        try{
             String driver="sun.jdbc.odbc.JdbcOdbcDriver";
        Class.forName(driver);
       //database used 
        String db="jdbc:odbc:td";
        con=DriverManager.getConnection(db);
        st=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
      //sql query
        String sql="select * from Table1 ";
        rs=st.executeQuery(sql);

        
        }catch(Exception ex){}
    }
       
    public void a(){
    JFrame f = new JFrame();
    f.setSize(800, 600);
    
    TableModelFromRS tmfr= new TableModelFromRS(rs);
    JTable table = new JTable(tmfr);
    f.add(table);
    
    
    f.setVisible(true);
    
    }

      
       
      public class TableModelFromRS extends AbstractTableModel {

	private static final long serialVersionUID = 1L;
	// the Column names based on the DB
	private String[] columnName;
	// ArrayList to hold each row composed of an array of Object
	private ArrayList<Object[]> al;

	TableModelFromRS(ResultSet rs) {
		try {
			// meta data to get info on the database
			ResultSetMetaData metaData = rs.getMetaData();
			
			// number of columns present in the ResultSet
			int nbCol = metaData.getColumnCount();
			columnName = new String[nbCol+1];
                        
                        //creating boolean array
                         Boolean[] array = new Boolean[nbCol];
                         Arrays.fill(array, Boolean.FALSE);
			// Load the Array of column names
			for (int i = 0; i < nbCol; ++i) {
				columnName[i] = metaData.getColumnLabel(i + 1); // +1 SQL columns start at 1
		                
                                
                                
                               
                               

                               


                        }

			// Now get the rows
			al = new ArrayList<Object[]>();
			// while there are still rows in the ResultSet
			while (rs.next()) {
				Object[] row = new Object[nbCol];
				// retreive each column
                              
				for (int i = 0; i < nbCol; i++) {
					row[i] = rs.getObject(i+1);				// +1 SQL columns start at 1
				
                                }
				// insert into arrayList
				al.add(row);
			}

		} catch (Exception e) {
			System.out.println("Error building TableModel: " + e);
			e.printStackTrace();
		}
	}

    // the number of rows is the number of entries in the ArrayList
	public int getRowCount() {
		return al.size();
	}

	// the number of columms is the size of the the Array of column name
	public int getColumnCount() {
		return columnName.length;
	}

	// we retreive the array of Object[] at that index in the ArrayList
	// then the object at the required column
	public Object getValueAt(int rowIndex, int columnIndex) {
		return al.get(rowIndex)[columnIndex];
	}
	
	// the column name is in the String[] array of column name
	public String getColumnName(int columnIndex) {
		return columnName[columnIndex];
	}

      }

    public static void main(String args[])throws SQLException {
        

         
          
                new Check();
    }
}



Was This Post Helpful? 0
  • +
  • -

#12 pbl  Icon User is offline

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

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

Re: database content on a table in java with a column for checkboxes

Posted 18 September 2012 - 04:46 PM


		try {
			// meta data to get info on the database
			ResultSetMetaData metaData = rs.getMetaData();
			
			// number of columns present in the ResultSet
			int nbCol = metaData.getColumnCount() + 1;   // nbCol + 1
			columnName = new String[nbCol];
                        
                        //creating boolean array  not really necessary
                        //Boolean[] array = new Boolean[nbCol];
                        // Arrays.fill(array, Boolean.FALSE);
			// Load the Array of column names
                        columnName[0] = "The colum for the check";
			for (int i = 1; i < nbCol; ++i) {   // the other starting at 1
				columnName[i] = metaData.getColumnLabel(i); //
		                
                        }

			// Now get the rows
			al = new ArrayList<Object[]>();
			// while there are still rows in the ResultSet
			while (rs.next()) {
				Object[] row = new Object[nbCol];
				// retreive each column
                row[0] = new Boolean(false);   // the Boolean one   
                
				for (int i = 1; i < nbCol; i++) {   // the other
					row[i] = rs.getObject(i);
				
                                }
				// insert into arrayList
				al.add(row);
			}


Was This Post Helpful? 0
  • +
  • -

#13 uzzi7862  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 28-February 12

Re: database content on a table in java with a column for checkboxes

Posted 19 September 2012 - 02:32 AM

hey thank you. :online2long: but when i run it for some odd reason it just writes the word false in the block instead of actually displaying it. any reason y that could happen since the code you gave me is fine.
Was This Post Helpful? 0
  • +
  • -

#14 pbl  Icon User is offline

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

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

Re: database content on a table in java with a column for checkboxes

Posted 19 September 2012 - 03:50 AM

You will need a CellRenderer for that column
A Boolean toString() method returns "true" or "false"
Was This Post Helpful? 0
  • +
  • -

#15 uzzi7862  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 28-February 12

Re: database content on a table in java with a column for checkboxes

Posted 20 September 2012 - 01:12 PM

View Postpbl, on 19 September 2012 - 03:50 AM, said:

You will need a CellRenderer for that column
A Boolean toString() method returns "true" or "false"


hello. i was wondering if you could perhaps help me with the cell renderer for the column and the boolean to string method since i cannot seem to get it right in my program
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2