Problem: invisible a JTable

I have a JTable created in a JScrollPane in a frame. Initialy, the table is empty, after I pressed on a create_table button on my GUI, the TableModel will be create and the data will show up on the table.
I want to disappear my table by pressing on another button. I simply use "table.setVisible(false)" in my actionPerformed method, and it doesnt work. However, When I scroll down the Panel, part of the table, that initially hidden down the screen, is scrolled up.
What i mean is: Lets say the scrollPane can see the first 10 rows, you need to scroll down to see the rest of the table, after i pressed on the disappear button, the table disapper, but when i scroll down, i can still see the 11th row coming up from the bottom. So in fact only the first 10 rows are disappeared. However if i move the frame a bit , then the 11th row disappear. I scroll down a bit more, the 12th row comes up, and I move again the frame, then it disappear..........
I think its the problem from scroll bar, it sholdnt be there, but i did try to set the scoll bar to invisible, but it just doesnt disappear.
How should I fix this problem?

Hi,
two possibilities for hiding the table:
1. if you want to hide table, header and scrollbars, you can call serVisible(false) on the JScrollPane. But be aware that this will perhaps change your layout.
2. If you only want to hide the table's content but not the header and scrollbars, you can call setVisible(false) on the JScrollPane's JViewport. It's your table's parent and could be done like
table.getParent().setVisible(false);where table is a reference to your JTable.
BTW, you can disable the mouse wheel by calling setWheelScrollingEnabled(false) on the JScrollPane.
Andr�

