Filling a JTable

I have an application that brings lot of data from a database, and I show this data in a JTable. But I have to wait until I have all the data returned by the database. How can I show data while downloading it from the database?

If you derive from AbstractTableModel, use it's fireTableCellUpdated() or fireTableUpdated() methods, otherwise you can directly send TableModelEvents to the table using table.tableChanged(TableModelEvent)
This will update the table whenever swing feels like it is a good time to do so, should you find that this is only after all the data has been added to the table, you can use the table.paintImmediately() method every once in a while (not too often though, as rendering a table is time consuming)

Similar Messages

  • Hi, i'm having trouble in filling a jtable with data

    hi, i'm having trouble in filling a jtable with data, but the real problem is that i have stablished a JDBC connection throught the windowsxp ODBC to my database written on microsoft access platform, so i created my table
    public CenterPanel(){
    panel = new JPanel();
    dataTable = new JTable(10,10);
    dataTable.setBorder(BorderFactory.createLineBorder(Color.black,2));
    panel.add(dataTable);
    setLayout(new BorderLayout());
    add(panel,BorderLayout.CENTER);
    i can see the table on my driver, but i want to fill it by connecting to the database and fil the fields from the database, i have the code to connect and retrieve the fields but on the dos, i want to fill them in the table,
    the code for accessing is
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         Connection conn1 = DriverManager.getConnection      ("jdbc:odbc:EHLAN",
                             "marius","svasdiga");
                   Statement stmt1 = conn1.createStatement();
                   Statement stmt2 = conn1.createStatement();
                   ResultSet rs1 = stmt1.executeQuery ("select * from Appartment");
                   System.out.println("App. Num, Stair Num, Elec. Num");
              while (rs1.next()) {
                   System.out.print (rs1.getInt ("appnum") + ","+" ");
                   System.out.print (rs1.getString ("staircase") + ","+" ");
                   System.out.println (rs1.getInt("electrnum") );
    ResultSet rs2 = stmt2.executeQuery ("select * from Person");
    System.out.println("First Name, Last Name, Blood Type");
              while (rs2.next()) {
                   System.out.print (rs2.getString ("namef") + ","+" ");
                   System.out.print (rs2.getString ("namel") + ","+" ");
                   System.out.println (rs2.getString("bloodType") );
    so help me to fill this data to the table. thank you
    yours sincerely,
    marius ajemian

    hi, i'm having trouble in filling a jtable with data, but the real problem is that i have stablished a JDBC connection throught the windowsxp ODBC to my database written on microsoft access platform, so i created my table
    public CenterPanel(){
    panel = new JPanel();
    dataTable = new JTable(10,10);
    dataTable.setBorder(BorderFactory.createLineBorder(Color.black,2));
    panel.add(dataTable);
    setLayout(new BorderLayout());
    add(panel,BorderLayout.CENTER);
    i can see the table on my driver, but i want to fill it by connecting to the database and fil the fields from the database, i have the code to connect and retrieve the fields but on the dos, i want to fill them in the table,
    the code for accessing is
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         Connection conn1 = DriverManager.getConnection      ("jdbc:odbc:EHLAN",
                             "marius","svasdiga");
                   Statement stmt1 = conn1.createStatement();
                   Statement stmt2 = conn1.createStatement();
                   ResultSet rs1 = stmt1.executeQuery ("select * from Appartment");
                   System.out.println("App. Num, Stair Num, Elec. Num");
              while (rs1.next()) {
                   System.out.print (rs1.getInt ("appnum") + ","+" ");
                   System.out.print (rs1.getString ("staircase") + ","+" ");
                   System.out.println (rs1.getInt("electrnum") );
    ResultSet rs2 = stmt2.executeQuery ("select * from Person");
    System.out.println("First Name, Last Name, Blood Type");
              while (rs2.next()) {
                   System.out.print (rs2.getString ("namef") + ","+" ");
                   System.out.print (rs2.getString ("namel") + ","+" ");
                   System.out.println (rs2.getString("bloodType") );
    so help me to fill this data to the table. thank you
    yours sincerely,
    marius ajemian

  • Filling a jtable with an array of Portfolio objects

    I have created a class Portfolio and want to put an array of portfolio objects in a Jtable.
    I created a tablePortfolioClass based on the AbstratTableModel and
    changed the classical 2 dimensional data array into a one dimensional arry of portfolio objects.
    The databaselayer correctly fills the Portfolio but does not display it inthe table...
    what am I doing wrong ?
    package DBpackage;
    import java.lang.String;
    public class Portfolio
    public Portfolio()
    public Portfolio(String sE)
    sEcode=sE;
    //here are normally set and getmethods that I left out
    private String sEcode;
    private double dQuantity;
    private double dAvgPrice;
    private double dPrice;
    private double dExchRate;
    private double dReturn;
    private String sDescr;
    private double dPerc;
    private double dTotal;
    =============================================================
    package DBpackage;
    import javax.swing.table.AbstractTableModel;
    class tablePortfolioClass extends AbstractTableModel
    Portfolio[]data=new Portfolio[50];
    final String[] columnNames={"Ecode","Description","Quantity","Price", "Avg","%","Total","Return"};
    public void tablePortfolioClass (int nrofRows)
    iRows=nrofRows;
    public void tablePortfolioClass(Portfolio[] pp)
    data=pp;
    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];
    public void setValueAt(Portfolio value, int row, int col) {
    data[row] = value;
    fireTableCellUpdated(row, col);
    private int iRows;
    private int iCols=4;
    =============================================================
    this is what is done in the frame
    Portfolio [] pf=new Portfolio[50];
    tablePortfolioClass pp=new tablePortfolioClass();
    //tablePortfolioClass pp=new tablePortfolioClass(pf); this one does not compile
    JTable grdPP=new JTable(pp);
    grdPP.setPreferredScrollableViewportSize(new Dimension(200,200));
    JScrollPane jscrollPanePP=new JScrollPane(grdPP);
    all more traditional implementations of the jtable work without any problem...
    anyone ?

    Your getValueAt() method should return the actual value you want to display in the table at the given row and column. Right now, it returns the whole Portfolio object. How is the table supposed to render a Portfolio object?
    Something more like this would make more sensepublic Object getValueAt(int row, int col)
      switch (col) {
      case 0:
        return data[row].getEcode();
      case 1:
        return data[row].getDescr();
      case 7:
        return new Double(data[row].getReturn());
    }The same can be said for your setValueAt() method. It should set the individual attributes of the Portfolio object at the given row rather than changing the whole object.

  • Reporting errors while filling a JTable

    Hello all, this is my first post here.
    When i implement a class derived from AbstractTableModel to show some data in a JTable, sometimes, specially when this data is coming from databases, i need to be able to report any errors that ocur while geting that data via a message dialog, for example, specifically inside the overriden getValueAt() function, eg.
    public Object getValueAt(int rowIndex, int columnIndex) {
    try{
    ..... read the information from the database
    }catch(SQLException ex){
    JOptionPane.showMessageDialog(null, "Error!"........ show the error
    this actually works, the message dialog is shown if an error ocurs, however there are 2 problems:
    1.- after the user closes the message dialog, the JTable is not painted properly.
    2.- i get all these exceptions:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at javax.swing.SwingUtilities.computeIntersection(SwingUtilities.java:417)
    at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:430)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:114)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
    If i just remove the line that shows the message dialog, then everything works ok. But i NEED a way to inform the user that something went wrong, how do i do this?
    Thanks!

    Hey numbnuts,
    People keep reporting this error and you keep closing it w/o proper attention:
    In SwingUtilities, sometimes "dest" becomes null. Don't tell why - sometimes its because of some library maybe you didnt write. But if you put in a "*if (dest == null) o something ...*" in there - it would fix it. Even a freshman comp sci programmer knows that.
    And you wonder why nobody wants to learn Java anymore...
        public static Rectangle computeIntersection(int x,int y,int width,int height,Rectangle dest) {
            int x1 = (x > dest.x) ? x : dest.x;
            int x2 = ((x+width) < (dest.x + dest.width)) ? (x+width) : (dest.x + dest.width);
            int y1 = (y > dest.y) ? y : dest.y;
            int y2 = ((y + height) < (dest.y + dest.height) ? (y+height) : (dest.y + dest.height));
            dest.x = x1;
            dest.y = y1;
            dest.width = x2 - x1;
            dest.height = y2 - y1;
         // If rectangles don't intersect, return zero'd intersection.
         if (dest.width < 0 || dest.height < 0) {
             dest.x = dest.y = dest.width = dest.height = 0;
            return dest;
        }End Communication

  • Student in distress: Read data from text file to fill a JTable

    I'm already late 2 weeks for my project and I still can't figure this out :(
    The project is made of 3 classes; the main one is Viewer.java; it creates the interface, Menu.java that manages the menu and the methods related to it and finally JTableData.java that extends JTable ( This is the part that I don't really understand)
    In the class MENU.JAVA I wrote the method jMenuOpen_actionPerformed(...) for the button OUVRIR (Open) that let's me select the file to read, then puts the content in a 2D table. Here' s my problem: I have to somehow update the content of the table created in VIEWER.JAVA with the content read from the file (cvs file delimited by ";") using a JTableData object (?)
    //THIS IS THE FIRST CLASS VIEWER.JAVA THAT CONTAINS THE MAIN METHOD
    //AND CREATES THE INTERFACE
    package viewer;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Viewer extends JFrame {
      public Menu menu = null;
      GridLayout gridLayout1 = new GridLayout();
      JTabbedPane jTabbedPane = new JTabbedPane();             
      JTableData jTableInfo = new JTableData(30, 7);
      public Viewer() {
              addWindowListener(new WindowAdapter()
              {               public void windowClosing(WindowEvent e)
                        dispose();
                        System.exit(0);
            try 
                jbInit();
                this.setSize(1000, 700);
                this.setVisible(true);
            catch(Exception e)
                e.printStackTrace();
      public static void main(String[] args) {
          Viewer viewer = new Viewer();
      private void jbInit() throws Exception {
        menu = new Menu(this);
        gridLayout1.setColumns(1);
        this.setTitle("Viewer");
        this.getContentPane().setLayout(gridLayout1);
        jTableInfo.setMaximumSize(new Dimension(0, 64));
        jTableInfo.setPreferredSize(new Dimension(0, 64));
        //TO DO Partie de droite
        JTabbedPane webViewerTabs = new JTabbedPane();
        //972 3299
        //java.net.URL URL1 = new java.net.URL("http://www.nba.com");
        //java.net.URL URL2 = new java.net.URL("http://www.insidehoops.com");
        //java.net.URL URL3 = new java.net.URL("http://www.cnn.com");
        JEditorPane webViewer01 = new JEditorPane();
        webViewer01.setEditable(false);
        //webViewer01.setPage(URL1);
        JEditorPane webViewer02 = new JEditorPane();
        webViewer02.setEditable(false);
        //webViewer02.setPage(URL2);
        JEditorPane webViewer03 = new JEditorPane();
        webViewer03.setEditable(false);
        //webViewer03.setPage(URL3);
        webViewerTabs.addTab("Site01", webViewer01);
        webViewerTabs.addTab("Site02", webViewer02);
        webViewerTabs.addTab("Site03", webViewer03);
        jTabbedPane.add(webViewerTabs);
            //End TO DO   
        this.getContentPane().add(jTableInfo);
        this.getContentPane().add(jTabbedPane);
        this.setJMenuBar(menu);  
    //This is the MENU.JAVA CLASS WHERE I OPEN THE FILE, READ THE
    //CONTENT AND WHERE I SHOULD SEND THE DATA TO THE TABLE.
    //Title:        Menu
    //Author:       Luc Duong
    package viewer;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    public class Menu extends JMenuBar {
      JMenu jMenu1 = new JMenu();
      JMenuItem jMenuNew = new JMenuItem();
      JMenuItem jMenuOpen = new JMenuItem();
      JMenuItem jMenuSave = new JMenuItem();
      JMenuItem jMenuExit = new JMenuItem();
      JMenuItem jMenuApropos = new JMenuItem();
      JFileChooser fileChooser = new JFileChooser();
      Viewer viewer = null;
      boolean isFileChanged = false;
      private File fileName;
      static String data [][] = new String[7][9];
      public int lineCount;
      public Menu(Viewer viewer) {
        try  {
          jbInit();
          this.viewer = viewer;
          this.add(jMenu1);
        catch(Exception e) {
          e.printStackTrace();
      private void jbInit() throws Exception {
        jMenu1.setText("Fichier");
        jMenuNew.setText("Nouveau");
        jMenuNew.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            jMenuNew_actionPerformed(e);
        jMenuOpen.setText("Ouvrir");
        jMenuOpen.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            jMenuOpen_actionPerformed(e);
        jMenuSave.setText("Sauvegarder");
        jMenuSave.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            jMenuSave_actionPerformed(e);
        jMenuExit.setText("Quitter");
        jMenuExit.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            jMenuExit_actionPerformed(e);
        jMenuApropos.setText("A propos");
        jMenuApropos.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            jMenuApropos_actionPerformed(e);
        jMenu1.add(jMenuNew);
        jMenu1.add(jMenuOpen);
        jMenu1.add(jMenuSave);
        jMenu1.add(jMenuExit);       
        jMenu1.add(jMenuApropos);   
      void jMenuNew_actionPerformed(ActionEvent e) {
      //THIS IS THE METHOD I'M WORKING ON RIGHT NOW
      void jMenuOpen_actionPerformed(ActionEvent e) {
          fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
          int result = fileChooser.showOpenDialog(this);
          if (result == JFileChooser.CANCEL_OPTION) return;
          if (result == JFileChooser.APPROVE_OPTION)
              //[email protected]
              File chosenFile = fileChooser.getSelectedFile();
              String path = chosenFile.getPath();
              String nom = chosenFile.getName();
              boolean exist = chosenFile.exists();
              try
                FileReader fr = new FileReader(chosenFile);
                BufferedReader reader = new BufferedReader(fr);
                System.out.println("Opening File Successful!" + chosenFile.getName());
                //String  qui contient la ligne courante
                String currentLine = new String();
                StringTokenizer currentLineTokens = new StringTokenizer("");
                int row = 0;
                int column = 0;
                while( (currentLine = reader.readLine() ) != null)
                    currentLineTokens = new StringTokenizer(currentLine,";");
                    System.out.println("Now reading line index: " + row);
                    while(currentLineTokens.hasMoreTokens())
                        data[row][column] = currentLineTokens.nextToken();
                        System.out.println(column + "\t" + data[row][column]);
                        if(column>=8) column=-1;
                        column++;
                    row++;
                lineCount = row-1;
                System.out.println("\nNombre total de lignes: " + lineCount);
            catch(Exception ex)
                System.out.println("Test: " + ex.getMessage());
                JOptionPane.showMessageDialog(this, "Erreur d'ouverture du fichier", "Erreur d'ouverture du fichier", JOptionPane.ERROR_MESSAGE);
      void jMenuSave_actionPerformed(ActionEvent e) {
          if (JFileChooser.APPROVE_OPTION == fileChooser.showSaveDialog(this))
                System.err.println("Save: " + fileChooser.getSelectedFile().getPath());     
      void jMenuExit_actionPerformed(ActionEvent e) {
        if (!isFileChanged)
           System.exit(1);
        else
            JOptionPane.showConfirmDialog(null, "Do you want to save now?", "Save?", JOptionPane.YES_NO_OPTION);
          // ask the user if he want to save
          // yes or no?
          // yes
           jMenuSave_actionPerformed(e);
          // no
          System.exit(1);
      void jMenuApropos_actionPerformed(ActionEvent e) {
    //THIS IS THE JTABLEDATA.JAVA CLASS THAT EXTENDS JTable. I'm not sure
    // how this works :(//Title: JTableData
    //Author: Luc Duong
    package viewer;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class JTableData extends JTable {
    public JTableData(int row, int col)
    super(row, col);

    Hi, Salut
    you should use JTable's DataModel to update your table.
    data[row][column] = currentLineTokens.nextToken();
    jTableInfo.getModel().setValueAt(data[row][column], row, column);
    jTableInfo.repaint();BEWARE CSV files and StringTokenizer, i've had problems with it (for example ;;Test; is not tokenized "", "", "Test")
    StringTokenizer ignores separator when in first position, and ignores double separators. I use this piece of code before tokenize a String :
    private static char _separator = ';';
    private static String checkCsvString(String s) {
             * V�rification du s�parateur inital, perdu par le StringTokenizer et
             * pourtant bien important
            if (s.startsWith("" + _separator)) {
                s = " " + s;
             * V�rification des doubles s�parateurs, perdus par le StringTokenizer
            int index;
            while ((index = s.indexOf("" + _separator + _separator)) >= 0) {
                s = s.substring(0, index) + _separator + " " + _separator + s.substring(index + 2);
            return s;
        }hope it helps
    Nico

  • How to fill the data in JTable at runtime

    Hi all,
    I am having a JButton and also a JTable.
    Now my problem is that intitially am setting the value of each column in the table to zero.
    But when I click the JButton i have to fill the JTable with all the new values.
    Please hepl me out solving this problem.
    I am really struck.
    Regards
    RAKESH SAGAR

    If other suggested links give you nothing - take a look at:
    http://forum.java.sun.com/thread.jspa?threadID=699117
    It seems Tjirpovf have code somewhat similar what you are asking for ("reply 5" - fill table with data from GUI). And you might even find my answer to his question useful ("reply 7" - fill table with data from file and save table data to file).

  • JTable problem when deleting all rows and reinserting data,

    Hi,
    I have a JTable with an AbstractModelTable.
    Some cells in the JTable have a custom cell editor. I am using
    the cell editor that accepts only numeric values as explained in
    the JTable tutorial (WholeNumberField).
    - The JTable gets filled by choosing a value from a JList
    for example:
    1- choose a customer name from the customer JList
    2- gets the customer order (database)
    3- fills the Jtable with the customer data.
    - When a customer is chosen from the Jlist I call a function
    inside my table model. (This function removes all rows, clears the vector holding the data and calls fireTableRowsDeleted (firstRow, lastRow));
    - Then I fill up the new data for this customer.
    All of this works fine, except if I have entered a new value inside
    one of the cell that has a customed cellEditor (ex: the Ordered column).
    for example : user enters number 20 in the "ordered" column for customer A. Then changes his mind and chooses customer B from the JList. So the JTable gets cleared and refilled with the data of Customer B but the column "ordered" still has the value '20'
    I would really appreciate any help...
    Thanks

    Don't know is this will work, but try the following before updating the table:
    if (table.isEditing())
      table.removeEditor();Also, why do two TableModelEvent's..one for all getting deleted, one for the new filling. You could do one fireTableDataChanged after the new data is in.

  • How to Sort JTable data using Multiple fields (Date, time and string)

    I have to fill the JTable data with some date, time and string values. for example my table data looks like this:
    "1998/12/14","15:14:38","Unicorn1","row1"
    "1998/12/14","15:14:39","Unicorn2","row2"
    "1998/12/14","15:14:40","Unicorn4","row3"
    "1998/12/17","12:14:12","Unicorn4","row6"
    Now the Sorted Table should be in the following way:
    "1998/12/17","12:14:12","Unicorn4","row6"
    "1998/12/14","15:14:40","Unicorn4","row3"
    "1998/12/14","15:14:39","Unicorn2","row2"
    "1998/12/14","15:14:38","Unicorn1","row1"
    ie First Date field should be sorted, if 2 date fields are same then sort based on time. if date and time fields are same then need to be sorted on String field.
    So if any one worked on this please throw some light on how to proceed. I know how to sort based on single column.
    But now i need to sort on multiple columns.So what is code change in the Comparater class.
    Thanks in advance.. This is urgent....

    I think your Schedule objects should implement Comparable. Then you can sort your linked list using the Collections.sort() method without passing in a Comparator.class Schedule(Date date, String class) implements Comparable
      public void compareTo(Object obj)
        Schedule other = (Schedule)obj;
        return date.getTime() - other.getDate().getTime();
    }

  • JDev902: how open form with empty JTable?

    Background: Using the wizard I have created a number of JClient forms pulling their data from a BC-layer. However, some forms fill only very slowly because of the large number of rows of the underlying tables. Sometimes it would be better to open a form with an empty JTable and let the user formulate a query and pull in the desired data.
    Question: How do I open a form without automatically filling its JTable from the BC-layer? The old method of setting "...WHERE 1 = 0" seems rather - well - old! Is there a more elegant way?
    Thanks for any help!
    Sten Jones

    You can bring up the panel that the JTable is contained in without executing the query on it (remove executeQuery()) call. See JClient component demo on the JDeveloper HowTo pages on how to detail data-binding and query execution. Basically what these panels do is not setup the UI till it's displayed and then perform the binding. You can take it a step further by also not executing the query and executing it only after the user says so.
    Another way would be to "force" the startup to be in find mode. So, instead of executing query for the panels, you may want to set the table in find mode so that the user is able to enter query right up, when the UI comes up.

  • Strange JTable/JViewport resizing

    Folk'ses,
    i have a strange problem with a JTable and its viewport when i change the data and column model.
    * autoResizeMode is set to AUTO_RESIZE_ALL_COLUMNS.
    * all my columns have a minimum size
    * when i change my data and column model i do not get a scrollbar in the surrounding scrollpane
    in the 1.5 JTable.doLayout() doc i found the following note:
    Note: When a JTable makes adjustments to the widths of the columns it respects their minimum and maximum values absolutely. It is therefore possible that, even after this method is called, the total width of the columns is still not equal to the width of the table. When this happens the JTable does not put itself in AUTO_RESIZE_OFF mode to bring up a scroll bar, or break other commitments of its current auto-resize mode -- instead it allows its bounds to be set larger (or smaller) than the total of the column minimum or maximum, meaning, either that there will not be enough room to display all of the columns, or that the columns will not fill the JTable's bounds. These respectively, result in the clipping of some columns or an area being painted in the JTable's background color during painting.
    has anybody an idea how to get around this problem?
    is it so uncommon?
    why did they implement it like that?
    frustrated,
    thomas

    frustrated,Yes, a verbal description of the problem doesn't always help me. I have no idea what you code is like, what layout manger you are using etc.....
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • Printing JTable content

    i wrote a program that reads from a MS-Access db and fill a jtable. i want to print out the content of the jtable.
    the problem is that i did not use PrinterJob class before and i can fiugre out how to get the selected rows data and passing it to the printer.
    if anyone did this before, kindly advise how to do it??
    thanx in advance
    Mina Guindy

    Hi, try PrintUtilities.java. You just pass the component,in this case the table, to the constructor and call print. You might want to study it since I cannot gaurantee the quality of the code. I am doing something fun, so I don't really want to go that deep:(
    * 7/99 Marty Hall, http://www.apl.jhu.edu/~hall/java/
    * May be freely used or adapted.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.print.*;
    public class PrintUtilities implements Printable {
    private Component componentToBePrinted;
    public static void printComponent(Component c) {
    new PrintUtilities(c).print();
    public PrintUtilities(Component componentToBePrinted) {
    this.componentToBePrinted = componentToBePrinted;
    public void print() {
    PrinterJob printJob = PrinterJob.getPrinterJob();
    Paper p1=new Paper();
    p1.setImageableArea(1,1,3,9);
    p1.setSize(4,12);
    PageFormat pf1=new PageFormat();
    pf1.setPaper(p1);
    printJob.setPrintable(this,pf1);
    //if (printJob.printDialog())
    if (true)
    try {
    printJob.print();
    } catch(PrinterException pe) {
    System.out.println("Error printing: " + pe);
    public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
    if (pageIndex > 0) {
    return(NO_SUCH_PAGE);
    } else {
    Graphics2D g2d = (Graphics2D)g;
    g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    disableDoubleBuffering(componentToBePrinted);
    componentToBePrinted.paint(g2d);
    enableDoubleBuffering(componentToBePrinted);
    return(PAGE_EXISTS);
    /** The speed and quality of printing suffers dramatically if
    * any of the containers have double buffering turned on.
    * So this turns if off globally.
    * @see enableDoubleBuffering
    public static void disableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(false);
    /** Re-enables double buffering globally. */
    public static void enableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(true);

  • Russian JTable under Solaris

    Hi,
    I have Swing JTables. If I configure my Windows2k with
    russion display and keyboard settings I can fill the JTable with
    russian characters. But if I try it under Solaris no
    characters will be displayed only the ASCII.
    Does anyone know a solution, it�s very urgend.
    thanx Stephan

    Now I have a function .setLocale:
    datesTable.setLocale(ctrl.getCountry());
    in my ctrl Object is the locale saved.
    but this function doesn�t change the JTable.

  • Add event(keyListener) to JTable Cell default editor.

    I've got a form(Jdialog) with a Jtable on it.
    I've added a keyListener to the JButtons and Jtable so that, wherever the the focus IS, when I hit the "F7" key, it fills the Jtable from the database connection.
    It's working REALLY fine now but there is one small glitch.
    When I'm editing a cell, the keyListener event is not thrown. I supposed it's because the "DefaultCellEditor" does not throw the event.
    How can I add such a thing??
    I'm looking for something like :
    table.getDefaultEditor().addKeyListener
    but it does not exists.
    If it's not possible, is there a way to make the JDialog listen to all the keyListener events from its childs??(Mimics the JDK < 1.4)
    Thx

    Using key binding is better implementation.
    After you read the tutorial your next move is to google for it.
    http://www.google.com/search?hl=en&q=jtable+keybinding
    Second result brings you to camickr's example:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=657819

  • Saving ResultSet Data From JTable

    Hi! I need help! I am using a JTable to display resultsets from an oracle database. I am retrieving the columns and rows from the DB and putting them into vectors. Then I return the table and display it in a JScrollpane. I have a button which searches the db table for my query and fills the JTable with the results. Now, I am trying to save that result using a JFileChooser or some form of saving method. Does anyone have any idea how I could do this? Thanks.

    The JFileChooser will only give you a dialog that asks the user for a filename, it doesn't do the saving for you.
    Your question belongs into the swing or general programming category, since the database portion is all working, but here's a hint:
    You are trying to pull the data out of the table and save it to the file. Create a FileOutputStream for the filename the user choses in the file-choser, then iterate the rows and columns of the table (or the table's model (look at the JTable.getModel() method) and write the values to the file, maybe separated by commas and each row terminated by a carriage-return/linefeed combination.
    This should give you a nice CSV file (that can be read by Excel) containing the data that is in your table.

  • Problem in refreshing jinternalframe

    Hello,
    In java code I have added jtable to jinternalframe and
    on each button click I have to show new values filled in jtable which is in jinternalframe.But I am getting new jinternalframe next to original jinternalframe.I want new jinternalframe to be superimposed on previous.What is solution to this?
    code:
    buttonNext.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e) {
    System.out.println("rowno"+tableActual.getRowCount());
    if(i<tableActual.getRowCount())
    String s1=tableActual.getValueAt(i,1).toString();
    System.out.println("s1:"+s1);
    tableVirtual.table.setValueAt(s1,i,1);
    System.out.println("s1 in vtable:"+tableVirtual.table.getValueAt(i,1));
    stepLabel.setText("Calculating Gen"+tableVirtual.table.getValueAt(i,1));
    String s2=tableActual.getValueAt(i,2).toString();
    tableVirtual.table.setValueAt(s2,i,2);
    stepLabel.setText("Calculating Kill"+tableVirtual.table.getValueAt(i,1));
    i=i+1;
    System.out.println("i="+i);
    tableVirtual.showTable();
    desktop.remove(frame);
    JInternalFrame frame = new JInternalFrame("SimpleTableDemo",true,true,true,true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    tableVirtual.setOpaque(true); //content panes must be opaque
    frame.setContentPane(tableVirtual);
    //Display the window.
    frame.pack();
    frame.setLocation(0,451);
    frame.setVisible(true);
    desktop.add(frame);
    });

    I have tried it. But its giving next internal frame of half size than previous one.
    And new jinternalframe is still in background of previous one.What to do to take it to front?I have tried jinternalframe.front().But it has no effect.

Maybe you are looking for