New jTable problem.. HELP..

I have the following function of new jTable is being created but it doesn't work:
public void setTable1(){
    /* Renew table component*/
    jTable1 = new JTable(rs.AttSize,2);
    /* Put jTable into JScrollPane and then into jPanel2 */
    JScrollPane scrollpane = new JScrollPane(jTable1);
    TableColumn column = null;
    column = jTable1.getColumnModel().getColumn(0);
    column.setHeaderValue("No");
    column = jTable1.getColumnModel().getColumn(1);
    column.setPreferredWidth(400);
    column.setHeaderValue("Attribute Name");
    jPanel2.add(scrollpane);
    jPanel2.validate();
}How can I remove previous jTable1? and add new jTable into jPanel, my code doesn't show up the new jTable1.. I'm dying to code rite now.. Please help me...

Bingoo.. I'm alive again.. found this link:
http://forum.java.sun.com/thread.jsp?thread=194107&forum=57&message=635591
from Author: lalo79. Thanks...
and my function suppose to be like:
protected void setTable1(){
    /* new jTable1 component to jPanel2 */
    jTable1 = new JTable(model);
    TableColumn column = null;
    column = jTable1.getColumnModel().getColumn(1);
    column.setPreferredWidth(400);  
    scrollpane = new JScrollPane(jTable1);
    jPanel2.add(scrollpane);
    /* Remove all row for inserting new value */
    while (jTable1.getRowCount() > 0)
      ((DefaultTableModel)jTable1.getModel()).removeRow(0);
    /* put value to the new row */
    for(int i=0;i<rs.AttSize;i++){
      model.addRow(new Object[] {String.valueOf(i+1),rs.ArrayAtts[0]});
jPanel2.updateUI();
jPanel2.validate();
come back to work again..

Similar Messages

  • Was just loading indesign and cannot start it. seem to have no rights for some presets. i deinstalled and installed new, same problem. help!

    was just loading indesign and cannot start it. seem to have no rights for some presets. i deinstalled and installed new, same problem. who can help?

    Not easy if vital information is missing. Sometimes it seems like people are using the internet the first time...
    What version of Indesign?
    What OS? "Rights" sounds like Windows
    What is happening when starting it?
    If Windows, where was it installed?
    If Windows, do you have admin permissions?

  • New syncing problem - HELP!

    Suddenly, I cannot sync my nano. Didn't have a problem before. Have turned firewall off and back on. iTunes works fine until I plug in to sync, and then it crashes. Message: "iTunes has stopped working" immediately appears when I try to sync. Very aggravating. BTW - have upgraded to the latest version of iTunes. Am using HP laptop using Vista Home. Thanks for any help.

    BTW - have upgraded to the latest version of iTunes.
    Let's doublecheck that. In iTunes, go "Help > About iTunes" and wait for the version number to scroll up from the bottom of the screen.
    Does it say 10.1.0.54 ? If so, we need to update you to 10.1.0.56 .
    10.1.0.56 won't appear for you in Apple Software Update for Windows if you already have 10.1.0.54 installed. So you'll need to get the installer from the Apple website as per the following document:
    [iTunes 10.1 for Windows: iTunes may stop working and need to quit while importing or syncing audio|http://support.apple.com/kb/TS3591]

  • Really tired with new itunes problems ( HELP)

    I have the newer verison of itunes and I am having issues... Most of the time I click the shortcut on the bottom of the lower left side of the screen and the pointer shows the program tring to open for a few seconds and nothing... In task manager it does not show the program to be working. I can go directly to the program ( not from the shortcut) and same problem. I have reinstalled the repair 3-4 times and nothing. When the program feels like working the program takes 45-60 seconds to open. The itunes folder is installed in ... "C:\Program Files\iTunes\iTunes.exe"
    328 k ram service pack 4

    The installations area might have more discussions along the lines of your problem -
    but here's something to check
    Paul Harvey3, "iTunes 6 installs but won't work?" #18, 05:19pm Oct 15, 2005 CDT

  • Downloading new itunes problem HELP !

    When i go to download iTunes 7.5 it goes through the download proccess and an error popup that says " This installation package could not be opened. Verify that the package exists and that you can access it, or contact the application vendor to verify that this is a valid Windows Installer package. " comes up . HELP !

    Hi MarRedd!
    Here is an article that will help you troubleshoot this issue:
    iTunes 11.1.4 for Windows: Unable to install or open
    http://support.apple.com/kb/TS5376
    Thanks for being a part of the Apple Support Communities!
    Cheers,
    Braden

  • Small Problem in JTable,Please help me..

    hi ,i am doing college project & hv some problem
    Problem : (code is given below ) as i run program ,i am not able to edit cells of table one by one.when i write value in any cell & then if i edit other cell, then previous cell's value become come to initial value
    This problem is requires small modification ,plz help(unless my project will not exceed further )
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    //import javax.swing.JScrollPane;
    //import javax.swing.JTable;
    import java.util.*;
    import java.util.List;
    public class v_swing1 extends JFrame
         {     JButton b1;
              Container cont;
              JTable table ;
              TableModel myData ;
              TextField t1;
              private LocalTableModel theTableModel;                         //t1.setEditable(false);
              private List<Row> theRows;
         private class Row {
              private int theFirstField;
              private String theSecondField;
              public Row(int aFirstField, String aSecondField) {
                   theFirstField = aFirstField;
                   theSecondField = aSecondField;
              public int getFirstField() {
                   return theFirstField;
              public String getSecondField() {
                   return theSecondField;
         private class LocalTableModel extends AbstractTableModel {
              public String getColumnName(int column) {
                   if (column == 0) {return "name";}
                   else      {  return "age";}     }
              public Class getColumnClass(int columnIndex) {
              if (columnIndex == 0) { return Integer.class;}
                   else      {   return String.class;   }
              public boolean isCellEditable(int rowIndex, int columnIndex) {
                   return true;     }
              public int getRowCount() {
                   return theRows.size();
              public int getColumnCount() {
                   return 2;
              public Object getValueAt(int rowIndex, int columnIndex) {
                   Row row = theRows.get(rowIndex);
                   if (columnIndex == 0) { return row.getFirstField();}
                   else { return row.getSecondField(); }
         public v_swing1(String theLable)
              b1=new JButton();
              t1=new TextField(4);
              theRows = new LinkedList<Row>();
              theTableModel = new LocalTableModel();           
              table = new JTable(theTableModel);
              setLayout(new FlowLayout());
              JPanel thePan=new JPanel();
              thePan.add(t1);
              thePan.add(b1);
              Container cont= getContentPane();
              cont.setLayout(new FlowLayout());
              cont.add(thePan);
              b1.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e)
                        load();
                        reload();
                             //x=Integer.parseInt(t1.getText());
                        //t1.setText(" ");          
                                            // table = new JTable(2,3);     
                                  //table.setRowSelectionAllowed(true);
                                  // table.setColumnSelectionAllowed(true);
                                  //table.setCellSelectionEnabled(true);
              cont.add(new JScrollPane(table));
              load();               
         private void reload(){
              int l =Integer.parseInt(t1.getText());
              for(int size = theRows.size();size<=l;size++)
              theRows.add(new Row(size, " "+size));
              theTableModel.fireTableRowsInserted(size, size);
         private void load(){
              int size = theRows.size();
              if (size > 0) {
                   theRows.clear();
                   theTableModel.fireTableRowsDeleted(0, size - 1);
              theRows.add(new Row(0, "" + 0));     
              theTableModel.fireTableRowsInserted(0, 1);
         public static void main(String args[])
              v_swing1 obj=new v_swing1("hay");
              obj.addWindowListener(new WindowAdapter(){
              public void windowClosing(WindowEvent e) {
              System.exit(0);
              obj.setSize(400,400);
              obj.setVisible(true);
         }

    Please cut and paste the exact message in a reply.
    Most likely, your CLASSPATH is wrong.
    Larry

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

  • 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

  • Problem in JTable,Kindly help very urgent

    I am trying to add /remove rows from JTable whose first column is JButton and others are JComboBox's.If no rows are selected,new row is added at the end.If user selects some row & then presses insert button,new row is added below it.Rows can only be deleted if user has made some selection.I am also using Icon for the button of currently active row.But i am getting exception(ArrayIndexBounds)when i try to add/delete.May be proper refreshing is not taking place.Kindly help me,where i am making mistake.If any function is to be used.My code is as follows....It is running code
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    import java.util.*;
    public class JButtonTableExample extends JFrame implements ActionListener,TableModelListener
    JComboBox mComboLHSType = new JComboBox();
    JComboBox mComboRHSType = new JComboBox();
    JLabel mLabelLHSType = new JLabel("LHS Type");
    JLabel mLabelRHSType = new JLabel("RHS Type");
    JButton mButtonDelete = new JButton("Delete");
    JButton mButtonInsert = new JButton("Insert");
    JButton check = new JButton("check");
    JPanel mPanelButton = new JPanel();
    JPanel mPanelScroll = new JPanel();
    JPanel mPanelCombo = new JPanel();
    DefaultTableModel dm ;
    TableColumnModel modelCol;
    JTable table;
    JScrollPane scroll;
    int currentRow = -1;
    static int mSelectedRow = -1;
    EachRowEditor rowEditor;
    public JButtonTableExample()
    super( "JButtonTable Example" );
    makeForm();
    setSize( 410, 222 );
    setVisible(true);
    private void makeForm()
         this.getContentPane().setLayout(null);
         mLabelLHSType.setBounds(new Rectangle(26,5,71,22));
         mComboLHSType.setBounds(new Rectangle(83,5,100,22));
         mLabelRHSType.setBounds(new Rectangle(232,5,71,22));
         mComboRHSType.setBounds(new Rectangle(292,5,100,22));
         mPanelCombo.setLayout(null);
         mPanelCombo.setBorder(new LineBorder(Color.red));
         mPanelCombo.setBounds(new Rectangle(1,1,400,30));
         mComboRHSType.addItem("Constant");
    mComboRHSType.addItem("Variable");
    mComboRHSType.setSelectedIndex(0);
    mComboRHSType.addActionListener(this);
    mPanelCombo.add(mLabelLHSType,null);
    mPanelCombo.add(mComboLHSType,null);
    mPanelCombo.add(mLabelRHSType,null);
    mPanelCombo.add(mComboRHSType,null);
         mPanelButton.setLayout(null);
         mPanelButton.setBorder(new LineBorder(Color.green));
         mPanelButton.setBounds(new Rectangle(1,165,400,30));
         mButtonInsert.setBounds(new Rectangle(120,5,71,22));
         mButtonDelete.setBounds(new Rectangle(202,5,71,22));
         mButtonDelete.addActionListener(this);
    mButtonInsert.addActionListener(this);
    check.setBounds(new Rectangle(3,3,71,22));
    check.addActionListener(this);
    mPanelButton.add(mButtonDelete,null);
    mPanelButton.add(mButtonInsert,null);
    mPanelButton.add(check,null);
         dm = new DefaultTableModel()
              public boolean isCellEditable(int row, int col)
              if(row == 0 && col ==1)
                   return false;
              return true;
         dm.addTableModelListener(this);
         //dm.setDataVector(null,
                             //new Object[]{"Button","Join","LHS","Operator","RHS"});
         dm.setDataVector(new Object[][]{{"","","","",""}},
                             new Object[]{"","Join","LHS","Operator","RHS"});
         table = new JTable(dm);
         table.getTableHeader().setReorderingAllowed(false);
         table.setRowHeight(25);
         table.setRowSelectionInterval(0,0);
         rowEditor = new EachRowEditor(table);
         int columnWidth[] = {20,45,95,95,95};
         mPanelScroll.setLayout(null);
         mPanelScroll.setBorder(new LineBorder(Color.blue));
         mPanelScroll.setBounds(new Rectangle(1,28,400,135));
         scroll = new JScrollPane(table);
    scroll.setBounds(new Rectangle(1,1,400,133));
    mPanelScroll.add(scroll,null);
         modelCol = table.getColumnModel();
         for (int i=0;i<5;i++)
         modelCol.getColumn(i).setPreferredWidth(columnWidth);
         setCellTypes();
    this.getContentPane().add(mPanelCombo,null);
    this.getContentPane().add(mPanelScroll,null);
    this.getContentPane().add(mPanelButton,null);
    }//end of makeForm()
    private void setCellTypes()
         modelCol.getColumn(0).setCellRenderer(new ButtonCR());
         modelCol.getColumn(0).setCellEditor(new ButtonCE(new JCheckBox()));
         modelCol.getColumn(0).setResizable(false);
         setUpJoinColumn(modelCol.getColumn(1));
         setUpLHSColumn(modelCol.getColumn(2));
         setUpOperColumn(modelCol.getColumn(3));
         setUpRHSColumn(modelCol.getColumn(4));//By Default contains JTextField
    public void actionPerformed(ActionEvent ae)
         if (ae.getSource() == mButtonInsert)
              int currentRow = table.getSelectedRow();
              if(currentRow == -1)
                   int rowCount = dm.getRowCount();
                   if(rowCount == 0)
                        table.clearSelection();
                        dm.insertRow(0,new Object[]{"","","","",""});
                        mComboRHSType.setEnabled(true);
                        mButtonDelete.setEnabled(true);
                        dm.fireTableDataChanged();
                        table.setRowSelectionInterval(0,0);
                   else
                        table.clearSelection();
                        dm.insertRow(rowCount,new Object[]{"","","","",""});
                        dm.fireTableDataChanged();
                        table.setRowSelectionInterval(rowCount,rowCount);
              else
                   table.clearSelection();
                   dm.insertRow(currentRow+1,new Object[]{"","","","",""});
                   dm.fireTableDataChanged();
                   table.setRowSelectionInterval(currentRow+1,currentRow+1);
    if(table.getRowCount()>0)
         table.setValueAt(new String(""),0,1);
         if(ae.getSource() == mButtonDelete)
    int currentRow = table.getSelectedRow();
    if(currentRow != -1)
    table.clearSelection();
                   dm.removeRow(currentRow);
                   if(dm.getRowCount() == 0)
                        mComboRHSType.setEnabled(false);
                        mButtonDelete.setEnabled(false);
                   dm.fireTableDataChanged();
              else
              JOptionPane.showMessageDialog(null, "Select row first", "alert", JOptionPane.ERROR_MESSAGE);
    //always the first cell is empty and disabled
    if(table.getRowCount()>0)
         table.setValueAt(new String(""),0,1);
         if(ae.getSource() == check)
              int r = table.getSelectedRow();
              for(int i=1;i<5;i++)
                   Object obj = table.getValueAt(r,i);
                   System.out.println("Value is"+obj.toString());
         if(ae.getSource()==mComboRHSType)
              System.out.println(mComboRHSType.getSelectedItem().toString());
              if(table.getSelectedRow() == -1)
                        JOptionPane.showMessageDialog(null, "Select row first", "alert", JOptionPane.ERROR_MESSAGE);
                        mComboRHSType.setSelectedIndex(0);
                   else
                        if((mComboRHSType.getSelectedItem().toString()).equalsIgnoreCase("Constant"))
                             rowEditor.stopCellEditing();
                             table.setValueAt("",table.getSelectedRow(),4);
                             rowEditor.setEditorAt(table.getSelectedRow(), new DefaultCellEditor(new JTextField()));
                             table.getColumn("RHS").setCellEditor(rowEditor);
                        else if((mComboRHSType.getSelectedItem().toString()).equalsIgnoreCase("Variable"))
                        JComboBox comboBox = new JComboBox();
                        comboBox.addItem("Variable1");
                        comboBox.addItem("Constant1");
                        comboBox.addItem("Constant2");
                        rowEditor.stopCellEditing();
                        table.setValueAt("",table.getSelectedRow(),4);
                        rowEditor.setEditorAt(table.getSelectedRow(), new DefaultCellEditor(comboBox));
                        table.getColumn("RHS").setCellEditor(rowEditor);
    }//end of actionPerformed()
    public void tableChanged(TableModelEvent e)
              if(e.getType()==e.DELETE)
                   System.out.println("DELETE CALEED called##################)");
              if(e.getType()==e.INSERT)
                   System.out.println("INSERT CALEED called##################)");
    public void setUpJoinColumn(TableColumn joinColumn)
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("AND");
    comboBox.addItem("OR");
    comboBox.addItem("NOT");
    joinColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    joinColumn.setCellRenderer(renderer);
    //Set up tool tip for the header.
    TableCellRenderer headerRenderer = joinColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer)
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText("Click to see list of Join Conditions");
    public void setUpLHSColumn(TableColumn LHSColumn)
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("Participant1");
    comboBox.addItem("Participant2");
    comboBox.addItem("Variable1");
    LHSColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    LHSColumn.setCellRenderer(renderer);
    //Set up tool tip for the header.
    TableCellRenderer headerRenderer = LHSColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer)
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText("Click the sport to see Participants or Variables");
    public void setUpOperColumn(TableColumn operColumn)
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("=");
    comboBox.addItem("!=");
    comboBox.addItem("Contains");
    operColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    operColumn.setCellRenderer(renderer);
    //Set up tool tip for header.
    TableCellRenderer headerRenderer = operColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer)
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click to see a list of operators");
    public void setUpRHSColumn(TableColumn rhsColumn)
              rowEditor.setEditorAt(table.getSelectedRow(), new DefaultCellEditor(new JTextField()));
              rhsColumn.setCellEditor(rowEditor);
    //Set up tool tips
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    rhsColumn.setCellRenderer(renderer);
    public static void main(String[] args)
    JButtonTableExample frame = new JButtonTableExample();
    frame.addWindowListener(new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    }//end of program
    //Button as a renderer for the table cells
    class ButtonCR implements TableCellRenderer
         JButton btnSelect;
         public ButtonCR()
              btnSelect = new JButton();
              btnSelect.setMargin(new Insets(0,0,0,0));
         public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column)
              if (column != 0) return null; //meany !!!
              return btnSelect;
    }//end fo ButtonCR
    //Default Editor for table
    class ButtonCE extends DefaultCellEditor implements ActionListener
         JButton btnSelect;
         JTable table;
         static int selectedRow = -1;
         public ButtonCE(JCheckBox whoCares)
              super(whoCares);
              btnSelect = new JButton();
              btnSelect.setMargin(new Insets(0,0,0,0));
              btnSelect.addActionListener(this);
              setClickCountToStart(1);
         public Component getTableCellEditorComponent(JTable     table,Object value,boolean isSelected,int row,int column)
              if (column != 0) return null; //meany !!!
              this.selectedRow = row;
              this.table = table;
              System.out.println("Inside getTableCellEditorComponent");
              return btnSelect;
         //public Object getCellEditorValue()
              //return val;
         public void actionPerformed(ActionEvent e)
              // Your Code Here...
              System.out.println("Inside actionPerformed");
              System.out.println("Action performed Row selected "+selectedRow);
              btnSelect.setIcon(new ImageIcon("capsigma.gif"));
    }//end of ButtonCE
    class EachRowEditor implements TableCellEditor
         protected Hashtable editors;
    protected TableCellEditor editor, defaultEditor;
    JTable table;
    * Constructs a EachRowEditor.
    * create default editor
    * @see TableCellEditor
    * @see DefaultCellEditor
    public EachRowEditor(JTable table)
              this.table = table;
         editors = new Hashtable();
         defaultEditor = new DefaultCellEditor(new JTextField());
         editor = defaultEditor;
         * @param row table row
         * @param editor table cell editor
         public void setEditorAt(int row, TableCellEditor editor)
         editors.put(new Integer(row),editor);
    public Component getTableCellEditorComponent(JTable table,Object value, boolean isSelected, int row, int column)
         //editor = (TableCellEditor)editors.get(new Integer(row));
         //if (editor == null)
         //     editor = defaultEditor;
         return editor.getTableCellEditorComponent(table,value, isSelected, row, column);
         public Object getCellEditorValue()
         System.out.println("getCellEditoeValue");
         return editor.getCellEditorValue();
         public boolean stopCellEditing()
         System.out.println("stopCellEditing");
         return editor.stopCellEditing();
         public void cancelCellEditing()
         System.out.println("cancelCellEditing");
         editor.cancelCellEditing();
    public boolean isCellEditable(EventObject anEvent)
    System.out.println("isCellEditable");
    selectEditor((MouseEvent)anEvent);
    return editor.isCellEditable(anEvent);
    public void addCellEditorListener(CellEditorListener l)
    System.out.println("addCellEditorListener");
    editor.addCellEditorListener(l);
    public void removeCellEditorListener(CellEditorListener l)
         System.out.println("removeCellEditorListener");
    editor.removeCellEditorListener(l);
    public boolean shouldSelectCell(EventObject anEvent)
    System.out.println("shouldSelect");
    selectEditor((MouseEvent)anEvent);
    return editor.shouldSelectCell(anEvent);
    protected void selectEditor(MouseEvent e) {
    int row;
    if (e == null) {
    row = table.getSelectionModel().getAnchorSelectionIndex();
    } else {
    row = table.rowAtPoint(e.getPoint());
    editor = (TableCellEditor)editors.get(new Integer(row));
    if (editor == null) {
    editor = defaultEditor;
    }//end of EachRowEditor

    Hello!
    Catch the exception in your event handler:
    try {
    } catch(Exception ex) { ex.printStackTrace(); }
    You can now isolate the wrong line ^;
    Next time if you post such a large code please use code and /code
    enclosed in brackets : []; (See http://forum.java.sun.com/faq.jsp#format)
    class A extends B {
          public void niceCode() {

  • Im trying to update, but all it does is backup my phone, My itunes is updated, BTW, I just went to Apple bar, i had previous problem with prior phone, now im having this update  problem with thyis new phone, someone HELP!!

    Im trying to update, but all it does is backup my phone, My itunes is updated, BTW, I just went to Apple bar, i had previous problem with prior phone, now im having this update  problem with thyis new phone, someone HELP!!

    Same here and this is driving me crazy. I can buy, but can't upgrade. Grrr.

  • JTable Compile problems HELP!!!

    I am trying to display a table of results. The results are held in a text file and I can't seem to get this working please can someone help. I am getting an error cannot resolve symbol. Symbol: variable values. Class EventTable
    JTable table = new JTable(values, columnNames);
    import javax.swing.JTable;
    import javax.swing.JScrollPane;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    import java.util.*;
    import java.text.*;
    public class EventTable extends JFrame {
         /** Member class instance used to hold the primary data InputStream. */
         private FileInputStream m_EventTableInputStream;
         /** Member class instance used to hold the text BufferedReader. */
         private BufferedReader m_bufferedReader;
         String text;
    public EventTable()throws IOException
              super("EventTable");
              FileReader file = new FileReader("c:\\projects\\FirstSupport\\logfile2.txt");
              BufferedReader inputfile = new BufferedReader (file);
              Object[] columnNames = {"Event No",
    "Time Elapsed",
    "Event String",
    "Parameter"};
              MessageFormat mf = new MessageFormat("Event No:{0,number} Time Elapsed: {1,number} Event String:{2} Parameter:{3,number}");
              while ((text = inputfile.readLine()) != null);
                   System.out.println(text);
                   Object[] values = mf.parse(text);
                   int eventNo = ((Number)values[0]).intValue();
                   double time = ((Number)values[1]).doubleValue();
                   String eventString = (String)values[2];
                   int param = ((Number)values[3]).intValue();
    JTable table = new JTable(values,columnNames);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this window.
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    private void printDebugData(JTable table) {
    int numRows = table.getRowCount();
    int numCols = table.getColumnCount();
    javax.swing.table.TableModel model = table.getModel();
    System.out.println("Value of data: ");
    for (int i=0; i < numRows; i++) {
    System.out.print(" row " + i + ":");
    for (int j=0; j < numCols; j++) {
    System.out.print(" " + model.getValueAt(i, j));
    System.out.println();
    System.out.println("--------------------------");
    public static void main(String[] args)throws IOException {
    EventTable frame = new EventTable();
    frame.pack();
    frame.setVisible(true);
    }

    As everyline contains the same headings which I don't want to display These are used as kindof tokenizers to split the file
    I had forgotten to add the text line.
    Below is the code as it should be
    I am totally lost with this. Is there maybe a better way to do it ??
    Object[] values;
              MessageFormat mf = new MessageFormat("Event No:{0,number} Time Elapsed: {1,number} Event String:{2} Parameter:{3,number}");
              text = "Event No: 0     Time Elapsed: 1.0     Event String: Algoritm changed Parameter: algo: Monitoring";
              while ((Line = inputfile.readLine()) != null);
                   System.out.println(text);
                   values = mf.parse(text);
                   int eventNo = ((Number)values[0]).intValue();
                   double time = ((Number)values[1]).doubleValue();
                   String eventString = (String)values[2];
                   int param = ((Number)values[3]).intValue();
              }

  • JTable problem plz help me urgent

    sir
    i carefully read the swing tutorial for JTable for the purpose
    of rendring specially header rendring.
    first u see the code
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.border.*;
    import java.util.*;
    import javax.swing.table.*;
    public class Myscrollpane extends JScrollPane
    ImageIcon icon=new ImageIcon("images/beach1.jpg");
    Image img;
    int w,h,wi,hi;
    TableColumn column = null;
    /*Vector cols=new Vector();
    cols.addElement("Company Code");
    cols.addElement("Company Name");
    String[] names = {"Company Code", "Company Name"};
    DefaultTableModel model=new DefaultTableModel(names,0);
    JTable table=new JTable(model);
    LogoViewport vp;//custom class extends with JViewport
    Myscrollpane(int width,int height)
    vp= new LogoViewport(width,height);
    setOpaque(false);
    setMinimumSize(new Dimension(width,height));
    setPreferredSize(new Dimension(width,height));
    setSize(350,125);
    ///////////here r the table methods to control /////////////////////
    table.setPreferredScrollableViewportSize(new Dimension(width,height));
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF );
    table.getTableHeader().setReorderingAllowed(false);
    table.setBackground(new Color(245,235,237));
    table.setForeground(Color.black);
    table.setOpaque(true);
    table.setEnabled(false);
    table.setFont(new java.awt.Font("Dialog", Font.ITALIC, 12));
    table.setGridColor(Color.pink);
    table.setRowHeight(22);
    table.setSelectionBackground(Color.lightGray);
    DefaultTableCellRenderer renderer=new DefaultTableCellRenderer();
    TableColumn code=table.getColumnModel().getColumn(0);
    renderer.setBackground(Color.red);
    ????//if i use the setIcon method then the data comes from the database
    ????//is not shown because the icon paint above the data.
    code.setCellRenderer(renderer);
    TableCellRenderer headerRenderer = table.getTableHeade.().getDefaultRenderer();
    TableColumn column1=null;
    ???//i use this to change the color of header column but it is not work
    for (int j = 0; j < 2; j++) {
    column1 = table.getColumnModel().getColumn(j);
    Component comp = headerRenderer.getTableCellRendererComponent(
    null, column1.getHeaderValue(),
    false, false, 0, 0);
    comp.setBackground(Color.red);
    ???//if i use following it also not work
    TableCellRenderer headerRenderer = table.getTableHeader().
    getDefaultRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {
    ((DefaultTableCellRenderer)headerRenderer).setBackground(Color.red);}
    for (int i = 0; i <=1; i++)
    column = table.getColumnModel().getColumn(i);
    if (i == 0) {
    column.setPreferredWidth(100);
    else
    column.setPreferredWidth(225);
    vp.setView(table);
    this.setViewport(vp);
    plz help me with the code.
    i also want to draw the image on the table with the use of DefaultTabel
    Model and data set from the data base.Initally no row is shown.
    plz help me
    shown(???) are the quesstion which i am unable to solve.
    thanks in advance.

    Formatting the code makes it easier to read, which means more people may attempt to read your code and answer your questions. Click on the "Help" link at the top of the page.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableHeader extends JFrame
        public TableHeader()
            JTable table = new JTable(5, 5);
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            JScrollPane scrollPane = new JScrollPane( table );
            getContentPane().add( scrollPane );
            table.getTableHeader().setBackground( Color.red );
        public static void main(String[] args)
            TableHeader frame = new TableHeader();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
    }

  • JTable problem plz help me urgent withDefault TableModel

    sir
    i carefully read the swing tutorial for JTable for the purpose
    of rendring specially header rendring.
    first u see the code
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.border.*;
    import java.util.*;
    import javax.swing.table.*;
    public class Myscrollpane extends JScrollPane {
    ImageIcon icon=new ImageIcon("images/beach1.jpg");
    Image img;
    int w,h,wi,hi;
    TableColumn column = null;
    String[] names = {"Company Code", "Company Name"};
    DefaultTableModel model=new DefaultTableModel(names,0);
    JTable table=new JTable(model);
    LogoViewport vp;//user class extends with JViewport
    Myscrollpane(int width,int height){
    vp= new LogoViewport(width,height);
    setOpaque(false);
    setMinimumSize(new Dimension(width,height));
    setPreferredSize(new Dimension(width,height));
    setSize(350,125);
    ///////////here r the table methods tocontrol /////////////////////
    table.setPreferredScrollableViewportSize(new Dimension width,height));
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF );
    table.getTableHeader().setReorderingAllowed(false);
    table.setBackground(new Color(245,235,237));
    table.setForeground(Color.black);
    table.setOpaque(true);
    table.setEnabled(false);
    table.setFont(new java.awt.Font("Dialog", Font.ITALIC, 12));
    table.setGridColor(Color.pink);
    table.setRowHeight(22);
    table.setSelectionBackground(Color.lightGray);
    DefaultTableCellRenderer renderer=new DefaultTableCellRenderer();
    TableColumn code=table.getColumnModel().getColumn(0);
    renderer.setBackground(Color.red);
    //if i use the setIcon method then the data comes from the database is
    //not shown because the icon paint above the data.Iwant to paint the
    //image on the table dynamically means as table populated the image is
    //paint on the table means no fix no of rows.How can i
    //do.
    code.setCellRenderer(renderer);
    TableCellRenderer headerRenderer = table.getTableHeade.().getDefaultRenderer();
    TableColumn column1=null;
    //i use this to change the color and paste icon of header column
    //but it is not work
    for (int j = 0; j < 2; j++) {
    column1 = table.getColumnModel().getColumn(j);
    Component comp = headerRenderer.getTableCellRendererComponent(null, column1.getHeaderValue(), false, false, 0, 0);
    comp.setBackground(Color.red);
    comp.setIcon(new ImageIcon("myimage.gif")); }
    //if i use following it also not work
    TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {((DefaultTableCellRenderer)headerRenderer).setBackground(Color.red);} vp.setView(table);
    this.setViewport(vp);
    }plz help me with the code.
    stated as above i also want to draw the image on the table with the use of DefaultTabel
    Model and data set from the data base.Initally no row is shown.
    plz help me
    thanks in advance

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableHeader extends JFrame
        public TableHeader()
            Object[] columnNames =
                new ImageIcon("copy16.gif"),
                "Some Text",
                new ImageIcon("add16.gif")
            //  Columns headings are cast to a String when created automatically.
            //  We want Icons, so use a special renderer and create the columns manually
            JTable table = new JTable();
            table.getTableHeader().setDefaultRenderer( new HeaderRenderer() );
            for (int i = 0; i < columnNames.length; i++)
                TableColumn newColumn = new TableColumn(i);
                newColumn.setHeaderValue( columnNames[i] );
                table.addColumn(newColumn);
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            JScrollPane scrollPane = new JScrollPane( table );
            getContentPane().add( scrollPane );
        class HeaderRenderer extends DefaultTableCellRenderer
            public Component getTableCellRendererComponent(
                JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col)
                setBorder(UIManager.getBorder("TableHeader.cellBorder"));
                setHorizontalAlignment(CENTER);
                //  color each cell
                if (col == 1)
                    setBackground( Color.yellow );
                else
                    setBackground( Color.green );
                //  display text or icon
                if (value instanceof Icon)
                    setIcon( (Icon)value );
                    setText( "" );
                else
                    setIcon( null );
                    setText((value == null) ? "" : value.toString());
                return this;
        public static void main(String[] args)
            TableHeader frame = new TableHeader();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
    }

  • JTable Problem Can any1 help??

    Hi there,
    I am pretty new to java so please forgive me if this is a silly question but I can not fix this.
    I have a JTable which when I enter a code a new line is added to the table describing the code entered. But when I press a button I basically want to delete everything in the jTable and start a fresh.
    Can anyone help me please :)

    Hi,
    I am not sure as to how you are constructing the JTable.
    But this is one of the way.
    DefaultTableModel tm = new DefaultTableModel(....see definitions to get one that suits);
    JTable myTable = new JTable(tm);
    Now in your actionPerformed method for the clear button-
    int rowcount = getRowCount();
    for(int i = rowcount - 1; i>=0; i-- ){
    tm.removeRow(i);
    Hope it helps
    Best of Luck
    Vignesh

Maybe you are looking for