JTable problem

I'm writing an application that will display info in multiple tables. I thought it would be a good idea to write my own table class. The problem is that only the table data appears, but not the table headers.
Layout.java creates an object of MyTable.java. The "createTable" constructor returns a JPanel wich in turn contains a JTable.
Layout.java (creates the GUI, extends JFrame)
    String[] headers = {"1","2","3","4","5","6"};
    String[][] data = {{"one","two","three","four","five","six"},{"seven","eight","nine","ten","eleven","twelve"}};
    MyTable jt = new MyTable();
    Component table = jt.createTable(data, headers);
    JScrollPane jsp = new JScrollPane(table);
    getContentPane().add(jsp, BorderLayout.CENTER);
MyTable.javapublic Component createTable(String[][] d, String[] h)
    data = d;
    headers = h;
    JPanel contentPane = new JPanel();
    TableModel tm = new AbstractTableModel(){
     public int getRowCount(){return data.length;}
     public int getColumnCount() {return headers.length;}
     public Object getValueAt(int r, int c) {return data[r][c];}
          public String getColumnName(int c) {return headers[c];}
    JTable jt = new JTable(tm);
    jt.setMaximumSize(new Dimension(700,40));
    jt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    contentPane.add(jt);
    return contentPane;
}

The table headers are not really part of the table, they are a separate component.
Normally a JTable is added directly to a JScrollPane. The JScrollPane is smart enough to take the column information create a component and add this component to the JScrollPane using the setColumnHeaderView() method of JScrollPane.
In your example you are adding the JTable to a Component and then adding the Component to a JScrollPane so the headers don't get created.
I suggest you add your table to the scrollpane in your createTable() method.

