Hello everybody!

I want to create a JTable (showing data from mysql..) on a Panel.
But I dont get it..nearly every method is unavailable.

Here is my code for creating it on a frame:

package gfx;

import java.awt.*;
import java.awt.event.MouseAdapter;

import java.awt.event.MouseEvent;

import java.io.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
 
public class TableDB extends JFrame

{
  public static String sql_preview ;

	public TableDB( String sql_preview){
		
    Vector columnNames = new Vector();
        Vector data = new Vector();
        try
        {
            //  Connect to the Database
 
            String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
            String url = "jdbc:mysql://localhost/database";
            String userid = "root";
            String password = "root";
            Class.forName( driver );
            Connection connection = DriverManager.getConnection( url, userid, password );
 
            //  Read data from a table
 
            Statement stmt = connection.createStatement();
          ResultSet rs = stmt.executeQuery( sql_preview );
            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 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 );
        }
 
        //  Create table with database data
 
        JTable table = new JTable(data, columnNames)
        {
			public Class getColumnClass(int column)
			{
				return getValueAt(0, column).getClass();
			}
        };
 
        JScrollPane scrollPane = new JScrollPane( table );
       getContentPane().add( scrollPane );
 JPanel buttonPanel = new JPanel();
       getContentPane().add( buttonPanel, BorderLayout.SOUTH );
    try {
      jbInit();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 public static void main(String[] args)
    {
        TableDB frame = new TableDB( sql_preview );
     frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
     frame.pack();
     frame.setVisible(true);
   }
private void jbInit() throws Exception {
    this.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
          this_mouseClicked(e);
        }
      });
  }
}

everything is working fine, but on an external frame. i want to integrate it on a panel, but as an external Class.

Any ideas?

ty for helping me.


bye

I tested your program. Two problems I have found.

1. sql_preview is not assigned.

public static void main(String[] args)
    {
      sql_preview="select * from tablename";
        TableDB frame = new TableDB( sql_preview );
     frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
     frame.pack();
     frame.setVisible(true);
   }

2. this_mouseClicked(e); method not found

//  this_mouseClicked(e);

Code after correction is

package gfx;

import java.awt.*;
import java.awt.event.MouseAdapter;

import java.awt.event.MouseEvent;

import java.io.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
 
public class TableDB extends JFrame

{
  public static String sql_preview;

	public TableDB( String sql_preview){
		
    Vector columnNames = new Vector();
        Vector data = new Vector();
        try
        {
            //  Connect to the Database
 
            String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
            String url = "jdbc:odbc:aa";
            String userid = "root";
            String password = "root";
            Class.forName( driver );
            Connection connection = DriverManager.getConnection( url,userid,password);
 
            //  Read data from a table
 
            Statement stmt = connection.createStatement();
          ResultSet rs = stmt.executeQuery( sql_preview );
            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 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 );
        }
 
        //  Create table with database data
 
        JTable table = new JTable(data, columnNames)
        {
			public Class getColumnClass(int column)
			{
				return getValueAt(0, column).getClass();
			}
        };
 
        JScrollPane scrollPane = new JScrollPane( table );
       getContentPane().add( scrollPane );
 JPanel buttonPanel = new JPanel();
       getContentPane().add( buttonPanel, BorderLayout.SOUTH );
    try {
      jbInit();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 public static void main(String[] args)
    {
      sql_preview="select * from tablename";
        TableDB frame = new TableDB( sql_preview );
     frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
     frame.pack();
     frame.setVisible(true);
   }
private void jbInit() throws Exception {
    this.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
          
         //  this_mouseClicked(e);
        }
      });
  }
}

Command line compilation,
>javac TableDB.java -d .
Launch JVM
>java gfx.TableDB

Hi there,

@BestJewSinceJC: i know. but if i'll exchange the "extands JFrame" to "extands JPanel", some methods in the body were not found.

I'm willing to write the whole Class new, if it fits then..

@adatapost: thanks. the string sql_preview is a parameter, which will be transfered by calling the class.
for example:

class1:
sql_preview="select * from tablename";
TabelDB table = new TableDB(sql_preview);
..

class2 is the tableDB

all i want is to integrate the table on a panel.

ty

Just change it to extend JPanel and drop the calls to getContentPane() when you add your components. They are added directly with add(). Your main() code will need to create a JFrame to display the panel of course.

something like that?

package gfx.client;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Rectangle;

import java.awt.event.MouseEvent;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