Similar Messages

  • Problem printing the JTable

    Hi all,
    I have a problem with printing JTable.
    My application has a submit button,JTable and Print Button.
    As I click on the Submit button, the data is retrieved from the Database(MS Access) and displayed on the JTable.
    Now when I click on the Print button, the printer properties dialog box is displayed. But when I click on the print button in the dialog box, nothing is printed on the paper.
    I checked the printers and faxes in the control panel, It showed Java printing under the Document name and Printing under the Status. It is displayed for sometime and then disappeared after some time. But nothing is printed on the paper(not even the blank paper).
    I tried a lot but couldn't understand the problem.
    I have used the following files:
    PrintJTable.java
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.print.*;
    import java.awt.geom.*;
    import java.awt.Dimension;
    import java.applet.*;
    import java.sql.*;
    import java.util.*;
    import java.net.*;
    import java.lang.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    class PrintJTable implements ActionListener,Printable
    Connection connect;
    ResultSet rs;
    JTable table;
    JScrollPane tableAggregate;
    DisplayTable displayTable;
    JButton print,submitButton;
    public PrintJTable()
    JFrame frame = new JFrame("Table");
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {System.exit(0);}});
    connect();
    displayTable= new DisplayTable();
    JButton submitButton= new JButton("SUBMIT");
    submitButton.addActionListener(this);
    JButton printButton= new JButton("PRINT!");
    // for faster printing turn double buffering off
    RepaintManager.currentManager( frame).setDoubleBufferingEnabled(false);
    printButton.addActionListener( new ActionListener(){
    public void actionPerformed(ActionEvent evt) {
    PrinterJob pj=PrinterJob.getPrinterJob();
    pj.setPrintable(PrintJTable.this);
    pj.printDialog();
    try{
    pj.print();
    }catch (Exception PrintException) {}
    tableAggregate = createTable();
    tableAggregate.setBorder(new BevelBorder(BevelBorder.LOWERED));
    frame.getContentPane().setLayout(new BorderLayout());
    frame.getContentPane().add(submitButton,BorderLayout.NORTH);
    frame.getContentPane().add(tableAggregate,BorderLayout.CENTER);
    frame.getContentPane().add(printButton,BorderLayout.SOUTH);
    frame.pack();
    frame.setVisible(true);
    } // end of constructor
    public void connect()
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    System.out.println("Opening db connection");
    connect = DriverManager.getConnection("jdbc:odbc:Driver={MicroSoft Access Driver (*.mdb)};DBQ=C:/db1.mdb","","");
    catch (ClassNotFoundException ex) {
    System.err.println("Cannot find the database driver classes.");
    System.err.println(ex);
    catch (SQLException ex) {
    System.err.println("Cannot connect to this database.");
    System.err.println(ex);
    public JScrollPane createTable() {
    displayTable= new DisplayTable();
    JTable table = new JTable(displayTable);
         table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
         table.getTableHeader().setReorderingAllowed(false);
    JScrollPane scrollpane = new JScrollPane(table,
    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
    JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    return scrollpane;
    } // end of createTable()
    public void actionPerformed(ActionEvent ie)
    try
    Statement statement6=connect.createStatement();
    ResultSet rs6=statement6.executeQuery("select * from benf_details");
    displayTable.executeQuery(rs6);
    statement6.close();
    catch(SQLException sqle)
    JOptionPane.showMessageDialog(null,"error2"+sqle);
    }// end of actionPerformed
    public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException {
    Graphics2D g2 = (Graphics2D)g;
    g2.setColor(Color.black);
    int fontHeight=g2.getFontMetrics().getHeight();
    int fontDesent=g2.getFontMetrics().getDescent();
    double pageHeight = pageFormat.getImageableHeight()-fontHeight; //leave room for page number
    double pageWidth = pageFormat.getImageableWidth();
    System.out.println("page width = " + pageWidth );
    double tableWidth = (double) table.getColumnModel().getTotalColumnWidth();
    System.out.println("table width = " + tableWidth );
    double scale = 1;
    if (tableWidth >= pageWidth) {
    scale = pageWidth / tableWidth;
    System.out.println("scale = " + scale );
    double headerHeightOnPage = table.getTableHeader().getHeight() * scale;
    double tableWidthOnPage = tableWidth * scale;
    double oneRowHeight = (table.getRowHeight() + table.getRowMargin()) * scale;
    int numRowsOnAPage = (int)((pageHeight - headerHeightOnPage) / oneRowHeight);
    double pageHeightForTable = oneRowHeight * numRowsOnAPage;
    int totalNumPages = (int)Math.ceil(((double)table.getRowCount())/numRowsOnAPage);
    if(pageIndex >= totalNumPages) {
    return NO_SUCH_PAGE;
    g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    g2.drawString("Page: "+ (pageIndex + 1),(int)pageWidth / 2 - 35,
    (int)( pageHeight + fontHeight - fontDesent ));//bottom center
    g2.translate( 0f, headerHeightOnPage );
    g2.translate( 0f, -pageIndex * pageHeightForTable );
    //If this piece of the table is smaller than the size available,
    //clip to the appropriate bounds.
    if (pageIndex + 1 == totalNumPages) {
    int lastRowPrinted = numRowsOnAPage * pageIndex;
    int numRowsLeft = table.getRowCount() - lastRowPrinted;
    g2.setClip(0, (int)(pageHeightForTable * pageIndex),
    (int) Math.ceil(tableWidthOnPage),
    (int) Math.ceil(oneRowHeight * numRowsLeft));
    //else clip to the entire area available.
    else{
    g2.setClip(0, (int)(pageHeightForTable * pageIndex),
    (int) Math.ceil(tableWidthOnPage),
    (int) Math.ceil(pageHeightForTable));
    g2.scale(scale,scale);
    table.paint(g2);
    g2.scale(1/scale,1/scale);
    g2.translate( 0f, pageIndex * pageHeightForTable);
    g2.translate( 0f, -headerHeightOnPage);
    g2.setClip(0, 0,(int) Math.ceil(tableWidthOnPage), (int)Math.ceil(headerHeightOnPage));
    g2.scale(scale,scale);
    table.getTableHeader().paint(g2);//paint header at top
    return Printable.PAGE_EXISTS;
    } // end of print()
    public static void main(String[] args) {
    new PrintJTable();
    }// end of PrintJTable
    DisplayTable.java
    import java.util.Vector;
    import java.sql.*;
    import javax.swing.*;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.event.TableModelEvent;
    public class DisplayTable extends AbstractTableModel {
    Connection connection;
    Statement statement;
    ResultSet resultSet;
    String[] columnNames = {};
    Vector          rows = new Vector();
    ResultSetMetaData metaData;
    String db_uname,db_passwd;
    public DisplayTable() {
    public void executeQuery(ResultSet resultSet) {
    try {
    metaData = resultSet.getMetaData();
    int numberOfColumns = metaData.getColumnCount();
    columnNames = new String[numberOfColumns];
    // Get the column names and cache them.
    // Then we can close the connection.
    for(int column = 0; column < numberOfColumns; column++) {
    columnNames[column] = metaData.getColumnLabel(column+1);
    // Get all rows.
    rows = new Vector();
    while (resultSet.next()) {
    Vector newRow = new Vector();
    for (int i = 1; i <= getColumnCount(); i++) {
         newRow.addElement(resultSet.getObject(i));
    rows.addElement(newRow);
    // close(); Need to copy the metaData, bug in jdbc:odbc driver.
    fireTableChanged(null); // Tell the listeners a new table has arrived.
    catch (SQLException ex) {
    System.err.println(ex);
    public void close() throws SQLException {
    System.out.println("Closing db connection");
    resultSet.close();
    statement.close();
    connection.close();
    protected void finalize() throws Throwable {
    close();
    super.finalize();
    // Implementation of the TableModel Interface
    // MetaData
    public String getColumnName(int column) {
    if (columnNames[column] != null) {
    return columnNames[column];
    } else {
    return "";
    public Class getColumnClass(int column) {
    int type;
    try {
    type = metaData.getColumnType(column+1);
    catch (SQLException e) {
    return super.getColumnClass(column);
    switch(type) {
    case Types.CHAR:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
    return String.class;
    case Types.BIT:
    return Boolean.class;
    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.INTEGER:
    return Integer.class;
    case Types.BIGINT:
    return Long.class;
    case Types.FLOAT:
    case Types.DOUBLE:
    return Double.class;
    case Types.DATE:
    return java.sql.Date.class;
    default:
    return Object.class;
    // to make the cells editable
    public boolean isCellEditable(int row, int column) {
    try {
    return metaData.isWritable(column+1);
    catch (SQLException e) {
    return false;
    public int getColumnCount() {
    return columnNames.length;
    // Data methods
    public int getRowCount() {
    return rows.size();
    public Object getValueAt(int aRow, int aColumn) {
    Vector row = (Vector)rows.elementAt(aRow);
    return row.elementAt(aColumn);
    public String dbRepresentation(int column, Object value) {
    int type;
    if (value == null) {
    return "null";
    try {
    type = metaData.getColumnType(column+1);
    catch (SQLException e) {
    return value.toString();
    switch(type) {
    case Types.INTEGER:
    case Types.DOUBLE:
    case Types.FLOAT:
    return value.toString();
    case Types.BIT:
    return ((Boolean)value).booleanValue() ? "1" : "0";
    case Types.DATE:
    return value.toString(); // This will need some conversion.
    default:
    return "\""+value.toString()+"\"";
    public void setValueAt(Object value, int row, int column) {
    try {
    String tableName = metaData.getTableName(column+1);
    // Some of the drivers seem buggy, tableName should not be null.
    if (tableName == null) {
    System.out.println("Table name returned null.");
    String columnName = getColumnName(column);
    String query =
    "update "+tableName+
    " set "+columnName+" = "+dbRepresentation(column, value)+
    " where ";
    // We don't have a model of the schema so we don't know the
    // primary keys or which columns to lock on. To demonstrate
    // that editing is possible, we'll just lock on everything.
    for(int col = 0; col<getColumnCount(); col++) {
    String colName = getColumnName(col);
    if (colName.equals("")) {
    continue;
    if (col != 0) {
    query = query + " and ";
    query = query + colName +" = "+
    dbRepresentation(col, getValueAt(row, col));
    System.out.println(query);
    System.out.println("Not sending update to database");
    // statement.executeQuery(query);
    catch (SQLException e) {
    // e.printStackTrace();
    System.err.println("Update failed");
    Vector dataRow = (Vector)rows.elementAt(row);
    dataRow.setElementAt(value, column);
    }

    Java 1.5 incorporates a very simple way to print from a JTable. I am using a mysql DB but it is the same concept. Review my code and let me know if you have any questions.
    package emsmain;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.*;
    import java.sql.*;
    import java.text.MessageFormat;
    import java.util.*;
    import javax.print.*;
    import javax.print.attribute.HashPrintRequestAttributeSet;
    import javax.print.attribute.PrintRequestAttributeSet;
    import javax.swing.*;
    import javax.swing.JTable;
    import javax.swing.table.*;
    import java.awt.print.*;
    public class TableFromDatabase extends JFrame implements ActionListener{
        JButton jbtprint = new JButton("Print Report");
        JTable Reporttable;
        Connection conn = Connect_Database.getConnection();
         public TableFromDatabase()
    Vector columnNames = new Vector();
    Vector data = new Vector();     
              try{  
                String query = null;
                Statement ps = null;
                ResultSet rs = null;
                  //Class Master List
                  if (Report_Menu.jrbMaster_list.isSelected()){
                      query =("Select * from students") ;
                  //Classes taken by student
                  if (Report_Menu.jrbClass_taken.isSelected()){
                      String taken = Report_Menu.jtfStudent.getText();
                      query = ("select program.course_num, course_name, course_start_date, course_stat_desc from registration, program where student_id = '"+taken+"' and program.course_num = registration.course_num");
                  //Birthday report
                  if (Report_Menu.jrbBirthday.isSelected()){
                      String birthday = (String) Report_Menu.jcb_birthday.getSelectedItem();
                      query = ("SELECT student_id, fname, lname, address, city, state_name, zipcode, dob FROM students where substring(dob, 6,2) = '"+birthday+"'"); 
                  //Course Catologue
                  if (Report_Menu.jrbCourseCatologue.isSelected()){
                      String course = (String) Report_Menu.jcbChooseCourse.getSelectedItem();
                      query = ("select  course_name, course_length, course_cost, course_credits from course where course_name = '"+course+"'");
                  //Certification expiration report
                  if (Report_Menu.jrbExpiration.isSelected()){
                      String month = (String) Report_Menu.jcbMonth.getSelectedItem();
                      String year = (String) Report_Menu.jcbYear.getSelectedItem();
                      query = ("SELECT FNAME, LNAME FROM STUDENTS, REGISTRATION WHERE substring(expiration_date, 6,2) = '"+month+"' and substring(expiration_date, 1,4) = '"+year+"' and registration.student_id = students.student_id") ;
                  //Class Roster
                  if (Report_Menu.jrbRoster.isSelected()){
                      String c_number = Report_Menu.jtfClassNumber.getText();
                      query = ("Select course_name, course_start_date, fname, lname from program, registration, students where program.course_num = '"+c_number+"' and registration.student_id = students.student_id;");
                  //Squad list and counts
                  if (Report_Menu.jrbSquadCount.isSelected()){
                      query = ("SELECT Squad_Name, count(student_id) from students group by Squad_Name");
                  //Student List
                  if (Report_Menu.jrbStudent_list.isSelected()){
                      String Choose_month = (String) Report_Menu.jcbcourse_month.getSelectedItem();
                      String Choose_Course = (String) Report_Menu.jcbcourse_name.getSelectedItem();
                      query = ("select count(student_id) from (registration, program) where program .course_name = '"+Choose_Course+"' and substring(course_start_date, 6,2) = '"+Choose_month+"'and registration.course_num = program.course_num;");
                ps = conn.createStatement();
                //Run Selected Report
                ps.execute(query);
                rs = ps.executeQuery(query);
                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) );
                    //add row data to JTable
                    data.addElement( row );
                rs.close();
                ps.close();
            catch(Exception e)
                JOptionPane.showMessageDialog(null,e.getMessage());
            //  Create Jtable with database data 
            Container c = getContentPane();
            c.setLayout(new BorderLayout());
            Reporttable = new JTable(data, columnNames);
            JScrollPane scrollPane = new JScrollPane( Reporttable );
            c.add( scrollPane );
            JPanel buttonPanel = new JPanel();
            buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
            buttonPanel.add(jbtprint);
            c.add(buttonPanel,BorderLayout.SOUTH);
            jbtprint.addActionListener(this);
        public void actionPerformed(ActionEvent e){
             if(e.getActionCommand().equals("Print Report")){
               PrintForm();
    public void PrintForm(){ 
         try {
             String name = null;
             // Will display correct heading for print job
             if (Report_Menu.jrbMaster_list.isSelected()){
             name = "Master List";
             if (Report_Menu.jrbBirthday.isSelected()){
             name = "Birthday List";
             if (Report_Menu.jrbClass_taken.isSelected()){
             name = "Classes taken by Student";
             if (Report_Menu.jrbCourseCatologue.isSelected()){
             name = "Course Catalogue";
             if (Report_Menu.jrbExpiration.isSelected()){
             name = "Certification Expiration Report";
             if (Report_Menu.jrbRoster.isSelected()){
             name = "Class Roster";
             if (Report_Menu.jrbSquadCount.isSelected()){
             name = "Squad list with Student Counts";
             if (Report_Menu.jrbStudent_list.isSelected()){
             name = "Student count by Course";
             // fetch the printable
             Printable printable = Reporttable.getPrintable(JTable.PrintMode.FIT_WIDTH,
                                                      new MessageFormat(name),
                                                      new MessageFormat("Page - {0}"));
             // fetch a PrinterJob
             PrinterJob job = PrinterJob.getPrinterJob();
             // set the Printable on the PrinterJob
             job.setPrintable(printable);
             // create an attribute set to store attributes from the print dialog
             PrintRequestAttributeSet attr = new HashPrintRequestAttributeSet();
             // display a print dialog and record whether or not the user cancels it
             boolean printAccepted = job.printDialog(attr);
             // if the user didn't cancel the dialog
             if (printAccepted) {
                    try {
                          // do the printing (may need to handle PrinterException)
                        job.print(attr);
                    } catch (PrinterException ex) {
                        ex.printStackTrace();
         } finally {
             // restore the original table state here (for example, restore selection)
    }

  • Problem in Customising JTable's Functionality

    Problem Scenario :
    We are facing a problem related to JTables. In our GUI, we have used JTables and the data model that we are using for the table is a bit complicated. Complicated in the sense that we want different values(multiple) in each cell of a particular column in the table and we want to use JComboBox at that particular cell. For achieving this we have set the values in the JComboBox in its renderer class. But to set the user selected value in the particular cell JComboBox we initialized a new JComboBox in the renderer class. With this the GUI is working fine but it has raised a problem that if we renderer the component another JComboBox appears in the same cell. The problem is obvious as we are initializing a new JComboBox in the renderer class, but to solve our purpose we don�t have another way.
    With the kind of data model we are using is it possible to create a JTable with combo boxes in a particular cell having different option values in each cell?
    Could someone suggest a solution for this problem?
    Regards
    Prajkta Bonde
    [email protected]

    I have done it around 4 years back. Add filled JComboBox as table data.
    Attached sample code should help
    // Imports
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    class SimpleTableExample
              extends      JFrame
         // Instance attributes used in this example
         private     JPanel          topPanel;
         private     JTable          table;
         private     JScrollPane scrollPane;
         // Constructor of main frame
         public SimpleTableExample()
              // Set the frame characteristics
              setTitle( "Simple Table Application" );
              setSize( 300, 200 );
              setBackground( Color.gray );
              // Create a panel to hold all other components
              topPanel = new JPanel();
              topPanel.setLayout( new BorderLayout() );
              getContentPane().add( topPanel );
              // Create columns names
              String columnNames[] = { "Column 1", "Column 2", "Column 3" };
              Object dataValues[][] = new Object[10][3];
              for(int row=0;row<dataValues.length;row++) {
                   for(int col=0;col<dataValues[row].length;col++){
                        JComboBox tempBox = new JComboBox();
                        for(int data=0;data<10;data++){
                             tempBox.addItem("Row "+row+" Column "+col+" Data "+data);
                        dataValues[row][col]=tempBox;
              // Create a new table instance
              table = new JTable( dataValues, columnNames );
            comboBoxColumn(table.getColumnModel().getColumn(0));
            comboBoxColumn(table.getColumnModel().getColumn(1));
            comboBoxColumn(table.getColumnModel().getColumn(2));
              // Add the table to a scrolling pane
              scrollPane = new JScrollPane( table );
              topPanel.add( scrollPane, BorderLayout.CENTER );
        public void comboBoxColumn(TableColumn comboBoxCol) {
            comboBoxCol.setCellEditor(new TableComponentEditor());
            comboBoxCol.setCellRenderer(new TableComponentRenderer());
            //Set up tool tip for the sport column header.
            TableCellRenderer headerRenderer = comboBoxCol.getHeaderRenderer();
            if (headerRenderer instanceof DefaultTableCellRenderer) {
                 ((DefaultTableCellRenderer)headerRenderer).setToolTipText("Click the sport to see a list of service stations");
        } //end of method
        class TableComponentEditor extends DefaultCellEditor {
            * Constructor
            * @param none
            TableComponentEditor() {
                super(new JComboBox());
            * Called when table Cell is clicked
            * @param table
            * @param value - Object associated with the particular column for which it is called
            * @param isSelected -whether the particular cell is selected
            * @param row - The row to which cell belongs
            * @param column - The Column To which Cell Belongs
            public  Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
                cbo = (JComboBox)value;
                return cbo;
            *  getCellEditorValue
            * @return Object
            public Object getCellEditorValue() {
                return cbo;
            /***************CLASS VARIABLES***********************/
            private JComboBox cbo = null;
        class TableComponentRenderer  implements TableCellRenderer {
            public  Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)  {
                return (JComboBox)value;
         // Main entry point for this example
         public static void main( String args[] )
              // Create an instance of the test application
              SimpleTableExample mainFrame     = new SimpleTableExample();
              mainFrame.setVisible( true );
    }

  • Problems with a JTable

    Hello folks,
    i got two problems with a JTable.
    1. how do I change the size of a table header???
    2. I know that it is possible to set different column-sizes. The problem in my table is that I don't know how long some cells are. In this case, I want to to get the biggest cell of one column and set its size as the default size of that specific column.
    Is that possilbe?
    Hopefully you can help me out,
    thank you

    A JTableHeader is just another Component, so you ought to be able to set its size like you would
    any other component; however, since its function is to act as a header for a table, it might constrain
    itself to fit the table.
    In order to size the column to fit the largest cell, for each row, go through each column and get the
    renderer component for that column (which configures the component for rendering) and get the width
    of that component. If that's bigger than the column's current width, set its width and preferred width.
    You'll also want to check the renderer component width for the header to make sure the header doesn't
    get truncated if the column doesn't have a cell whose value is longer than the header.
    : jay

  • Making border of cell  invisible in JTable

    Hi i want to make border of cell invisible in JTable
    any help appreciated
    thanks in advance

    Create a renderer with no border - http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#editrender .

  • Can anybody help me in fixing the problem ? of JTable ( CODE GIVEN )

    My problem is
    1)when i select the combo box (2nd column) through keyboard the selected item is not visible in the cell
    2) i need to press TAB key twice to go to next cell .
    3) also before editing i need to press a key to start editing (caret visible) HELP ME
    CODE CAN BE RUN TO SEE WHAT I MEANT
    <code>
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Vector;
    import java.text.*;
    public class BaseTable
    public JScrollPane scrollPane;
         public JTable table;
         public int totalRows;
         public int i,numRows,numCols;
         public TableModel model;
         public int rowCount;
         public JComboBox box;
    public BaseTable()
              String[] items=new String[]{"item1","jItem2","kItem3","Item4","Item5","Item6"};
              String[] columns = {"Column1","Column2","Column3","Column4","Column5","Column6","Column7","Column8","Column9"};
              box=new JComboBox(items);
              box.setEditable(true);
    DefaultTableModel baseModel=new DefaultTableModel();
              baseModel.setColumnIdentifiers(columns);
    table = new JTable(baseModel)
                   protected void processKeyEvent(KeyEvent e)
                        if ( e.getID() == KeyEvent.KEY_PRESSED && e.getKeyCode() != e.VK_TAB)
                             int column = table.getSelectedColumn();
                             int row = table.getSelectedRow();
                             Rectangle r = getCellRect(row, column, false);
                             Point p = new Point( r.x, r.y );
                             SwingUtilities.convertPointToScreen(p, table);
                             try
                                  System.out.println("PROCESS KEY EVENT Typing"+e.getKeyCode());
                                  Robot robot = new Robot();
                                  robot.mouseMove(p.x, p.y );
                                  robot.mousePress(InputEvent.BUTTON1_MASK);
                                  robot.mouseRelease(InputEvent.BUTTON1_MASK);
                                  robot.mouseMove(0, 0 );
                             catch (Exception e2) {}
                        else
                             System.out.println("PROCESS KEY EVENT IN ELSE");
                             if(e.getKeyCode() == e.VK_TAB && table.isEditing())
                                  ((DefaultCellEditor)table.getCellEditor()).stopCellEditing();
                             else
                                  super.processKeyEvent(e);
    Vector vectorRow = new Vector();
              vectorRow.addElement("");
              vectorRow.addElement("");
              vectorRow.addElement("");
              vectorRow.addElement("");
              vectorRow.addElement("");
              vectorRow.addElement("");
              vectorRow.addElement("");
              vectorRow.addElement("");
              vectorRow.addElement("");
              TableCellEditor tableCellEditor_comboBox = new MyCustomTableCellEditor(box,this);
              table.getColumnModel().getColumn(1).setCellEditor(tableCellEditor_comboBox);
              ((DefaultTableModel)table.getModel()).addRow(vectorRow);
              rowCount = table.getRowCount();
              ((DefaultTableModel)table.getModel()).fireTableRowsInserted(rowCount,rowCount);
              scrollPane = new JScrollPane(table);
              scrollPane.setForeground(Color.white);
              rowCount = table.getRowCount();
    numCols = table.getColumnCount();
    public class MyCustomTableCellEditor extends DefaultCellEditor
                   JTable table=null;
                   BaseTable baseTable=null;
                   JComboBox box=null;
                   MyCustomTableCellEditor(JComboBox editorComponent,BaseTable baseTable)
                        super(editorComponent);
                        this.table=baseTable.table;
                        this.baseTable=baseTable;
                        setClickCountToStart(0);
                   public Component getTableCellEditorComponent(
                        JTable table,
                        Object value,
                        boolean isSelected,
                        int row,
                        int column)
                             super.getTableCellEditorComponent(table,value,isSelected,row,column);
                             box=(JComboBox)getComponent();
                             box.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
                             return box;
         public static void main(String s1[])
              BaseTable t=new BaseTable();
              JFrame f=new JFrame();
              f.getContentPane().add(t.scrollPane);
              f.setSize(800,200);
              f.setVisible(true);
    </code>

    sahas@sun, you're very impolite! farukkhan was trying to help, and he's right because when you use code formatting the code is really easier to read.
    Perhaps you have lost a chance for getting the answer!

  • Disk Utility sees problem invisible to Disk Warrior?

    Hi all,
    In brief: Disk Utility seems to think I've got a big problem, Disk Warrior seems to be unable to fix it.
    More detail: I ran verify disk from Disk Utility and was told I needed to repair my startup volume. So I ran Disk Utility's repair disk function from the install CD and it was unable to repair the disk. It was also unable to repair permissions.
    So I reached for trusty Disk Warrior and ran that. It rebuilt the directory, reporting various changes, eventually ending with zero errors. That should have fixed it, right?
    But then I re-ran Disk Utilty and was told, again, that the disk needed to be repaired.
    Here's what happened when I ran DU's repair function from the install CD:
    - I selected only the volume containing Mac OS X for repair and Disk Utility reported there's an "invalid leaf record count (it should be 3 instead of 525) and also that '1 HFS volume repaired' but '1 HFS volume could not be repaired'. (I'd selected only my startup volume).
    - The verify disk function reports the same
    - The repair disk permissions function cannot complete its task. Its error message reads: "Disk Utility internal error: disk utility has lost its connection with the disk management tool and cannot continue. Please quit and relaunch disk utility."
    So, I ran Disk Warrior AGAIN (2nd time) and sure enough, it reports that it successfully rebuilt the directory but that the rebuilt version has no changes from the original version (meaning it's ok, right?).
    Needless to say, if my startup disk DOES need repair, I want to do something about it. But does it need repair? And if Disk Warrior can't fix it, what can? Could it be that Disk Utility is seeing a problem that's invisible to Disk Warrior?
    By the way, I ran DW's manual diagnostic and it said the drive itself was operating normally.
    Very grateful if any of you can give me some insight into this.
    Jason
    Dual G5 2.5Ghz 2GB RAM, Powerbook G4 1.33Ghz, iPod 60GB   Mac OS X (10.4.8)   500GB internal HDD

    Hi Allan,
    Sure thing. Here's the business.
    Disk Warrior (v3.0.3)
    DW reports that it's successfully rebuilt a new directory each time I run it. I've run it three times now. The first time, there were differences between the original directory and the rebuilt version and it displayed a message coloured red describing this. On the subsequent two occasions, it has displayed a message coloured green and said there are "no changes to the number or contents of the files and folders" in the rebuilt directory.
    DW's manual diagnostic reports that the drive itself is "operating normally."
    DU
    Running DU internally (from the volume that also contains 10.4.9), it can only 'verify', of course. The volume's name is 'G5 hard drive'. The full message is:
    Verifying volume “G5 hard drive”
    Checking HFS Plus volume.
    Checking Extents Overflow file.
    Checking Catalog file.
    Checking multi-linked files.
    Checking Catalog hierarchy.
    Checking Extended Attributes file.
    Incorrect number of Extended Attributes
    Checking volume bitmap.
    Checking volume information.
    d.",1)
    G5 hard drive
    Error: The underlying task reported failure on exit
    1 HFS volume checked
    Volume needs repair
    Running DU (repair disk) from the install CD (for Powermac G5, OS X 10.3.5) produces the following report:
    Repairing disk for "G5 hard drive"
    Checking HFS plus volume
    Checking extents overflow file
    Checking catalog file
    Checking multi-linked files
    Checking catalog hierachy
    Checking extent attributes file
    Invalid leaf record count
    (It should be 3 instead of 422)
    Repairing volume
    The volume G5 hard drive was repaired successfully
    Repair attempted on 2 volumes
    1 HFS volume repaired
    1 HFS volume could not be repaired
    So let's say that DW is doing it all right, and the copy of DU on the install CD (10.3.5) is producing an inaccurate result because it doesn't match up with Tiger, I can understand that. But why would the same problem come up with DU run internally from (in the course of the last 24 hours) both 10.4.8 and 10.4.9 (because the problem survived my upgrade)?
    On the other hand, Allan, possibly DW isn't the right tool for the job. In that case, do you know what is?
    Thanks,
    Jason
    Dual G5 2.5Ghz 2GB RAM, Powerbook G4 1.33Ghz, iPod 60GB   Mac OS X (10.4.9)   500GB internal HDD

  • Problem in Printing jtable swing component using dot martix Epson printer

    Hello,
         I am devoloping desktop aplication using swing.In which i want to prit jtable on paper using dot matrix printer.
    It works well if i am not chnging the font.But if i changed the font (to my local language or any any other language)
    the printing text in table gets Blur (Characters in the text get ovewrites to each other and it become hard to recognize).
    Please help me in this problem.I am trying this from more than two days but not yet found the solution.
    Thank you,
    Dattatray

    Joerg22 wrote:
    Windows allows to change the keyboard to Hindi, but not to Marathi.
    But I wonder why you are changing the focus. The problem arose when you were setting a particular font. So the first question is: Can you do without that font? Meaning: are the Devanagari characters an option?No Devanagari characters are not option.I have to use Marathi language in my application for displaying to the user and taking value from user.See perblem come into picture when i am using setFont method.i did one expriment using characters 0900-097F.For one jtext field i have set text as "\u0937\u0937\0937".In gui i saw the corresponding marathi characters for it (here i did not used any set font method).Also after printuing that on paper i saw marathi text.As i mentioned in previous post i was not able to use "\u0937\u0937\0937" this in table.It might be some mistake in string formation.But i am sure it will work.Only need to check how to form string.
    In this case Only problem is that how to take input from user.As user will not gonna input "\u0900".He will laways enter abcd....I have to interprete them into unicode.Please correct me if i am thinking wrong.
    I will try by changing the language of keyboard to hindi and get back.
    Edited by: Ashtekar on Aug 9, 2010 2:13 AM
    Edited by: Ashtekar on Aug 9, 2010 2:13 AM

  • Problem in editing JTable fields.....

    Hi there!!
    I have got 2 classes in my package,one contains a public static JTable while the other has got some variables whose values I want the JTable's fields to populate with.Now the problem I have is that I can't populate the JTable's fields after making it's class's object and accessing the JTable using that object...Can anybody help plz?
    Thanks...

    Hi Cantry!!
    I'm embedding my code in this post,,had to simplify the code as my application's code may not have been understandable,,,
    Here's the code
    //THIS IS THE CLASS CONTAINING JTable
    import java.sql.*;
    import java.util.StringTokenizer;
    import javax.swing.JOptionPane;
    import javax.swing.JTextField;
    import javax.swing.*;
    public class Test_GUI extends javax.swing.JFrame {
        /** Creates new form Test_GUI */
        public Test_GUI() {
            initComponents();
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                     
        private void initComponents() {
            jScrollPane1 = new javax.swing.JScrollPane();
            jTable1 = new javax.swing.JTable();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("New Allocations");
            jTable1.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(jTable1);
            org.jdesktop.layout.GroupLayout layout = new
    org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(57, 57, 57)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 344,
    org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(106, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(55, 55, 55)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 143,
    org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(247, Short.MAX_VALUE))
            pack();
        }// </editor-fold>                       
         * @param args the command line arguments
        public static void main(String args[]) {
            Test_GUI tg2=new Test_GUI();
            tg2.SetTableValues();
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Test_GUI().setVisible(true);
            try
    javax.swing.UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    catch(Exception e)
                        e.printStackTrace();
            Test_GUI tg=new Test_GUI();
            tg.setVisible(true);
        // Variables declaration - do not modify                    
        private javax.swing.JScrollPane jScrollPane1;
        public static javax.swing.JTable jTable1;
        // End of variables declaration                  
        private javax.swing.JTextField jTextField6;
        public static void SetTableValues()
            System.out.println("here");
            Data_Class dc=new Data_Class();
            jTable1.setValueAt(dc.Test_data,0,0);
    and code from the other calss,,,
    //CLASS FROM WHERE I'M FETCHING THE DATA
    public class Data_Class {
        static String Test_data="testdata";
        /** Creates a new instance of Data_Class */
        public Data_Class() {
    }thanks in advance...

  • Date Format problem in a JTable, help plzzz !!!

    Hi,
    i have a JTable which contains multiple date columns, and more particulary, Timestamp columns.
    I mean this format : yyyy-mm-dd hh:mm:ss.fffffffff
    I only need hh:mm:ss informations for my JTable.
    The problem is when i retrieve the datas in the JTable (which has a bean Select for model), the date column has this format : yyyy-mm-dd (only the date), and the time is not present !
    What must i do to have only a part of the timestamp data in the column ??
    Thanks in advance
    Steve

    If you want to format data in any way other than the default in a JTable, you need a table cell renderer. Sun's tutorial on how to use JTables explains them.

  • Problems with JList & JTable in Netbeans 5.5

    Hi,
    Netbeans provides good GUI building provider.
    But when i am adding JList inside panel
    and trying to add elements its giving error.
    So how to modify read only code in netBeans 5.5 generated code. ??
    There is problem accessing JList variable to be modify.
    HOW TO ACHIEVE THIS ????
    because When you add JList in your GUI Part.
    Netbeans generates code automatically.
    we can't change it.
    HOW TO DO it... ???

    I have had similar trouble.
    In NetBeans Guieditor, JList and JTable are automatically created in a JScrollPanel. This is good as it saves you lots of formatting.
    PROBLEM: when you click/select the JTable or JList in the GUI Editor the Properties box (right hand side ) only shows properties for the JScrollPane.
    So you will only be able to edit Init code etc for the JScrollPane
    SOLUTION: The "Members View" is a list of members (Panels, Objects, etc) on the left hand side of the screen.
    The JScrollPane is listed there. You simply click on this to expand and select the JTable/JList that it contains.
    When you select the JTable/JList the Properites window (right side of screen) now shows the properties for the component you really want to deal with.
    The code options are very powerful.

  • Problem in populating jtable data from database

    hi,
    i am using JTable to retrieve data from database and show it in table. JTable
    is working fine with static data. but while retrieving from databse its giving a NullPointerException at getColumnClass() method. Below is complete source code. plzz help.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.sql.*;
    import javax.swing.table.*;
    /*jdbc connection class*/
    class connect
    Connection con;
    Statement stat;
    public connect()throws Exception
    Class.forName("org.postgresql.Driver");
    con=DriverManager.getConnection("jdbc:postgresql://localhost/dl","dl","dl");
    stat=con.createStatement();
    public ResultSet rsf(String rsstr)throws Exception
    ResultSet rs=stat.executeQuery(rsstr);
    return rs;
    public void upf(String upstr)throws Exception
    stat.executeUpdate(upstr);
    class MyTableModel extends AbstractTableModel
    private String[] columnNames = {"name","id","dep","cat","rem","chkout"};
    Object[][] data;
    public MyTableModel()
    try{
    connect conn=new connect();
    ResultSet rs3=conn.rsf("select * from usertab");
    ResultSetMetaData rsmd=rs3.getMetaData();
    int col=rsmd.getColumnCount();
    int cou=0;while(rs3.next()){cou++;}
    data=new Object[cou][col];
    System.out.println(cou+" "+col);
    ResultSet rs2=conn.rsf("select * from usertab");
    int i=0;int j=0;
    for(i=0;i<cou;i++)
    rs2.next();
    for(j=0;j<col;j++)
    data[i][j]=rs2.getString(getColumnName(j));
    System.out.println(data[0][2]);
    }catch(Exception e){System.out.println("DFD "+e);}
            public int getColumnCount() {
                return columnNames.length;
            public int getRowCount() {
                return data.length;
            public String getColumnName(int col) {
                return columnNames[col];
            public Object getValueAt(int row, int col) {
                return data[row][col];
           public Class getColumnClass(int c) {
              return getValueAt(0, c).getClass();
            public boolean isCellEditable(int row, int col) {
                if (col < 2) {
                    return false;
                } else {
                    return true;
            public void setValueAt(Object value, int row, int col) {
                data[row][col] = value;
                fireTableCellUpdated(row, col);
    class MyFrame extends JFrame
    public MyFrame()
         setSize(600,500);
         JPanel p1=new JPanel();
         p1.setBackground(new Color(198,232,189));
         JTable table = new JTable(new MyTableModel());
         table.setPreferredScrollableViewportSize(new Dimension(500,200));
         table.setBackground(new Color(198,232,189));
         JScrollPane scrollPane = new JScrollPane(table);
         scrollPane.setBackground(new Color(198,232,189));
         p1.add(scrollPane);
         getContentPane().add(p1);
    /*Main Class*/
    class test2
         public static void main(String args[])
         MyFrame fr =new MyFrame();
         fr.setVisible(true);
    }thanx

    hi nickelb,
    i had returned Object.class in the getColumnClass() method. But then i
    got NullPointerException at getRowCount() method. i could understand that the
    main problem is in data[][] object. In all the methods its returning null values as it is so declared outside the construtor. But if i declare the object inside the constructor, then the methods could not recognize the object. it seems i cant do the either ways. hope u understood the problem.
    thanx

  • Problem with refreshing jtable. help please urgent.

    hi there
    i can refresh the table now, but the problem is that every time it refreshes, it adds the same data to the freshed table. i just need the table to display what was displayed few seconds ago unless there is change in the datasource. here is my code:
    public void run()
    String selectSQL = "select * from buyerordertable";
    int rowCounter = 1;
    boolean okay = true;
    ResultSet rs;
    Vector rowdata = new Vector();
    Vector columNames = new Vector();
    columNames.add("order Id");
    columNames.add("suplier name");
    columNames.add("item name");
    columNames.add("model");
    columNames.add("quantity");
    columNames.add("price");
    columNames.add("description");
    columNames.add("job Id");
    columNames.add("order confirm Id");
    while (okay)
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection("jdbc:odbc:wgclientdatabase", "admin", "");
    PreparedStatement ps = con.prepareStatement(selectSQL);
    rs = null;
    rs = ps.executeQuery();
    while(rs.next())
    Vector temp =new Vector();
    String orderid = rs.getString("OrderID");
    temp.add(orderid);
    String supplier =rs.getString("supplierName");
    temp.add(supplier);
    String item = rs.getString("ItemName");
    temp.add(item);
    String model = rs.getString("Model");
    temp.add(model);
    String quantity = rs.getString("Quantity");
    temp.add(quantity);
    String price = rs.getString("Price");
    temp.add(price);
    String description = rs.getString("Description");
    temp.add(description);
    String jobid = rs.getString("JobID");
    temp.add(jobid);
    String confirmid = rs.getString("OrderConfirmID");
    temp.add(confirmid);
    rowdata.add(temp);
    }catch (SQLException sqle)
    catch(ClassNotFoundException ce)
    try
    /*the table keeps adding old data to the refreshed table. i start with one row of data, after every second, a new row of same data is added to the table. i don't know why.*/
    DefaultTableModel newmodel =(DefaultTableModel)jTable.getModel();
    newmodel.setDataVector(rowdata, columNames);
    jScrollPane.repaint();
    Thread.sleep(1000);
    catch (InterruptedException e)
    okay = false;
    }

    hi there
    thank you for your reply
    doesn't the tablemodel keep one set of data? every time i refresh the table, the table model should only provide same data over and over unless it is reset again? in my program, the result seems like the table model is cumulating data every time it refreshes. and the display is growing with the same data. i already use the
    newmodel.setDataVector(rowdata, columNames);
    to reset the data. ideally the table should only display rowdata. some people say that just using table model will solve the refreshing task. i am not sure if they have my kind of problem.

  • Problem displaying table (JTABLE), can u help me?

    Hi 2 all.
    I'm beginer in java (I have expirience of some yoears developing in pro-C, but not java).
    I try to create some JDialog using Intellig Idea7. There I create JTable component, try to initialize it with values in the array (that was inialized before)
    (ex:
    JTable table1 = new JTable(data_string_array, row_names_array);
    The problem is when I try to make & run application, there is nothing displayed.
    On "debug prints" ( print(table1.getValueAt(0,0)); ) where I try to print values of the table - everything is right. it print right values, but then aren't displayed on the dialog window.
    What could be a problem?
    here is example of the code:
    import javax.swing.*;
    import java.awt.event.*;
    * Created by IntelliJ IDEA.
    * User: db2admin
    * Date: Jul 10, 2008
    * Time: 11:53:43 AM
    * To change this template use File | Settings | File Templates.
    public class frame1 extends JFrame{
    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JTable table1;
    private JScrollPane scrollpane;
    public frame1 ()
    contentPane = new JPanel();
    setContentPane(contentPane);
    getRootPane().setDefaultButton(buttonOK);
    // Create table data:
    Object[][] data_matrix = {
    {"one", "two"},
    {"five", "six"},
    {"nine", "ten"},
    Object[] row_names = {"1row1", "2row2"};
    // create new table instance
    table1 = new JTable(data_matrix, row_names);
    scrollpane = new JScrollPane(table1);
    System.out.println("this print");
    buttonOK.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    onOK();
    buttonCancel.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    onCancel();
    // call onCancel() when cross is clicked
    setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
    addWindowListener(new WindowAdapter()
    public void windowClosing(WindowEvent e)
    onCancel();
    // call onCancel() on ESCAPE
    contentPane.registerKeyboardAction(new ActionListener()
    public void actionPerformed(ActionEvent e)
    onCancel();
    }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    private void onOK()
    // add your code here
    //dispose();
    private void onCancel()
    // add your code here if necessary
    dispose();
    public static void main(String[] args)
    frame1 dialog = new frame1();
    dialog.pack();
    dialog.setVisible(true);
    System.out.println("This is other print");
    //JTableDemo demo = new JTableDemo();
    //System.exit(0);
    P.S. Other question: what principal difference in creating simple forms as JFrame or JDialog?

    Hi!
    Well, I don't know what IntellyJ makes, but
    1) I can't see where the buttons are created, so addActionListener throws NPE.
    2) I can't see where the scrollPane is added to the contentPane
    Andras_

  • Problem  Search Records JTable

    Hello All,
    I'm newbie in java, somebody help me..,i've problem using JTable.I have 6 Column in one JTable and i'm using MS Access database,example :
    i want to search records in JTable , i press keyboard and first cell Focus,then i typed ID records result into JTable column1,column2, and column3,column4 i'm entry agains,entry the student point and the last column summary from column 3 and column 3 value1 + value 2 / 2 , and i want to search Smith Data for the example :
    1.
    ==============================================
    ID Name Address value1 value2 total
    ==============================================
    123 ..... ....... .... ..... ......
    ==============================================
    2.
    ==============================================
    ID Name Address value1 value2 total
    ==============================================
    123 Smith St Louis ... ..... ......
    ==============================================
    3.
    ==============================================
    ID Name Address value1 value2 total
    ==============================================
    123 Smith St Louis 70 70 ......
    ==============================================
    4.
    ==============================================
    ID Name Address value1 value2 total
    ==============================================
    123 Smith St Louis 70 70 70
    ==============================================

    The Java&#8482; Tutorials: [How to Use Tables|http://java.sun.com/docs/books/tutorial/uiswing/components/table.html]
    db

Maybe you are looking for