Similar Messages

  • URGENT HELP NEEDED FOR JTABLE PROBLEM!!!!!!!!!!!!!!!!!

    firstly i made a jtable to adds and deletes rows and passes the the data to the table model from some textfields. then i wanted to add a tablemoselistener method in order to change the value in the columns 1,2,3,4 and set the result of them in the column 5. when i added that portion of code the buttons that added and deleted rows had problems to function correctly..they dont work at all..can somebody have a look in my code and see wot is wrong..thanx in advance..
    below follows the code..sorry for the mesh of the code..you can use and run the code and notice the problem when you press the add button..also if you want delete the TableChanged method to see that the add button works perfect.
    * Created on 03-Aug-2005
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    * @author Administrator
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Vector;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import java.io.*;
    public class NodesTable extends JFrame implements TableModelListener, ActionListener {
    JTable jt;
    DefaultTableColumnModel dtcm;
    TableColumn column[] = new TableColumn[100];
    DefaultTableModel dtm;
    JLabel Name,m1,w1,m2,w2;
    JTextField NameTF,m1TF,w1TF,m2TF,w2TF;
    String c [] ={ "Name", "Assessment1", "Weight1" , "Assessment2","Weight2 ","TotalMark"};
    float x=0,y=0,tMark=0,z = 0;
    float j=0;
    int i;
         JButton DelButton;
         JButton AddButton;
         JScrollPane scrollPane;
         JPanel mainPanel,buttonPanel;
         JFrame frame;
         Object[][] data =
              {"tami", new Float(1), new Float(1.11), new Float(1.11),new Float(1),new Float(1)},
              {"tami", new Float(1), new Float(2.22), new Float(2.22),new Float(1),new Float(1)},
              {"petros", new Float(1), new Float(3.33), new Float(3.33),new Float(1),new Float(1)},
              {"petros", new Float(1), new Float(4.44), new Float(4.44),new Float(1),new Float(1)}
    public NodesTable() {
    super("Student Marking Spreadsheet");
    this.AddNodesintoTable();
    setSize(400,250);
    setVisible(true);
    public void AddNodesintoTable(){
    // Create a vector object and load them with the data
    // to be placed on each row of the table
    dtm = new DefaultTableModel(data,c);
    dtm.addTableModelListener( this );
    jt = new JTable(dtm){
         // Returning the Class of each column will allow different
              // renderers to be used based on Class
              public Class getColumnClass(int column)
                   return getValueAt(0, column).getClass();
              // The Cost is not editable
              public boolean isCellEditable(int row, int column)
                   int modelColumn = convertColumnIndexToModel( column );
                   return (modelColumn == 5) ? false : true;
    //****************************User Input**************************
    //Add another node
    //Creating and setting the properties
    //of the panel's component (panels and textfields)
    Name = new JLabel("Name");
    Name.setForeground(Color.black);
    m1 = new JLabel("Mark1");
    m1.setForeground(Color.black);
    w1 = new JLabel("Weigth1");
    w1.setForeground(Color.black);
    m2= new JLabel("Mark2");
    m2.setForeground(Color.black);
    w2 = new JLabel("Weight2");
    w2.setForeground(Color.black);
    NameTF = new JTextField(5);
    NameTF.setText("Node");
    m1TF = new JTextField(5);
    w1TF = new JTextField(5);
    m2TF=new JTextField(5);
    w2TF=new JTextField(5);
    //creating the buttons
    JPanel buttonPanel = new JPanel();
    AddButton=new JButton("Add Row");
    DelButton=new JButton("Delete") ;
    buttonPanel.add(AddButton);
    buttonPanel.add(DelButton);
    //adding the components to the panel
    JPanel inputpanel = new JPanel();
    inputpanel.add(Name);
    inputpanel.add(NameTF);
    inputpanel.add(m1);
    inputpanel.add(m1TF);
    inputpanel.add(w1);
    inputpanel.add(w1TF);
    inputpanel.add(m2);
    inputpanel.add(m2TF);
    inputpanel.add(w2TF);
    inputpanel.add(w2);
    inputpanel.add(AddButton);
    inputpanel.add(DelButton);
    //creating the panel and setting its properties
    JPanel tablepanel = new JPanel();
    tablepanel.add(new JScrollPane(jt, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED
    , JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
    getContentPane().add(tablepanel, BorderLayout.CENTER);
    getContentPane().add(inputpanel, BorderLayout.SOUTH);
    //Method to add row for each new entry
    public void addRow()
    Vector r=new Vector();
    r=createBlankElement();
    dtm.addRow(r);
    jt.addNotify();
    public Vector createBlankElement()
    Vector t = new Vector();
    t.addElement((String) " ");
    t.addElement((String) " ");
    t.addElement((String) " ");
    t.addElement((String) " ");
    t.addElement((String) " ");
    return t;
    // Method to delete a row from the spreadsheet
    void deleteRow(int index)
    if(index!=-1) //At least one Row in Table
    dtm.removeRow(index);
    jt.addNotify();
    // Method that adds and deletes rows
    // from the table by pressing the
    //corresponding buttons
    public void actionPerformed(ActionEvent ae){
         Float z=new Float (m2TF.getText());
    String Name= NameTF.getText();
    Float x= new Float(m1TF.getText());
    Float y= new Float(w1TF.getText());
    Float j=new Float (w2TF.getText());
    JFileChooser jfc2 = new JFileChooser();
    String newdata[]= {Name,String.valueOf(x),String.valueOf(y),
    String.valueOf(z),String.valueOf(j)};
    Object source = ae.getSource();
    if(ae.getSource() == (JButton)AddButton)
    addRow();
    if (ae.getSource() ==(JButton) DelButton)
    deleteRow(jt.getSelectedRow());
    //method to calculate the total mark in the TotalMark column
    //that updates the values in every other column
    //It takes the values from the column 1,2,3,4
    //and changes the value in the column 5
    public void tableChanged(TableModelEvent e) {
         System.out.println(e.getSource());
         if (e.getType() == TableModelEvent.UPDATE)
              int row = e.getFirstRow();
              int column = e.getColumn();
              if (column == 1 || column == 2 ||column == 3 ||column == 4)
                   TableModel model = jt.getModel();
              float     q= ((Float)model.getValueAt(row,1)).floatValue();
              float     w= ((Float)model.getValueAt(row,2)).floatValue();
              float     t= ((Float)model.getValueAt(row,3)).floatValue();
              float     r= ((Float)model.getValueAt(row,4)).floatValue();
                   Float tMark = new Float((q*w+t*r)/(w+r) );
                   model.setValueAt(tMark, row, 5);
    // Which cells are editable.
    // It is only necessary to implement this method
    // if the table is editable
    public boolean isCellEditable(int row, int col)
    { return true; //All cells are editable
    public static void main(String[] args) {
         NodesTable t=new NodesTable();
    }

    There are too many mistakes in your program. It looks like you are new to java.
    Your add and delete row buttons are not working because you haven't registered your action listener with these buttons.
    I have modifide your code and now it works fine. Just put some validation code for the textboxes becuase it throws exception when user presses add button without entering anything.
    Here is the updated code: Do the diff and u will know my changes
    * Created on 03-Aug-2005
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    * @author Administrator
    * TODO To change the template for this generated type comment go to Window -
    * Preferences - Java - Code Style - Code Templates
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.DefaultTableColumnModel;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableModel;
    public class NodesTable extends JFrame implements TableModelListener,
              ActionListener {
         JTable jt;
         DefaultTableColumnModel dtcm;
         TableColumn column[] = new TableColumn[100];
         DefaultTableModel dtm;
         JLabel Name, m1, w1, m2, w2;
         JTextField NameTF, m1TF, w1TF, m2TF, w2TF;
         String c[] = { "Name", "Assessment1", "Weight1", "Assessment2", "Weight2 ",
                   "TotalMark" };
         float x = 0, y = 0, tMark = 0, z = 0;
         float j = 0;
         int i;
         JButton DelButton;
         JButton AddButton;
         JScrollPane scrollPane;
         JPanel mainPanel, buttonPanel;
         JFrame frame;
         public NodesTable() {
              super("Student Marking Spreadsheet");
              this.AddNodesintoTable();
              setSize(400, 250);
              setVisible(true);
         public void AddNodesintoTable() {
              // Create a vector object and load them with the data
              // to be placed on each row of the table
              dtm = new DefaultTableModel(c,0);
              dtm.addTableModelListener(this);
              jt = new JTable(dtm) {
                   // The Cost is not editable
                   public boolean isCellEditable(int row, int column) {
                        int modelColumn = convertColumnIndexToModel(column);
                        return (modelColumn == 5) ? false : true;
              //****************************User Input**************************
              //Add another node
              //Creating and setting the properties
              //of the panel's component (panels and textfields)
              Name = new JLabel("Name");
              Name.setForeground(Color.black);
              m1 = new JLabel("Mark1");
              m1.setForeground(Color.black);
              w1 = new JLabel("Weigth1");
              w1.setForeground(Color.black);
              m2 = new JLabel("Mark2");
              m2.setForeground(Color.black);
              w2 = new JLabel("Weight2");
              w2.setForeground(Color.black);
              NameTF = new JTextField(5);
              NameTF.setText("Node");
              m1TF = new JTextField(5);
              w1TF = new JTextField(5);
              m2TF = new JTextField(5);
              w2TF = new JTextField(5);
              //creating the buttons
              JPanel buttonPanel = new JPanel();
              AddButton = new JButton("Add Row");
              AddButton.addActionListener(this);
              DelButton = new JButton("Delete");
              DelButton.addActionListener(this);
              buttonPanel.add(AddButton);
              buttonPanel.add(DelButton);
              //adding the components to the panel
              JPanel inputpanel = new JPanel();
              inputpanel.add(Name);
              inputpanel.add(NameTF);
              inputpanel.add(m1);
              inputpanel.add(m1TF);
              inputpanel.add(w1);
              inputpanel.add(w1TF);
              inputpanel.add(m2);
              inputpanel.add(m2TF);
              inputpanel.add(w2TF);
              inputpanel.add(w2);
              inputpanel.add(AddButton);
              inputpanel.add(DelButton);
              //creating the panel and setting its properties
              JPanel tablepanel = new JPanel();
              tablepanel.add(new JScrollPane(jt,
                        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                        JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
              getContentPane().add(tablepanel, BorderLayout.CENTER);
              getContentPane().add(inputpanel, BorderLayout.SOUTH);
         //Method to add row for each new entry
         public void addRow() {
              Float z = new Float(m2TF.getText());
              String Name = NameTF.getText();
              Float x = new Float(m1TF.getText());
              Float y = new Float(w1TF.getText());
              Float j = new Float(w2TF.getText());
              String newdata[] = { Name, String.valueOf(x), String.valueOf(y),
                        String.valueOf(z), String.valueOf(j) };
              dtm.addRow(newdata);
         // Method to delete a row from the spreadsheet
         void deleteRow(int index) {
              if (index != -1) //At least one Row in Table
                   dtm.removeRow(index);
                   jt.addNotify();
         // Method that adds and deletes rows
         // from the table by pressing the
         //corresponding buttons
         public void actionPerformed(ActionEvent ae) {
              Object source = ae.getSource();
              if (ae.getSource() == (JButton) AddButton) {
                   addRow();
              if (ae.getSource() == (JButton) DelButton) {
                   deleteRow(jt.getSelectedRow());
         //method to calculate the total mark in the TotalMark column
         //that updates the values in every other column
         //It takes the values from the column 1,2,3,4
         //and changes the value in the column 5
         public void tableChanged(TableModelEvent e) {
              System.out.println(e.getSource());
              //if (e.getType() == TableModelEvent.UPDATE) {
                   int row = e.getFirstRow();
                   int column = e.getColumn();
                   if (column == 1 || column == 2 || column == 3 || column == 4) {
                        TableModel model = jt.getModel();
                        float q = (new Float(model.getValueAt(row, 1).toString())).floatValue();
                        float w = (new Float(model.getValueAt(row, 2).toString())).floatValue();
                        float t = (new Float(model.getValueAt(row, 3).toString())).floatValue();
                        float r = (new Float(model.getValueAt(row, 4).toString())).floatValue();
                        Float tMark = new Float((q * w + t * r) / (w + r));
                        model.setValueAt(tMark, row, 5);
         // Which cells are editable.
         // It is only necessary to implement this method
         // if the table is editable
         public boolean isCellEditable(int row, int col) {
              return true; //All cells are editable
         public static void main(String[] args) {
              NodesTable t = new NodesTable();
    }

  • JTable problem...can anybody help me...

    hi i have try out some jtable program. I have done some alteration to the table that it can resize row and column via the gridline. but it seems that when i'm resizing through the gridline, the row header did not resize. I sense that the row header not syncronizing with the main table. So when i'm tried to resize, the row header didn't
    can you solve my problem...
    //the main program
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Test {     public static void main(String[] args)
         //row headers:     
         String[][] rowHeaders = {{"Alpha"},{"Beta"}, {"Gamma"}};
         JTable leftTable = new JTable(rowHeaders, new Object[]{""});
         leftTable.setDefaultRenderer(
              Object.class, leftTable.getTableHeader().getDefaultRenderer());
         leftTable.setPreferredScrollableViewportSize(new Dimension(50,100));      
         //main table:
         Object[][] sampleData = {{"Homer", "Simpson"},{"Seymour","Skinner"},{"Ned","Flanders"}};
         JTable mainTable = new JTable(sampleData, new Object[]{"",""});
         //scroll pane:
         JScrollPane sp = new JScrollPane(
              mainTable, ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);     
              sp.setRowHeaderView(leftTable);          
              sp.setColumnHeaderView(null);      
         new TableColumnResizer(mainTable);
         new TableRowResizer(mainTable); 
         //frame:
         final JFrame f = new JFrame("Test");
         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         f.getContentPane().add(sp);     
         f.pack();
         SwingUtilities.invokeLater(new Runnable(){
                   public void run(){     f.setLocationRelativeTo(null);
                                       f.setVisible(true);               }          });     
    }This the TableColumnResizer.java
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.MouseInputAdapter;
    import java.awt.*;
    import java.awt.event.MouseEvent;
    import java.awt.event.*;
    public class TableColumnResizer extends MouseInputAdapter
        public static Cursor resizeCursor = Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR);
        private int mouseXOffset;
        private Cursor otherCursor = resizeCursor;
        private JTable table;
        public TableColumnResizer(JTable table){
            this.table = table;
            table.addMouseListener(this);
            table.addMouseMotionListener(this);
        private boolean canResize(TableColumn column){
            return column != null
                    && table.getTableHeader().getResizingAllowed()
                    && column.getResizable();
        private TableColumn getResizingColumn(Point p){
            return getResizingColumn(p, table.columnAtPoint(p));
        private TableColumn getResizingColumn(Point p, int column){
            if(column == -1){
                return null;
            int row = table.rowAtPoint(p);
            if(row==-1)
                return null;
            Rectangle r = table.getCellRect(row, column, true);
            r.grow( -3, 0);
            if(r.contains(p))
                return null;
            int midPoint = r.x + r.width / 2;
            int columnIndex;
            if(table.getTableHeader().getComponentOrientation().isLeftToRight())
                columnIndex = (p.x < midPoint) ? column - 1 : column;
            else
                columnIndex = (p.x < midPoint) ? column : column - 1;
            if(columnIndex == -1)
                return null;
            return table.getTableHeader().getColumnModel().getColumn(columnIndex);
        public void mousePressed(MouseEvent e){
            table.getTableHeader().setDraggedColumn(null);
            table.getTableHeader().setResizingColumn(null);
            table.getTableHeader().setDraggedDistance(0);
            Point p = e.getPoint();
            // First find which header cell was hit
            int index = table.columnAtPoint(p);
            if(index==-1)
                return;
            // The last 3 pixels + 3 pixels of next column are for resizing
            TableColumn resizingColumn = getResizingColumn(p, index);
            if(!canResize(resizingColumn))
                return;
            table.getTableHeader().setResizingColumn(resizingColumn);
            if(table.getTableHeader().getComponentOrientation().isLeftToRight())
                mouseXOffset = p.x - resizingColumn.getWidth();
            else
                mouseXOffset = p.x + resizingColumn.getWidth();
        private void swapCursor(){
            Cursor tmp = table.getCursor();
            table.setCursor(otherCursor);
            otherCursor = tmp;
        public void mouseMoved(MouseEvent e){
            if(canResize(getResizingColumn(e.getPoint()))
               != (table.getCursor() == resizeCursor)){
                swapCursor();
        public void mouseDragged(MouseEvent e){
            int mouseX = e.getX();
            TableColumn resizingColumn = table.getTableHeader().getResizingColumn();
            boolean headerLeftToRight =
                    table.getTableHeader().getComponentOrientation().isLeftToRight();
            if(resizingColumn != null){
                int oldWidth = resizingColumn.getWidth();
                int newWidth;
                if(headerLeftToRight){
                    newWidth = mouseX - mouseXOffset;
                } else{
                    newWidth = mouseXOffset - mouseX;
                resizingColumn.setWidth(newWidth);
                Container container;
                if((table.getTableHeader().getParent() == null)
                   || ((container = table.getTableHeader().getParent().getParent()) == null)
                                    || !(container instanceof JScrollPane)){
                    return;
                if(!container.getComponentOrientation().isLeftToRight()
                   && !headerLeftToRight){
                    if(table != null){
                        JViewport viewport = ((JScrollPane)container).getViewport();
                        int viewportWidth = viewport.getWidth();
                        int diff = newWidth - oldWidth;
                        int newHeaderWidth = table.getWidth() + diff;
                        /* Resize a table */
                        Dimension tableSize = table.getSize();
                        tableSize.width += diff;
                        table.setSize(tableSize);
                         * If this table is in AUTO_RESIZE_OFF mode and has a horizontal
                         * scrollbar, we need to update a view's position.
                        if((newHeaderWidth >= viewportWidth)
                           && (table.getAutoResizeMode() == JTable.AUTO_RESIZE_OFF)){
                            Point p = viewport.getViewPosition();
                            p.x =
                                    Math.max(0, Math.min(newHeaderWidth - viewportWidth, p.x + diff));
                            viewport.setViewPosition(p);
                            /* Update the original X offset value. */
                            mouseXOffset += diff;
        public void mouseReleased(MouseEvent e){
            table.getTableHeader().setResizingColumn(null);
            table.getTableHeader().setDraggedColumn(null);
    } This is TableRowResizer.java
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.MouseInputAdapter;
    import java.awt.*;
    import java.awt.event.MouseEvent;
    public class TableRowResizer extends MouseInputAdapter
        public static Cursor resizeCursor = Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR);
        private int mouseYOffset, resizingRow;
        private Cursor otherCursor = resizeCursor;
        private JTable table;
        public TableRowResizer(JTable table){
            this.table = table;
            table.addMouseListener(this);
            table.addMouseMotionListener(this);
        private int getResizingRow(Point p){
            return getResizingRow(p, table.rowAtPoint(p));
        private int getResizingRow(Point p, int row){
            if(row == -1){
                return -1;
            int col = table.columnAtPoint(p);
            if(col==-1)
                return -1;
            Rectangle r = table.getCellRect(row, col, true);
            r.grow(0, -3);
            if(r.contains(p))
                return -1;
            int midPoint = r.y + r.height / 2;
            int rowIndex = (p.y < midPoint) ? row - 1 : row;
            return rowIndex;
        public void mousePressed(MouseEvent e){
            Point p = e.getPoint();
            resizingRow = getResizingRow(p);
            mouseYOffset = p.y - table.getRowHeight(resizingRow);
        private void swapCursor(){
            Cursor tmp = table.getCursor();
            table.setCursor(otherCursor);
            otherCursor = tmp;
        public void mouseMoved(MouseEvent e){
            if((getResizingRow(e.getPoint())>=0)
               != (table.getCursor() == resizeCursor)){
                swapCursor();
        public void mouseDragged(MouseEvent e){
            int mouseY = e.getY();
            if(resizingRow >= 0){
                int newHeight = mouseY - mouseYOffset;
                if(newHeight > 0)
                    table.setRowHeight(resizingRow, newHeight);
    }

    cross-post: http://forum.java.sun.com/thread.jspa?forumID=57&threadID=755250

  • JTable Problems - JDK 1.2.2_05a & JDK 1.3.0

    Hi,
    I have a JTable program that works in JDK 1.2.2_05a but it no longer works when I run the 1.2.2 compiled version in a 1.3.0 environment or compiled and run in a 1.3.0 environment. The problem is that the JTable doesn't accept any keyboard inputs. Is there a known issue about this? If not, has anyone else run into this problem before? Any help is greatly appreciated. Many Thanks In Advance!
    Juivette

    I too face a similar problem. I had a JTable code which worked perfectly in 1.3.0. But when I recompiled it in 1.2.2_09 and ran it., I get square boxes when I try to set value to a cell.
    I think., the square box is the Enter Key I press for setting value. Has any one faced this problem before ?
    and suggest how to overcome ??
    regards
    Sriram

  • JTable problem in master detail form

    I've created a master detail form. There is only one Navigation bar for both master and detail. Detail has a JTable component. JTable doesn't get focus when it doesn't have any row and I am uanble to insert new rows. To cope with this problem I've added two new buttons in Navigation Bar to travers to the next and previous iterBinding.
    When I start my form cursor apperas in the first field of master view when I press Next Button nothing happens ( Status Bar should show the next iterbinding/view). I've addes some debug mesgs in iterBindingChanged method of NavitaionBar class and it seems by looking the mesgs that detail/Jtable's iterBinding get focus two times but at last focus has been returned to the master iterBinding.
    Is there any suggestion to solve this problem.
    Regards
    Aamir

    Hi,
    I'm using 1.4.0 for my JClient and, due to the improved focus management provided in the new JDK, I am able to properly manage master-details configuration with only one navigation bar (of course, the JTable must be able to receive the focus, but this also is much easier in 1.4.0...)
    Nevertheless, the solution I found is quite complex and I would happily discard it.
    If you could find a solution that works "naturally" on frames with only one navigation bar, it would be great! I think that the buttons in the nav bar should apply to the "current" iterator binding (the iterator binding for the control having the focus).
    Thanks,
    Adrian

  • JTable problem - cannot edit the cells (only happens in Linux)

    I have a JFrame that contains a JScrollPane, and this JScrollPane contains a JTable, the code is:aPanel = new JScrollPane(myTable);The program is done, runs fine in PC & Unix, but when I run it in Linux the problem occurs. Somehow I just cannot type anything into the cells. There is a workaround, if I minimize and later restore the Frame, then I can start type the cells.
    I run out ideas what to do. Is this a bug in Java itself? Anybody has any idea why this happens or suggestions what I should do?
    Thanks,
    shyo

    Hi,
    This very well could be a bug in Java's focus system (by the way, what version are you using?). Another possibility is that this could be a threading issue. Can you try and see if this works? Re-write the main method of your application like this so that all GUI construction happens on the event dispatch thread:
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
    private createAndShowGUI() {
        // move construction of GUI and
        // pack(), setVisible(), etc. here.
    }Does that help?
    Shannon Hickey (Swing Team)

  • Jtable problem in changing the row selected

    hi,
    I am displaying the oracle database information in JTable...user can make changes to a row...once he presses either ENTER,UP OR DOWN ARROW...the changes should be updated into the database...if there is some SQL exception,i am displaying JOptionPane to show the exception message ...i need to keep the selected row to be the one with errors...
    my problems are:
    i have written a function to update the change to the database...
    when should i call that...right now i am calling that in tableChanged method... is there any method to dissable the predefined keys and actions? becaz once user makes changes to a row and presses some key like up/down or enter,the control is getting transfered to the next row...
    plz give me the solution...
    here is part of my code....
    I am adding data later....
         model= new DefaultTableModel((Vector)null,columnNames);
         table = new JTable(model)
         public void tableChanged(TableModelEvent e)
              int firstRow = e.getFirstRow();
         if (e.getType()==TableModelEvent.UPDATE &&(firstRow!=TableModelEvent.HEADER_ROW))
              updateChangesToDatabase(row);
    /********in my update method i am setting the focus to the same row
    if i get exception....like this....
    JOptionPane.showMessageDialog (thisPanel,sb,"Error in UPDATING...",JOptionPane.ERROR_MESSAGE);
    table.requestFocusInWindow();
    table.setRowSelectionInterval(currentRow,currentRow);
         super.tableChanged(e);
              setUpTableData(); // method to add data...to table..
              table.setDragEnabled(false);
              table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              JScrollPane scrollPane = new JScrollPane(table,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              add(scrollPane,BorderLayout.CENTER);
    // this i am doing to reset keyboard action but not working....
              table.resetKeyboardActions();

    ye rammohan,
    you can change the data-element of the field or char of the data-element.
    if you try to change the name of the field, it deletes.
    so what you can do is, keep the field unchanged, add another field of your choice, using ABAP program, move the data from old field to new field, and then you can delete your old field.
    thx
    rams

  • Printing JTable problem

    hi
    i have a problem in printing jtable
    after printing the box around the table only printed and the content of the table isn't
    instead there is a wight space in the box
    can any one help me

    In fact the program i'm making is for printing preview
    it's three classes i found in one of the topics , then i modified them to preview a table
    here is my code : \\ the class "TPrintPreview" needs a JTable object as an argument
    ********************************TPrintPreview.java************************************************************
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Cursor;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.image.BufferedImage;
    import java.awt.print.PageFormat;
    import java.awt.print.Paper;
    import java.awt.print.Printable;
    import java.awt.print.PrinterException;
    import java.awt.print.PrinterJob;
    import java.text.MessageFormat;
    import javax.swing.JTable;
    import javax.swing.JTable.PrintMode;
    * @author  TAREQ145
    public class TPrintPreview extends javax.swing.JFrame {
       int m_wPage;
       int m_hPage;
        /** Creates new form TPrintPreview */
        public TPrintPreview(JTable table) {
            initComponents();
            PageFormat m_pageFormat = PrinterJob.getPrinterJob().defaultPage();//use PageDialog
            m_wPage = (int)(m_pageFormat.getWidth());
            m_hPage = (int)(m_pageFormat.getHeight());
            int scale = getScale(5);  //Scale Index = 100
            jComboBox1.setSelectedIndex(5);
            int w = (int)(m_wPage*scale/100);
            int h = (int)(m_hPage*scale/100);   
            int pageIndex = 0;
            try{
            while (true) {
                int theFirstImageWidth = table.getColumnModel().getTotalColumnWidth()+1;
                BufferedImage img = new BufferedImage(theFirstImageWidth, theFirstImageWidth+180, BufferedImage.TYPE_INT_RGB); 
                Graphics g = img.getGraphics();
                g.setColor(Color.white);
                g.fillRect(0, 0, theFirstImageWidth , theFirstImageWidth+180);//180 = height - width
                Paper p = new Paper();
                p.setImageableArea(0,0,theFirstImageWidth,theFirstImageWidth+180);
                m_pageFormat.setPaper(p);
                Printable  m_target = table.getPrintable(PrintMode.FIT_WIDTH,null,new MessageFormat("- {0} -"));
               if (m_target.print(g, m_pageFormat, pageIndex) != Printable.PAGE_EXISTS) {
                   img = null;
                   break;
                int rightOrLeftSpace = 25;
                int upOrDownSpace = 25;
                int theSecondImageWidth = theFirstImageWidth + (rightOrLeftSpace*2);
                BufferedImage img2 = new BufferedImage(theSecondImageWidth, theSecondImageWidth+180, BufferedImage.TYPE_INT_RGB); 
                Graphics g2 = img2.getGraphics();
                g2.setColor(Color.white);
                g2.fillRect(0, 0, theSecondImageWidth, theSecondImageWidth+180);
                g2.drawImage(img,rightOrLeftSpace,upOrDownSpace,null); 
                Image img3 = img2.getScaledInstance(m_wPage,m_hPage,Image.SCALE_SMOOTH);
                PagePreview pp = new PagePreview(w, h, img3);
                previewContainer1.add(pp);
                //pp = null;
                pageIndex++;
                img = null;
                g = null;
            } catch (PrinterException e)   {
              e.printStackTrace();
             System.err.println("Printing error: "+e.toString());
        /** 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.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
            jLabel1 = new javax.swing.JLabel();
            jScrollPane1 = new javax.swing.JScrollPane();
            previewContainer1 = new PreviewContainer();
            jButton1 = new javax.swing.JButton();
            jComboBox1 = new javax.swing.JComboBox();
            setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
            setTitle("Print Preview");
            jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24));
            jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            jLabel1.setText("Print Preview");
            jLabel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
            javax.swing.GroupLayout previewContainer1Layout = new javax.swing.GroupLayout(previewContainer1);
            previewContainer1.setLayout(previewContainer1Layout);
            previewContainer1Layout.setHorizontalGroup(
                previewContainer1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 752, Short.MAX_VALUE)
            previewContainer1Layout.setVerticalGroup(
                previewContainer1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 511, Short.MAX_VALUE)
            jScrollPane1.setViewportView(previewContainer1);
            jButton1.setText("EXIT");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "10 %", "25 %", "30 %", "50 %", "75 %", "100 %", "125 %", "150 %", "175 %", "200 %" }));
            jComboBox1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jComboBox1ActionPerformed(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)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 754, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 754, Short.MAX_VALUE))
                            .addContainerGap())
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(183, 183, 183)
                            .addComponent(jButton1)
                            .addGap(74, 74, 74))))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 513, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(40, 40, 40)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jButton1)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addContainerGap(80, Short.MAX_VALUE))
            pack();
        }// </editor-fold>                       
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
            this.dispose();
        private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {                                          
            int scale = getScale(jComboBox1.getSelectedIndex());
                      int w = (int)(m_wPage*scale/100);
                      int h = (int)(m_hPage*scale/100);
                      Component[] comps = previewContainer1.getComponents();
                      for (int k=0; k<comps.length; k++) {
                         if (!(comps[k] instanceof PagePreview)) continue;
                         PagePreview pp = (PagePreview)comps[k];
                         pp.setScaledSize(w, h);
                      previewContainer1.doLayout();
                      getContentPane().validate();
        private int getScale(int scaleIndex) {
          int scale = 10;
          String[] scales = { "10 %", "25 %", "30 %", "50 %", "75 %", "100 %" , "125 %","150 %","175 %","200 %"};
          if (scaleIndex>-1 && scaleIndex<scales.length) {
             String str = scales[scaleIndex];
             if (str.endsWith("%"))str = str.substring(0, str.length()-1);
             str = str.trim();
             try { scale = Integer.parseInt(str); }
             catch (NumberFormatException ex) { ex.printStackTrace();}
          return scale;
        // Variables declaration - do not modify                    
        private javax.swing.JButton jButton1;
        private javax.swing.JComboBox jComboBox1;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JScrollPane jScrollPane1;
        private PreviewContainer previewContainer1;
        // End of variables declaration                  
    ********************************PreviewContainer.java************************************************************
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Insets;
    import javax.swing.JPanel;
    * PreviewContainer.java
    * Created on 04 &#1603;&#1575;&#1606;&#1608;&#1606; &#1575;&#1604;&#1579;&#1575;&#1606;&#1610;, 2008, 10:20 &#1605;
    * @author  TAREQ145
    public class PreviewContainer extends JPanel {
        protected int H_GAP = 16;
        protected int V_GAP = 10;
        /** Creates new form BeanForm */
        public PreviewContainer() {
            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.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
        }// </editor-fold>                       
          public Dimension getPreferredSize() {
             int n = getComponentCount();
             if (n == 0) return new Dimension(H_GAP, V_GAP);
             Component comp = getComponent(0);
             Dimension dc = comp.getPreferredSize();
             Dimension dp = getParent().getSize();
             int nCol = Math.max((dp.width - H_GAP) / (dc.width + H_GAP), 1);
             int nRow = n / nCol;
             if ((nRow * nCol) < n) nRow++;
             int ww = nCol * (dc.width + H_GAP) + H_GAP;
             int hh = nRow * (dc.height + V_GAP) + V_GAP;
             Insets ins = getInsets();
             return new Dimension(ww+ins.left+ins.right, hh+ins.top+ins.bottom);
          public Dimension getMaximumSize() {
             return getPreferredSize();
          public Dimension getMinimumSize() {
             return getPreferredSize();
          public void doLayout() {
             Insets ins = getInsets();
             int x = ins.left + H_GAP;
             int y = ins.top + V_GAP;
             int n = getComponentCount();
             if (n == 0) return;
             Component comp = getComponent(0);
             Dimension dc = comp.getPreferredSize();
             int w = dc.width;
             int h = dc.height;
    //fl+ 03.09.2003
             if (getParent() == null) return;
    //fl-        
             Dimension dp = getParent().getSize();
             int nCol = Math.max((dp.width-H_GAP)/(w+H_GAP), 1);
             int nRow = n/nCol;
             if (nRow*nCol < n) nRow++;
             int index = 0;
             for (int k = 0; k<nRow; k++) {
                for (int m = 0; m<nCol; m++) {
                   if (index >= n) return;
                   comp = getComponent(index++);
                   comp.setBounds(x, y, w, h);
                   x += w+H_GAP;
                y += h+V_GAP;
                x = ins.left + H_GAP;
        // Variables declaration - do not modify                    
        // End of variables declaration                  
    ******************************PagePreview.java***********************************************************************************
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.Insets;
    import javax.swing.JPanel;
    * PagePreview.java
    * Created on 04 &#1603;&#1575;&#1606;&#1608;&#1606; &#1575;&#1604;&#1579;&#1575;&#1606;&#1610;, 2008, 10:25 &#1605;
    import javax.swing.border.MatteBorder;
    * @author  TAREQ145
    public class PagePreview extends JPanel {
         protected int m_w;
         protected int m_h;
         protected Image m_source;
         protected Image m_img;
        /** Creates new form BeanForm */
        public PagePreview() {
            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.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
        }// </editor-fold>                       
        public PagePreview(int w, int h, Image source) {
             m_w = w;
             m_h = h;
             m_source = source;
             m_img = m_source.getScaledInstance(m_w, m_h, Image.SCALE_SMOOTH);
             m_img.flush();
             setBackground(Color.white);
             setBorder(new MatteBorder(1, 1, 2, 2, Color.black));
          public void setScaledSize(int w, int h) {
             m_w = w;
             m_h = h;
             m_img = m_source.getScaledInstance(m_w, m_h, Image.SCALE_SMOOTH);
             repaint();
          public Dimension getPreferredSize() {
             Insets ins = getInsets();
             return new Dimension(m_w+ins.left+ins.right,
                m_h+ins.top+ins.bottom);
          public Dimension getMaximumSize() {
             return getPreferredSize();
          public Dimension getMinimumSize() {
             return getPreferredSize();
          public void paint(Graphics g) {
             g.setColor(getBackground());
             g.fillRect(0, 0, getWidth(), getHeight());
             g.drawImage(m_img, 0, 0, this);
             paintBorder(g);
        // Variables declaration - do not modify                    
        // End of variables declaration                  
    }please help me
    thankz

  • JTable problem : how to get the last value entered by user + event lost

    Hi all,
    I have 2 problems with Jtable class.
    1 => To get the last value entered by user in a cell,
    it seems that we must change the selected cell.
    That is to say we can only have the previous cell's value.
    Is there a simple way to get the current value of any cell ?
    2 => To resolve the problem i store the values of each cell in a vector and i intercept keyboard event (!)
    BUT, when i do a double click with the mouse on the Jtable, i loose keyboard events. Then, i can't intercept them.
    Is it a bug of swing or am i following a wrong way ?
    Thanks by anticipation for your help.

    You have to fire the "TableCellUpdatedEvent"
    and override the getCellEditorValue in TableCellEditor to return the current value

  • Need help .. JTable problem!!!!!

    Is there any way to provide drag n drop feature within Jtable cells ....
    What I want to do is that ... I shud be able to drag a JTable cell to another JTable cell and the values of those two cell should interchange ....
    Is this even possible ??? Please help me as I m new to Java
    Thanx alot....

    Plus I have one more problem the column headers arnt appearing ..... So please help me ..... I need two things to be done ....
    1) Populate the tables using vectors, so that only that no of rows appear which are in table of my database ..
    2) Column headers shud show up...
    Here's my code ...
    * Drag.java
    package test;
    import javax.swing.*;
    import java.awt.Dimension;
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.datatransfer.*;
    import java.awt.dnd.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import java.util.*;
    public class Drag extends javax.swing.JFrame {
         private String url = "jdbc:odbc:FAMS";
        private Connection con;
        private Statement stmt;
        private Map<String, Color> colormap = new HashMap<String, Color>();
        public void populate()
        try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            } catch(java.lang.ClassNotFoundException e) {
                System.err.print("ClassNotFoundException: ");
                System.err.println(e.getMessage());
               String query = "SELECT * FROM SubAllot";
            /* First clear the JTable */
            clearTable();
            /* get a handle for the JTable */
            javax.swing.table.TableModel model = table.getModel();
            int r = 0;
            try {
                /* connect to the database */
                con = DriverManager.getConnection(url, "", "");
                stmt = con.createStatement();
                /* run the Query getting the results into rs */
                   ResultSet rs = stmt.executeQuery(query);
                   while ((rs.next()) ) {
                        /* for each row get the fields
                           note the use of Object - necessary
                           to put the values into the JTable */
                       Object nm = rs.getObject(1);
                       Object sup = rs.getObject(2);
                       Object pri = rs.getObject(3);
                       Object sal = rs.getObject(4);
                       Object tot = rs.getObject(5);
                       model.setValueAt(nm, r, 0);
                       model.setValueAt(sup, r, 1);
                       model.setValueAt(pri, r, 2);
                       model.setValueAt(sal, r, 3);
                       model.setValueAt(tot, r, 4);
                       r++;
                stmt.close();
                con.close();
            } catch(SQLException ex) {
                System.err.println("SQLException: " + ex.getMessage());
           private void clearTable(){
            int numRows = table.getRowCount();
            int numCols = table.getColumnCount();
            javax.swing.table.TableModel model = table.getModel();
            for (int i=0; i < numRows; i++) {
                for (int j=0; j < numCols; j++) {
                    model.setValueAt(null, i, j);
              private void writeTable(){
             /* First clear the table */
             emptyTable();
             Statement insertRow;// = con.prepareStatement(
             String baseString = "INSERT INTO SubAllot " +
                                        "VALUES ('";
             String insertString;
            int numRows = table.getRowCount();
            javax.swing.table.TableModel model = table.getModel();
           /* Integer sup, sal, tot;
            Double pri;
            Object o;
            try {
                /* connect to the database */
                con = DriverManager.getConnection(url, "", "");
                 for (int r=0; r < numRows; r++) {
                      if (model.getValueAt(r, 0) != null){
                           insertString = baseString + model.getValueAt(r, 0)+"','";
                           insertString = insertString + model.getValueAt(r, 1)+"','";
                           insertString = insertString + model.getValueAt(r, 2)+"','";
                           insertString = insertString + model.getValueAt(r, 3)+"','";
                           insertString = insertString + model.getValueAt(r, 4)+"');";
                           System.out.println(insertString);
                          insertRow = con.createStatement();
                           insertRow.executeUpdate(insertString);
                           System.out.println("Writing Row " + r);
                insertRow.close();
                con.close();
            } catch(SQLException ex) {
                System.err.println("SQLException: " + ex.getMessage());
           // clearTable();
           private void emptyTable(){
             /* Define the SQL Query to get all data from the database table */
            String query = "DELETE * FROM SubAllot";
            try {
                /* connect to the database */
                con = DriverManager.getConnection(url, "", "");
                stmt = con.createStatement();
                /* run the Query */
                   stmt.executeUpdate(query);
                stmt.close();
                con.close();
            } catch(SQLException ex) {
                System.err.println("SQLException: " + ex.getMessage());
               abstract class StringTransferHandler extends TransferHandler {
            public int dropAction;
            protected abstract String exportString(final JComponent c);
            protected abstract void importString(final JComponent c, final String str);
            @Override
            protected Transferable createTransferable(final JComponent c) {
                return new StringSelection(exportString(c));
            @Override
            public int getSourceActions(final JComponent c) {
                return MOVE;
            @Override
            public boolean importData(final JComponent c, final Transferable t) {
                if (canImport(c, t.getTransferDataFlavors())) {
                    try {
                        String str = (String) t.getTransferData(DataFlavor.stringFlavor);
                        importString(c, str);
                        return true;
                    } catch (UnsupportedFlavorException ufe) {
                    } catch (IOException ioe) {
                return false;
            @Override
            public boolean canImport(final JComponent c, final DataFlavor[] flavors) {
                for (int ndx = 0; ndx < flavors.length; ndx++) {
                    if (DataFlavor.stringFlavor.equals(flavors[ndx])) {
                        return true;
                return false;
        class TableTransferHandler extends StringTransferHandler {
            private int dragRow;
            private int[] dragColumns;
            private BufferedImage[] image;
            private int row;
            private int[] columns;
            public JTable target;
            private Map<String, Color> colormap;
            private TableTransferHandler(final Map<String, Color> colormap) {
                this.colormap = colormap;
            @Override
            protected Transferable createTransferable(final JComponent c) {
                JTable table = (JTable) c;
                dragRow = table.getSelectedRow();
                dragColumns = table.getSelectedColumns();
                createDragImage(table);
                return new StringSelection(exportString(c));
            protected String exportString(final JComponent c) {
                JTable table = (JTable) c;
                row = table.getSelectedRow();
                columns = table.getSelectedColumns();
                StringBuffer buff = new StringBuffer();
                colormap.clear();
                for (int j = 0; j < columns.length; j++) {
                    Object val = table.getValueAt(row, columns[j]);
                    buff.append(val == null ? "" : val.toString());
                    if (j != columns.length - 1) {
                        buff.append(",");
                    colormap.put(row+","+columns[j], Color.LIGHT_GRAY);
                table.repaint();
                return buff.toString();
            protected void importString(final JComponent c, final String str) {
                target = (JTable) c;
                DefaultTableModel model = (DefaultTableModel) target.getModel();
                String[] values = str.split("\n");
                int colCount = target.getSelectedColumn();
                int max = target.getColumnCount();
                for (int ndx = 0; ndx < values.length; ndx++) {
                    String[] data = values[ndx].split(",");
                    for (int i = 0; i < data.length; i++) {
                        String string = data;
    if(colCount < max){
    String val = (String) model.getValueAt(target.getSelectedRow(), colCount);
    model.setValueAt(string, target.getSelectedRow(), colCount);
    model.setValueAt(val, dragRow, dragColumns[i]);
    colCount++;
    public BufferedImage[] getDragImage() {
    return image;
    private void createDragImage(final JTable table) {
    if (dragColumns != null) {
    try {
    image = new BufferedImage[dragColumns.length];
    for (int i = 0; i < dragColumns.length; i++) {
    Rectangle cellBounds = table.getCellRect(dragRow, i, true);
    TableCellRenderer r = table.getCellRenderer(dragRow, i);
    DefaultTableModel m = (DefaultTableModel) table.getModel();
    JComponent lbl = (JComponent) r.getTableCellRendererComponent(table,
    table.getValueAt(dragRow, dragColumns[i]), false, false, dragRow, i);
    lbl.setBounds(cellBounds);
    BufferedImage img = new BufferedImage(lbl.getWidth(), lbl.getHeight(),
    BufferedImage.TYPE_INT_ARGB_PRE);
    Graphics2D graphics = img.createGraphics();
    graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f));
    lbl.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
    lbl.paint(graphics);
    graphics.dispose();
    image[i] = img;
    } catch (RuntimeException re) {
    class TableDropTarget extends DropTarget {
    private Insets autoscrollInsets = new Insets(20, 20, 20, 20);
    private Rectangle rect2D = new Rectangle();
    private TableTransferHandler handler;
    public TableDropTarget(final TableTransferHandler h) {
    super();
    this.handler = h;
    @Override
    public void dragOver(final DropTargetDragEvent dtde) {
    handler.dropAction = dtde.getDropAction();
    JTable table = (JTable) dtde.getDropTargetContext().getComponent();
    Point location = dtde.getLocation();
    int row = table.rowAtPoint(location);
    int column = table.columnAtPoint(location);
    table.changeSelection(row, column, false, false);
    paintImage(table, location);
    autoscroll(table, location);
    super.dragOver(dtde);
    public void dragExit(final DropTargetDragEvent dtde) {
    clearImage((JTable) dtde.getDropTargetContext().getComponent());
    super.dragExit(dtde);
    @Override
    public void drop(final DropTargetDropEvent dtde) {
    Transferable data = dtde.getTransferable();
    JTable table = (JTable) dtde.getDropTargetContext().getComponent();
    clearImage(table);
    handler.importData(table, data);
    super.drop(dtde);
    private final void paintImage(final JTable table, final Point location) {
    Point pt = new Point(location);
    BufferedImage[] image = handler.getDragImage();
    if (image != null) {
    table.paintImmediately(rect2D.getBounds());
    rect2D.setLocation(pt.x - 15, pt.y - 15);
    int wRect2D = 0;
    int hRect2D = 0;
    for (int i = 0; i < image.length; i++) {
    table.getGraphics().drawImage(image[i], pt.x - 15, pt.y - 15, table);
    pt.x += image[i].getWidth();
    if (hRect2D < image[i].getHeight()) {
    hRect2D = image[i].getHeight();
    wRect2D += image[i].getWidth();
    rect2D.setSize(wRect2D, hRect2D);
    private final void clearImage(final JTable table) {
    table.paintImmediately(rect2D.getBounds());
    private Insets getAutoscrollInsets() {
    return autoscrollInsets;
    private void autoscroll(final JTable table, final Point cursorLocation) {
    Insets insets = getAutoscrollInsets();
    Rectangle outer = table.getVisibleRect();
    Rectangle inner = new Rectangle(outer.x + insets.left,
    outer.y + insets.top,
    outer.width - (insets.left + insets.right),
    outer.height - (insets.top + insets.bottom));
    if (!inner.contains(cursorLocation)) {
    Rectangle scrollRect = new Rectangle(cursorLocation.x - insets.left,
    cursorLocation.y - insets.top,
    insets.left + insets.right,
    insets.top + insets.bottom);
    table.scrollRectToVisible(scrollRect);
    /** Creates new form Drag */
    public Drag() {
    initComponents();
    populate();
    /** 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.
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
    jScrollPane1 = new javax.swing.JScrollPane();
    table = new javax.swing.JTable();
    jButton1 = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    table.setModel(new javax.swing.table.DefaultTableModel(
    new Object [][] {
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, null},
    {null, null, null, null, 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", "Title 5"
    Class[] types = new Class [] {
    java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
    public Class getColumnClass(int columnIndex) {
    return types [columnIndex];
    jScrollPane1.setViewportView(table);
    table.getTableHeader().setReorderingAllowed(false);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.setCellSelectionEnabled(true);
    table.setRowHeight(23);
    table.setDragEnabled(true);
    TableTransferHandler th = new TableTransferHandler(colormap);
    table.setTransferHandler(th);
    table.setDropTarget(new TableDropTarget(th));
    table.setTableHeader(null);
    jButton1.setText("UPDATE");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton1ActionPerformed(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()
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGap(18, 18, 18)
    .addComponent(jButton1)
    .addContainerGap(15, Short.MAX_VALUE))
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 348, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(layout.createSequentialGroup()
    .addGap(80, 80, 80)
    .addComponent(jButton1)))
    .addContainerGap(14, Short.MAX_VALUE))
    pack();
    }// </editor-fold>
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    writeTable(); // TODO add your handling code here:
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new Drag().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable table;
    // End of variables declaration
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      

  • Big JTable-Problem

    Hello,
    I've got a rather big problem with a JTable-object: I've got a 2-dimensional array called data which contains the data for my JTable. Now the array changes and I want my Table two show the new data. So I removed my old JTable from the Panel and created a new JTable, which is being added to the Panel. This works quite fine, but now there occurs a problem: I want to give a selection to my JTable (the first row shall be selected) by using the method
    JTableXY.changeSelection(0,0,false,false)
    The row is selected, but navigating with keys (up- down-arrows) in the Table doesn't work anymore. As soon as I click on another entry navigating with keys works again. How can I resolve this problem ? I guess it's got sth. to do with the Focus, but I tried everything to give the Focus to my Table but it didn't work.
    I'd be really glad if somebody could help me..thanx,
    Findus

    Try to change the Table MODEL and not JTABLE
    More about Table Models in "Java Tutorial - how to use JTable"
    I have good expirience whith changing the Table Models Data. After the Change a "fireTableDataChanged" is nessesary - thats all.

  • Please Help.....Swing(jtable) problem

    Hi,In one application i want to show the data of database into jtable.The requirement is like this ..the date in database keep on updating and i want the jtable to keep on refreshing so to show the updated data.I hope am clear with my problem.
    Pls help me out
    Thanx
    Your Friend

    Here ya go, hope I didn't just do your homework for you :-)
    import java.awt.*;
    import java.awt.event.*;
    import java.text.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class TimeTable extends JFrame
         static public void main(String [] args)
              TimeTable timeTable = new TimeTable();
              timeTable.setBounds(100, 100, 500, 200);
              timeTable.setVisible(true);
              timeTable.addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        ((TimeTable) e.getSource()).setVisible(false);
                        ((TimeTable) e.getSource()).dispose();
                        System.exit(0);
         TimeRunnable runnable = null;
         public TimeTable()
              JTable jTable = new JTable(5, 5);
              getContentPane().add(new JScrollPane(jTable));
              runnable = new TimeRunnable(jTable, 3, 3);
         public void addNotify()
              super.addNotify();
              new Thread(runnable).start();
    class TimeRunnable implements Runnable
         private JTable jTable = null;
         private int x = -1, y = -1;
         public TimeRunnable(JTable _jTable, int _x, int _y)
              jTable = _jTable;
              x = _x;
              y = _y;
         public void run()
              boolean okay = true;
              SimpleDateFormat format = new SimpleDateFormat("H:mm:ss:SSS");
              while (okay)
                   try
                        jTable.setValueAt(format.format(new Date()), x, y);
                        Thread.sleep(2000);
                   catch (InterruptedException e)
                        okay = false;

  • JTable problem.  Two JTables sharing one Selection Listener.

    So heres my problem. Any help would be much appreciated.
    I have two JTables each displayed inside a JSplitPane. If table A has a row selected and the user selects a row from table B, I want table A to become deselected. I want the two tables to act as one. Only one rwo from either of the tables can be selected at a time.
    I currently have two different table models for the tables but the data is coming from the same source. It is just grouped into two categories so I divided them up into two different tables in a splitpane. Thanks for your help.

    Hi,
    You have to use the clearSelection() m�thode on the ListSelectionModel of your JTable
    tableA.addMouseListener(new MouseAdapter(){
              public void mouseClicked(MouseEvent e_) {                    
                   tableB.getSelectionModel().clearSelection();
    });

  • 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.

  • JTable problem pls help!!!!!!

    Is it possible to place sub-columns in a single Jtable columns ??? I want to place three subcolumns under a single Column
    Please tell me if it can be done...
    Will it retrieve data from database as the simple Jtable does or is there some other method?? If there is please tell me that also
    Thanks

    may be you mean something like this http://www.codeguru.com/java/articles/125.shtml or just the other way around? You could have a cell renderer that is a JPanel with a i.e a Layout etc etc . Hope that might help you.
    Andr'e

Maybe you are looking for

  • ITunes 10 - Mutliple Accounts no longer working on ATV

    Just when I thought upgrading to Itunes 10 was a breeze... In my house we have 3 Apple TV's. My wife and two kids each have their own iTunes accounts. We often play each others music or watch each others shows or movies and simply authorise all 4 com

  • Unusual problem with Photoshop Elements 10

    When using Photoshop Elements 10 on my computer I find it to be very difficult to move the "box" around on my desktop. I have to click on it many time in order to get it to move.

  • DCOM errors ID: 10010

    Hello, I was checking on my "event viewer" and I found tons of errors DCOM related, all of them have as the event id: 10010. Checking for details is not only related to one application only but several: The server App.AppX54xz6wnkhmw763c2y8tb018n7d71

  • Customer Master - Debit Notification Preferences

    In the Customer master, on the Payment Details tab, there is a section at the bottom called "Debit Notification Preferences", under which I can choose a delivery method (email, fax, printed) and then enter the corresponding information (email address

  • RSQL ERROR 23 WHEN ACCESSING TABLE "BKPF"

    Can you tell me what is wrong with this statement.  I get an ABAP runtime error. DBIF_RSQL_INVALID_RSQL. RSQL ERROR 23 WHEN ACCESSING TABLE "BKPF" START-OF-SELECTION.   SELECT BUDAT BLDAT BLART XBLNR_ALT BKTXT XSNET WAERS FROM BKPF INTO   IT_BKPF