import java.util.Vector;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class table_panel extends JPanel {
   public static String sql_preview ;

	public table_panel( String sql_preview){
    Vector columnNames = new Vector();
        Vector data = new Vector();
 
        try
        {
            //  Connect to the Database
 
            String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
            String url = "jdbc:mysql://localhost/hotel";
            String userid = "root";
            String password = "root";
 
            Class.forName( driver );
            Connection connection = DriverManager.getConnection( url, userid, password );
 
            //  Read data from a table
 
            Statement stmt = connection.createStatement();
          ResultSet rs = stmt.executeQuery( sql_preview );
            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 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 );
        }
 
        //  Create table with database data
 
        JTable table = new JTable(data, columnNames)
        {
			public Class getColumnClass(int column)
			{
				return getValueAt(0, column).getClass();
			}
        };
 
        JScrollPane scrollPane = new JScrollPane( table );
      
 
        JPanel buttonPanel = new JPanel();
      
    try {
      jbInit();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 
  private void jbInit() throws Exception {
  }

}

and this is my call in on a frame:

tabelle = new table_panel(sql_preview);
    this.add("tab", tabelle);
    tabelle.setVisible(true);

ty

Below would be my implementation of your issue. The GUI was developed using NetBeans IDE.

/*
 * Main.java
 * @author mrogers
 * Created on Jun 4, 2009, 9:55:56 AM
 */
package tabledemo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

public class Main extends javax.swing.JFrame
{

    Connection dbConn = null;

    /** Creates new form Main */
    public Main()
    {
        //I like to make sure we have a DB connection before I display a full GUI.
        getConnection();
        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() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblData = new javax.swing.JTable();
        lblTitle = new javax.swing.JLabel();
        cmdClose = new javax.swing.JButton();
        cmdLoadInfo = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Table Demo");

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        tblData.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(tblData);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 516, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 388, Short.MAX_VALUE)
        );

        lblTitle.setText("This is a Table Demo in a Panel.");

        cmdClose.setText("Close");
        cmdClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdCloseActionPerformed(evt);
            }
        });

        cmdLoadInfo.setText("Load Info");
        cmdLoadInfo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdLoadInfoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lblTitle)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(cmdLoadInfo)
                        .addGap(18, 18, 18)
                        .addComponent(cmdClose)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblTitle)
                .addGap(18, 18, 18)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmdClose)
                    .addComponent(cmdLoadInfo))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void cmdCloseActionPerformed(java.awt.event.ActionEvent evt)
    {
        //Close the program
        System.exit(0);
    }

    private void cmdLoadInfoActionPerformed(java.awt.event.ActionEvent evt)
    {

        try
        {
            Vector ssn = new Vector();
            Vector name = new Vector();
            Vector department = new Vector();

            String query = "SELECT DISTINCT Employee_SSN, Employee_Name, Department_Name FROM Payroll";

            Statement stmt = dbConn.createStatement();
            ResultSet rs = stmt.executeQuery(query);

            while (rs.next())
            {
                ssn.add(rs.getString("EmpSSN"));
                name.add(rs.getString("Employee_Name"));
                department.add(rs.getString("Department_Name"));
            }

            if (ssn.isEmpty() == false)//If there were results in the query create a table model with the vectors.
            {
                DefaultTableModel model = new DefaultTableModel()
                {

                    @Override
                    public Class getColumnClass(int columnIndex)
                    {
                        Object o = getValueAt(0, columnIndex);
                        if (o == null)
                        {
                            return Object.class;
                        }
                        else
                        {
                            return o.getClass();
                        }
                    }
                };

                model.addColumn("SSN", ssn);
                model.addColumn("Name", name);
                model.addColumn("Department", department);
                tblData.setModel(model);

            }
            else //If the query returned no results create a table model that displays a "No Result" message and disables the view salaries register button.
            {
                DefaultTableModel model = new DefaultTableModel()
                {

                    @Override
                    public Class getColumnClass(int columnIndex)
                    {
                        Object o = getValueAt(0, columnIndex);
                        if (o == null)
                        {
                            return Object.class;
                        }
                        else
                        {
                            return o.getClass();
                        }
                    }
                };

                ssn.add("No Results");
                name.add("No Results");
                department.add("No Results");

                model.addColumn("SSN", ssn);
                model.addColumn("Name", name);
                model.addColumn("Department", department);
                tblData.setModel(model);
            }

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }


    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[])
    {
        java.awt.EventQueue.invokeLater(new Runnable()
        {

            public void run()
            {
                new Main().setVisible(true);
            }
        });
    }

    private Connection getConnection()
    {
        String dbDriver = "sun.jdbc.odbc.JdbcOdbcDriver";
        String dbLocation = "jdbc:mysql://localhost/database";
        String dbUser = "root";
        String dbPass = "root";

        boolean connectSucessful = true;
        //Try to connect to the database
        try
        {
            System.out.println("About to connect to the database.");
            //Create database connection objects.
            Class.forName(dbDriver); //set the database driver
            dbConn = DriverManager.getConnection(dbLocation, dbUser, dbPass);
            System.out.println("Successfully connected to the database.");
        }
        catch (ClassNotFoundException cnfEx)
        {
            connectSucessful = false;
            System.out.println("ERROR: The driver specified could not be found.");
            cnfEx.printStackTrace();
        }
        catch (SQLException sqlEx)
        {
            connectSucessful = false;
            System.out.println("ERROR: Could not connect to the database.");
            sqlEx.printStackTrace();
        }

        //Test if we were able to connect to the database.
        if (connectSucessful == true)
        {
            return dbConn;
        }
        else
        {
            JOptionPane.showMessageDialog(null, "An error occured.\nCould not connect to the database.", "Connection Error", JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }
        return dbConn;
    }

    // Variables declaration - do not modify
    private javax.swing.JButton cmdClose;
    private javax.swing.JButton cmdLoadInfo;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblTitle;
    private javax.swing.JTable tblData;
    // End of variables declaration
}
This article has been dead for over six months. Start a new discussion instead.