GetSelectedRow( ) problem.

Hi Guys,
I use combo box to get diffrent tables from microsoft access database.
The table will allow user to click on the cell and the data in the cell will be puting into a text field.
My problem now is when i refresh the table to get another table, the new table will coming out, but the getSelectedRow()is pointed at the wrong direction. Instead of the row that i want, the getSelectedRow() give me the value of -1. I debug for many days already and still don'y know how to fix it......
please help me guys.

http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JTable.html#getSelectedRow()
quote:
Returns the index of the first selected row, -1 if no row is selected.

Similar Messages

  • Problem using getSelectedRow... Tenks

    Can you help me on how to solve my problem about the getSelectedRow .....
    I have one JComboBox and a SearchButton
    ... Once I selected an Item in a JComboBox, I will press the SearchButton
    and then it will look up to the database and display it in the JTable..........
    i used the getSelectedRow to print the value that I selected in the table...
    like this...
    public void mouseClicked(MouseEvent e) {
    if(e.getClickCount() == 1 ) {
    System.out.println(table1.getSelectedRow());
    In the first press in the SearchButton and then clicking the row
    , It will print the selected row...... but when i press again the SearchButton then clicking a row again........
    there is a problem occured....... selectedRow is always -1, can you help me to solve this.....

    tenks for the help.... but the main problem here is that, yes I always get the value in the combo box when i pressed the button searched.... and when i look up to the database to check it.... it will display it in the table....
    The problem is when I pressed twice or trice the search button, then if there is a value in the database it will display it, in the table.....
    I Used the event mouseClicked, in clicking the row to print the value...
    But everytime I click the Search button twice, then clicking the row... the value is always -1, looks like he cannot read the row.... Is there any way to do this.... thank you.....

  • 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();
    }

  • Can You Help Me ABout getSelectedRow in JTable

    Can you help me on how to solve my problem about the getSelectedRow .....
    I have one JComboBox and a SearchButton
    ... Once I selected an Item in a JComboBox, I will press the SearchButton
    and then it will look up to the database and display it in the JTable..........
    i used the getSelectedRow to print the value that I selected in the table...
    like this...
    public void mouseClicked(MouseEvent e) {
    // Ilabas yung form
    if(e.getClickCount() == 1 ) {
    System.out.println(table1.getSelectedRow());
    In the first press in the SearchButton and then clicking the row
    , It will print the selected row...... but when i press again the SearchButton then clicking a row again........
    there is a problem occured....... selectedRow is always -1, can you help me to solve this.....

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.sql.*;
    import java.util.*;
    import javax.swing.plaf.metal.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import java.text.*;
    import java.beans.*;
    public class OpenProject extends JDialog {
         ResultSet rs, rs1, rs2, rs3;
         JFrame JFParentFrame; // create a JFrame
         JFrame OwnerFrame; // create a JFrame
         public JLabel proj_name;
         public JLabel proj = new JLabel("Project Name:");
         public JLabel form = new JLabel("Form Name");
         public JLabel lang = new JLabel("Language");
         public JComboBox form_lang = new JComboBox();
         public JComboBox form_name = new JComboBox();
         public JButton edit = new JButton("Edit");
         public JButton reload = new JButton("Search");
         public JButton def = new JButton("Set Text Default");
         public JButton langs = new JButton("Add Language");
         public JButton exit = new JButton("Exit");
         public JPanel panel1 = new JPanel ();
         public JTable table1, table2, table3,table4;
         public JScrollPane scrollPane1, scrollPane2, scrollPane3, scrollPane4;
         public JTabbedPane UITab,UITab1;
         Container c = getContentPane();
         Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
         public String column[][];
         public String strRow;
         public String strCol;
         public String strForm;
         public String strGetProj_id;
         public String strForm_lang;
         public String strForm_name;
         private boolean DEBUG = false;
         public int getLang;
         public int getForm;
         public int getDef_id;
         public int count2 = 0,count3 = 0,count4 = 0;
         public int row2 = 0,row3 = 0,row4 = 0;
         public int selectedRow1 = 0, selectedRow2 = 0;
         public DbBean db = new DbBean();
         public OpenProject(JFrame OwnerForm, String getProj_id) {
              super(OwnerForm,true);
                   strGetProj_id = getProj_id;
              try{
                   db.connect();
              } catch(SQLException sqlex) {
              } catch(ClassNotFoundException cnfex) {
              try {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              } catch(Exception e) {
              // Para ito sa paglalagay sa dalawang combo box ng value.......
              try {
                   rs = db.execSQL("Select * from mst_form where form_proj_id = "+strGetProj_id+"");
                   while(rs.next()) {
                        form_name.addItem(rs.getString("form_name"));
                        //System.out.println(strForm);
              } catch(SQLException sqlex) {
              try {
                   rs = db.execSQL("Select distinct from mst_form where form_proj_id = "+strGetProj_id+"");
                   while(rs.next()) {
                        form_name.addItem(rs.getString("form_name"));
                        //System.out.println(strForm);
              } catch(SQLException sqlex) {
              try {
                   int counts;
                   rs = db.execSQL("Select * from mst_project where proj_id = "+strGetProj_id+"");
                   while(rs.next()) {
                        counts = rs.getInt("proj_lang_id");
                        System.out.println(counts);
                        rs1 = db.execSQL("Select * from mst_language where lang_id = "+counts+"");
                        while (rs1.next()) {
                             form_lang.addItem(rs1.getString("lang_name"));     
              } catch(SQLException sqlex) {
              edit.setActionCommand("edit");
              edit.addActionListener(actions);
              reload.setActionCommand("load");
              reload.addActionListener(actions);
              def.setActionCommand("default");
              def.addActionListener(actions);
              langs.setActionCommand("lang");
              langs.addActionListener(actions);
              exit.setActionCommand("exit");
              exit.addActionListener(actions);
              proj_name = new JLabel();     
              proj_name.setBackground(new Color(255,255,255));
              form_name.setMaximumRowCount(5);
              form_name.setBackground(new Color(255,255,255));
              form_lang.setMaximumRowCount(5);
              form_lang.setBackground(new Color(255,255,255));
              proj.setBounds(20, 20,100,20);
              proj_name.setBounds(120, 20,250,20);
              form.setBounds(20, 50,100,20);
              form_name.setBounds(120, 50,150,20);
              lang.setBounds(300, 50,100,20);     
              form_lang.setBounds(380, 50,150,20);
              reload.setBounds(560,50,80, 20);
              edit.setBounds(110,360,115,20);
              def.setBounds(230,360,115,20);
              langs.setBounds(350,360,115,20);
              exit.setBounds(470,360,115,20);
              panel1.add(getTable());
              panel1.setLayout(null);     
              panel1.setBackground(Color.white);     
              panel1.add(proj);
              panel1.add(proj_name);
              panel1.add(form);
              panel1.add(form_name);
              panel1.add(lang);
              panel1.add(form_lang);
              panel1.add(reload);     
              panel1.add(def);
              panel1.add(langs);
              panel1.add(exit);
              panel1.add(edit);
              c.add(panel1);
              setSize(680,420);
              setTitle("Open Project");
              setLocation((screen.width - 590)/2,((screen.height - 280)/2) - 45);
         public JTabbedPane getTable() {
              UITab = new JTabbedPane();
              strForm_lang = form_lang.getSelectedItem().toString();
              strForm_name = form_name.getSelectedItem().toString();
              int count1=0;
              int row1=0;
              try {
                   rs = db.execSQL("Select * from mst_default where def_proj_id = '"+strGetProj_id+"' AND def_category = 'Title'" );
                   while(rs.next()) {
                        count1 += 1;
                        getDef_id = rs.getInt("def_id");
                   column = new String[count1][2];
                   rs1 = db.execSQL("Select form_id from mst_form WHERE form_name = '"+strForm_name+"'");
                   while(rs1.next()) {
                        getForm = rs1.getInt("form_id");
                        System.out.println("getForm");
                   rs2 = db.execSQL("Select lang_id from mst_language WHERE lang_name = '"+strForm_lang+"'");
                   while(rs2.next()) {
                        getLang = rs2.getInt("lang_id");
                        System.out.println("getLang");
                   rs3 = db.execSQL("Select * from mst_default a, mst_translation b WHERE a.def_form_id = '"+getForm+"' AND b.trans_lang_id = '"+getLang+"' AND a.def_proj_id = '"+strGetProj_id+"' AND b.trans_def_id = '"+getDef_id+"' AND a.def_category = 'Title' " );
                   while(rs3.next()) {
                        column[row1][0] = "" + rs3.getString("display_name");          // rowNum ay kung ilan ang row na ilalabas
                   column[row1][1] = "" + rs3.getString("translation"); // Default yung isang array ng column ko, kaya fixed
                        row1++;
                   row1 = 0;
              } catch(SQLException sqlex) {
                   sqlex.printStackTrace();
                   System.exit(1);
              // End
              table1 = new JTable(new MyTableModel()){
              scrollPane1 = new JScrollPane(table1);
              UITab.setBounds(30,100,610,250);
              UITab.add("Title",scrollPane1);
              return UITab;
         class MyTableModel extends AbstractTableModel {     
                   // Pagawa ng header Coloumn
                   String ColumnHeaderName[] = {
                        "Default Text",""+strForm_lang+" Translation"
                   //End
                   public int getColumnCount() {     
                        //System.out.println("The Column Count is" + ColumnHeaderName.length);
         return ColumnHeaderName.length;
         public int getRowCount() {
              //System.out.println("The Row Count is" + column.length);
         return column.length;
         public String getColumnName(int col) {
                        //System.out.println("The Column Name is" + ColumnHeaderName[col]);     
         return ColumnHeaderName[col];
         public Object getValueAt(int row,int col) {
              System.out.println("The value at row and column = " + column[row][col]);
         return column[row][col];
         public int getSelectedRow() {
              System.out.println("Integer" + column.length);
              return column.length;
         ActionListener actions = new ActionListener() {
              public void actionPerformed(ActionEvent ae) {
                   String source = ae.getActionCommand();
                   if (source == "load") {
                        table1.clearSelection();
                        panel1.add(getTable());
                        table1.addNotify();
                        repaint();
                   } else if (source == "default") {
                        dispose();
                        TextDefaultForm form = new TextDefaultForm(OwnerFrame,JFParentFrame);
                        form.setVisible(true);
                   } else if (source == "lang") {
                        dispose();
                        CreateProject lang = new CreateProject(JFParentFrame);
                        lang.setVisible(true);
                   } else if (source == "exit") {
                        dispose();
                   } else if (source == "edit") {
                        if (table1.getValueAt(table1.getSelectedRow(),table1.getSelectedColumn()) != null){
                             formLang lang = new formLang(OwnerFrame,strCol,strRow, strGetProj_id);
                             lang.setVisible(true);
         MouseListener MouseTableListener = new MouseListener() {
                   public void mouseClicked(MouseEvent e) {
                        // Ilabas yung form
                        if(e.getClickCount() == 2 ) {
                             dispose();
                             int col_a = 0;
                             int col_b = 1;
                             selectedRow1 = table1.getSelectedRow();     
                             Object objColumn1 = table1.getValueAt(selectedRow1, col_a);
                             Object objRow1 = table1.getValueAt(selectedRow1, col_b);
                             strCol = objColumn1.toString();
                             strRow = objRow1.toString();
                             formLang lang = new formLang(OwnerFrame,strCol,strRow,strGetProj_id);
                             System.out.println(selectedRow1);
                             System.out.println(strCol);
                             System.out.println(strRow);
                             lang.txtProj.setText(strCol);
                             lang.txtLang.setText(strRow);
                             lang.show();
                        } else if (e.getClickCount() == 1) {
                             table1.setSelectionBackground(Color.blue);
                             table1.setColumnSelectionAllowed(false);
                        table1.setRowSelectionAllowed(true);
                        table1.setFocusable(true);
                             int a = table1.getRowCount();
                             System.out.println("Row Count = " + a);
                             int sel = table1.getSelectedRow();     
                             //if (sel == -1) return;
                             System.out.println("Selected Row = " + sel);
                             System.out.println(table1.isRowSelected(sel));
                   public void mouseReleased(MouseEvent e) {
                   public void mouseExited(MouseEvent e) {
                   public void mouseEntered(MouseEvent e) {
                   public void mousePressed(MouseEvent e) {
         //public static void main(String leo[]) {
              //OpenProject open = new OpenProject();
    }

  • A problem to get the value of a selected cell

    Hi all,
    I am trying to get the value of a cell in JTable. The problem that I have is ListSelectionListener only listens if the selection changes(valueChanged method).
    It means that if I select apple then rum, only rowSelectionModel is triggered, which means I do not get the index of the column from selectionModel of ColumnModel.
    apple orange plum
    rum sky blue
    This is a piece of code from JTable tutorial that I modified by adding
    selRow and selCol variables to keep track of the location so that I can get the value of the selected cell.
    Thank you.
    if (ALLOW_ROW_SELECTION) { // true by default
    ListSelectionModel rowSM = table.getSelectionModel();
    rowSM.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
    if (e.getValueIsAdjusting()) return;
    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
    if (lsm.isSelectionEmpty()) {
    System.out.println("No rows are selected.");
    } else {
    int selectedRow = lsm.getMinSelectionIndex();
    selRow = selectedRow;
    System.out.println("Row " + selectedRow + " is now selected.");
    else {
    table.setRowSelectionAllowed(false);
    if (ALLOW_COLUMN_SELECTION) { // false by default
    if (ALLOW_ROW_SELECTION) {
    table.setCellSelectionEnabled(true);
    table.setColumnSelectionAllowed(true);
    ListSelectionModel colSM = table.getColumnModel().getSelectionModel();
    colSM.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
    //Ignore extra messages.
    if (e.getValueIsAdjusting()) return;
    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
    if (lsm.isSelectionEmpty()) {
    System.out.println("No columns are selected.");
    } else {
    int selectedCol = lsm.getMinSelectionIndex();
    selCol = selectedCol;
    System.out.println("Column " + selCol + " is now selected.");
    System.out.println("Row " + selRow + " is now selected.");
    javax.swing.table.TableModel model = table.getModel();
    // I get the value here
    System.out.println("Value: "+model.getValueAt(selRow,selCol));
    }

    maybe you can try with :
    table.getSelectedColumn()
    table.getSelectedRow()
    :)

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

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

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

  • While loop problem

    I have a problem with a while loop in this code and it is really holding me up doing my degree. I can see nothing wrong with it but perhaps someone here can help. I would be really greatful if someone could. I have commented the line where the while loop starts about a third of the way down the code.
    Thanks
    Michael
    if (ae.getSource()==client_open)
    int row=0;
    check=true;
    row=client_listing.getSelectedRow();
    try
    System.out.println("information[row][1] is "+information[row][1]);
    if(information[row][1]!=null) //if the index is not null. Comment out this if statement to troubleshoot
    try
    InetAddress inet=InetAddress.getByName(information[row][1]);
    //Create a client socket on the listeners machone on port 7070
    client_socket=new Socket(inet,7070);
    System.out.println("Client port open on 7070 ");
    //Get the output as well as the input streams on that socket
    BufferedOutputStream out=new BufferedOutputStream(client_socket.getOutputStream());
    BufferedInputStream br_socket=new BufferedInputStream(client_socket.getInputStream());
    XMLWriter writer=new XMLWriter();
    writer.requestFString("SHOWFILES"," ");
    String file_data=writer.returnRequest();
    byte file_bytes[]=file_data.getBytes();
    int file_size=file_bytes.length;
    byte b[]=new byte[1024];
    // The methos takes a byte array and it's length as parameters and return
    // a byte array of length 1024 bytes....
    add_on upload=new add_on();
    System.out.println("Class of add_on created sucessfully");
    b=upload.appropriatelength(file_bytes,file_size);
    out.write(b,0,1024);
    /*An output stream is also initialised. This is used to store all the response
    from the listener */
    BufferedOutputStream out_file=new BufferedOutputStream(new FileOutputStream("response.xml"));
    int y=0;
    byte f[]=new byte[32];
    System.out.println("Entering while loop");
    //This while loop is not working. Any ideas. It just hangs here
    while((y=br_socket.read(f,0,32))>0) //the socket input stream is read
    out_file.write(f,0,y); //written on to the file output stream, y bytes from f start @ ofset 0
    out.close();
    br_socket.close();
    out_file.close();
    System.out.println("Exited while loop and closed streams");
    catch(Exception e)
    client_socket=null;
    check=false;
    System.out.println("Didnt enter try");
    try
    client_socket.close();
    catch(Exception e)
    System.out.println("Error occuered "+e.getMessage());
    row=0;
    if(check) //If the exception occurs then do not come here
    Vector parameters=new Vector();
    // A class SParser is also used here this class has a function/method of
    // the name perform which calls the xml parser to parse the xml file
    // generated by the response from the client soket...
    // the function perform returns a Vector which has the files/directories,
    // along with their flag information and size in case of files....
    SParser sp=new SParser();
    System.out.println("SParser object created sucessfully");
    parameters=sp.perform("response.xml");
    System.out.println("Parsing finished ");
    // The vector value returned by the xml parseris then passed as one of
    // the parameters to a class named file_gui this class is responsible for
    // displaying GUI consisting of a table and some buttons along with the
    // root information and flag..
    // Initially since the class is called for the first time the parameter
    // for the root is given the name "ROOT" and the Flag is set to "0"..
    file_gui showfiles=new file_gui(parameters,information[row][1],"Root","0");
    showfiles.show();
    check=false;
    } //end if
    } // end if
    } //end try
    catch(Exception e)
    row=0;
    } //end of ae.getSource()

    Why do you think it hangs at the while loop, eh? You need to put in additional printlns to justify your assertion. It takes alot less time to diagnose if you put in specific try/catch blocks with their own printlns - even if it is not as much fun. When you get into these kinds of troubles, there is no shame in putting in prints at each statement or logical point to track down the actual fault.
    ~Bill

  • Problem retrieving data from a JTable.

    Hi All,
    I've just searched to 45th page of this forum but I heven't found a topic containing infos that can help me.
    Well, my problem is: I have to retrieve data from a JTable. I use getValue() method but it seems to work well on all cells of a row but the last cell. I use the TAB to move focus on the row and when it is on the last cell, using TAB, the focus jumps on the next row & 1st column.
    Using TAB moving on system, I can retrieve all data but data on the last cell data.
    I add another info hoping someone has a solution for my problem: If the focus goes back on the last cell of a row just edited, in this case the data retrieving work as well.
    Thank you for your attention!
    Bye.

    I don't understand your question. I don't understand what using Tab and getValueAt(...) have to do with one another. If you want data from a cell then just use getValueAt(...).
    If you want to know what cell currently has focus you use
    getSelectedRow()
    getSelectedColumn()

  • Problem in Saving records in JTable

    Hi all,
    iam using DefaultTableModel ... iam displaying Rows and Columns in my table from database..and iam adding a new row to edit data and by clicking the save button the edited data as to be stored in the database..
    My task is to Add the edited data in from the JTable to the database..
    My Save Method.............
    The problem iam facing in these methiod is that
    When ian typing data in the newly added row three columns it is showing nullpointer exception and if i type
    some data in the fourth column it is printing without exception but see below i am getting table value only for three columns .............
    public void save(){
         int row =info_table.getSelectedRow();
         System.out.println(row);
         strCustId = info_table.getValueAt(row, 0).toString();
         System.out.println(strCustId);
         strDelFlg =info_table.getValueAt(row, 1).toString();
         System.out.println(strDelFlg);
                         strPostCd =info_table.getValueAt(row, 2).toString();
                          System.out.println(strPostCd);
              

    this question has come up VERY often in this forum, as well as the database forum, AND the java programming forum, just doing a quick search i've come up with these threads:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=557433
    http://onesearch.sun.com/search/onesearch/index.jsp?qt=jtable+to+database&rf=0&qp=siteforumid%3Ajava48&site=dev&nh=10&cs=0&chooseCat=allJava&st=1&col=developer-forums

  • Problem with ListSelectionListener

    I'm having a problem with my ListSelectionListener. I had it as part of my Scheduler class
    //from old scheduler class
                schedulerTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
                ListSelectionModel rowSM = schedulerTable.getSelectionModel();
                rowSM.addListSelectionListener( new ListSelectionListener()
                  public void valueChanged( ListSelectionEvent e ) {
                    //Ignore extra messages.
                    if ( e.getValueIsAdjusting() )
                      return;
                    ListSelectionModel lsm = ( ListSelectionModel ) e.getSource();
                    if ( lsm.isSelectionEmpty() )
                      System.out.println( "No rows are selected." );
                    else
                      //int selectedRow = lsm.getMinSelectionIndex ();
                      int row = 0, column = 0;
                      column = schedulerTable.getSelectedColumn();
                      row = schedulerTable.getSelectedRow();
                      if ( schedulerTable.getValueAt( row, column ) != null )
                        practassist.domain.Appointment data = ( practassist.domain.
                            Appointment ) schedulerTable.
                            getValueAt( row, column );
                        // Do something with the data...
                        //printDetails( data );
                } );but i didn't know how to pass back the "data" object so i'm doing it the long, hard and wrong way.
    I've add the code as a method in my SchedulerUI class which creates two instances of the Scheduler class for the tabbed pane.
    I think it might be easier to add most of my code and put:
    //"###########################################"to highlight the areas i've a problem with. So here it goes, sorry bout dis in advance.
    import ...
    public class SchedulerUI extends JFrame
        private BorderLayout borderLayout1 = new BorderLayout ();
        private JTabbedPane schedulerView;
        private JPanel panDayView;
        private JPanel panMonthView;
        Scheduler dayView;
        Scheduler monthView;
        private CalPane schCal = new CalPane ();
        public SchedulerUI ()
            try {
                jbInit ();
            catch ( Exception exception ) {
                exception.printStackTrace ();
            practassist.domain.Appointment appDetails = this.applyListSelectionModel(dayView);
            printDetails (appDetails);
        private void jbInit () throws Exception
            getContentPane ().setLayout ( borderLayout1 );
            //Layout
            c = getContentPane ();
            c.setLayout ( new BorderLayout () );
            schedulerView = new JTabbedPane ();
            schedulerView.setSize ( 900, 550 );
            panDayView = new JPanel ( new FlowLayout () );
            panDayView.setSize ( 60, 60 );
            panMonthView = new JPanel ( new FlowLayout () );
            schedulerView.addTab ( "Day View", panDayView );
            schedulerView.addTab ( "Week View", panMonthView );
            this.setSize ( schedulerView.getWidth (), schedulerView.getHeight () );
            north = new JPanel ();
            north.setLayout ( new FlowLayout () );
            south = new JPanel ();
            south.setLayout ( new FlowLayout () );
            west = new JPanel ();
            west.setLayout ( new FlowLayout () );
            westComponents ();
            c.add ( west, BorderLayout.WEST );
        public void westComponents ()
            Calendar date1 = Calendar.getInstance ();
            Calendar[] dView = {date1};
            dayView = new Scheduler ( dView );
            Calendar[] mView = new Calendar[6 ];
            //Initialise array
            for ( int j = 0; j < 6; j++ ) {
                mView[ j ] = Calendar.getInstance ();
            //set dates in array
            if ( date1.get ( Calendar.DAY_OF_WEEK ) == 2 ) {
                for ( int i = 0; i < 6; i++ ) {
                    mView[ i ].set ( date1.get ( Calendar.YEAR ),
                                     date1.get ( Calendar.MONTH ),
                                     ( date1.get ( Calendar.DATE ) + i ) );
            else {
                int day = date1.get ( Calendar.DATE );
                int month = date1.get ( Calendar.MONTH );
                int year = date1.get ( Calendar.YEAR );
                int addDay = 0;
                for ( int i = 0; i < 6; i++ ) {
                    if ( ( date1.get ( Calendar.DAY_OF_WEEK ) + i ) ==
                         Calendar.SATURDAY ) {
                        mView[ i ].set ( year, month, ( day + addDay ) );
                        addDay++;
                    else if ( ( date1.get ( Calendar.DAY_OF_WEEK ) + addDay ) ==
                              Calendar.SUNDAY ) {
                        addDay++;
                        mView[ i ].set ( year, month, ( day + addDay ) );
                    else {
                        mView[ i ].set ( year, month, ( day + addDay ) );
                    addDay++;
            monthView = new Scheduler ( mView );
            AppointmentController aptController = new AppointmentController ();
            practassist.domain.Appointment[] appointments = aptController.view ( null );
            System.out.println ( "Day View:" );
            dayView.addToTable ( appointments );
            System.out.println ( "Month View:" );
            monthView.addToTable ( appointments );
            panDayView.add ( dayView );
            panMonthView.add ( monthView );
            west.add ( schedulerView );
        public void printDetails ( practassist.domain.Appointment displayApp )
            Calendar appDate = displayApp.getAppointmentDate ();
            Calendar appTime = displayApp.getAppointmentTime ();
            Calendar appAllocation = displayApp.getTimeAllocation ();
            patient.setText ( displayApp.getPatient ().getName () );
            txtDate.setText ( "" + appDate.get ( Calendar.DATE ) + "/" +
                              appDate.get ( Calendar.MONTH ) + "/" +
                              appDate.get ( Calendar.YEAR ) );
            time.setText ( "" + appTime.get ( Calendar.HOUR ) + ":" +
                           appTime.get ( Calendar.MINUTE ) );
            timeAllocation.setText ( "" +
                                     appAllocation.get ( Calendar.HOUR ) + ":" +
                                     appAllocation.get ( Calendar.MINUTE ) );
            procedures.setListData ( displayApp.getProcedures () );
            dentist.setText ( "" + displayApp.getDentist ().getName () );
            System.out.println ( displayApp.getPatientArrived () );
            arrived.setSelected ( displayApp.getPatientArrived () );
        public practassist.domain.Appointment applyListSelectionModel ( Scheduler
                scheduler )
            JTable schedulerTable = scheduler.getTable ();
            schedulerTable.setSelectionMode ( ListSelectionModel.SINGLE_SELECTION );
            ListSelectionModel rowSM = schedulerTable.getSelectionModel ();
            rowSM.addListSelectionListener ( new ListSelectionListener ()
                public void valueChanged ( ListSelectionEvent e )
                    //Ignore extra messages.
                    if ( e.getValueIsAdjusting () ) {
                        return;
                    ListSelectionModel lsm = ( ListSelectionModel ) e.getSource ();
                    if ( lsm.isSelectionEmpty () ) {
                        System.out.println ( "No rows are selected." );
                    else {
                        //int selectedRow = lsm.getMinSelectionIndex ();
                        int row = 0, column = 0;
    //see errors below for schedulerTable
                        column = schedulerTable.getSelectedColumn ();
    //see errors below for schedulerTable
                        row = schedulerTable.getSelectedRow ();
    //see errors below for schedulerTable
                        if ( schedulerTable.getValueAt ( row, column ) != null ) {
                            practassist.domain.Appointment appData = ( practassist.
                                    domain.Appointment ) schedulerTable.
                                    getValueAt (
                                            row,
                                            column );
                            // Do something with the data...
                            //return appData
    }I'm getting errors saying
    "SchedulerUI.java": local variable schedulerTable is accessed from within inner class; needs to be declared final at line 301, column 30
    "SchedulerUI.java": local variable schedulerTable is accessed from within inner class; needs to be declared final at line 302, column 27
    "SchedulerUI.java": local variable schedulerTable is accessed from within inner class; needs to be declared final at line 304, column 26
    "SchedulerUI.java": local variable schedulerTable is accessed from within inner class; needs to be declared final at line 306, column 54
    any advice. Will i post up the Scheduler class? Sorry bout the length of dis one.

    schedulerTable is accessed from within inner class; needs to be declared final
    final JTable schedulerTable = scheduler.getTable ();

  • Problem of deletion of rows in jtable, table refreshing too

    Hi,
    I have a table with empty rows in the beginning with some custom properties( columns have fixed width...), later user would be adding to the rows to this table and can delete, I've a problem while deleting the rows from table,
    When a selected row is deleted the model is also deleting the data but the table(view) is not refreshed.
    Actually i'm selecting a cell of a row, then hitting the delete button.
    So the model is deleting the information, but i'm not able to c the fresh data in table( especially when the last cell of last row is selectd and hit the delete button, i am getting lots of exception)
    Kindly copy the below code and execute it, and let me know,
    * AuditPanel.java
    * Created on August 30, 2002, 3:05 AM
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.util.Vector;
    * @author yaman
    public class AuditPanel extends javax.swing.JPanel {
    // These are the combobox values
    private String[] acceptenceOptions;
    private Vector colNames;
    private Color rowSelectionBackground = Color.yellow;
    private int rowHeight = 20;
    private int column0Width =70;
    private int column1Width =96;
    private int column2Width =327;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    /** Creates new form AuditPanel */
    public AuditPanel() {
    public void renderPanel(){
    initComponents();
    public String[] getAcceptenceOptions(){
    return acceptenceOptions;
    public void setAcceptenceOptions(String[] acceptenceOptions){
    this.acceptenceOptions = acceptenceOptions;
    public Vector getColumnNames(){
    return colNames;
    public void setColumnNames(Vector colNames){
    this.colNames = colNames;
    public Vector getData(){
    Vector dataVector = new Vector();
    /*dataVector.add(null);
    dataVector.add(null);
    dataVector.add(null);
    return dataVector;
    /** 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.
    private void initComponents() {
    java.awt.GridBagConstraints gridBagConstraints;
    jPanel2 = new javax.swing.JPanel();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jPanel1 = new javax.swing.JPanel();
    jTable1 = new javax.swing.JTable();
    setLayout(new java.awt.GridBagLayout());
    setBorder(new javax.swing.border.EmptyBorder(0,0,0,0));
    jPanel2.setLayout(new java.awt.GridBagLayout());
    jPanel2.setBorder(new javax.swing.border.EmptyBorder(0,0,0,0));
    jButton1.setText("Add");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints.ipadx = 8;
    gridBagConstraints.insets = new java.awt.Insets(0, 1, 5, 0);
    gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
    jPanel2.add(jButton1, gridBagConstraints);
    jButton2.setText("Delete");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
    jPanel2.add(jButton2, gridBagConstraints);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
    gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
    add(jPanel2, gridBagConstraints);
    jPanel1.setLayout(new java.awt.GridBagLayout());
    jPanel1.setBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.LOWERED, Color.black, Color.gray) );
    jTable1.setModel(new javax.swing.table.DefaultTableModel(getData(), getColumnNames()));
    // get all the columns and set the column required properties
    java.util.Enumeration enum = jTable1.getColumnModel().getColumns();
    while (enum.hasMoreElements()) {
    TableColumn column = (TableColumn)enum.nextElement();
    if( column.getModelIndex() == 0 ) {
    column.setPreferredWidth(column0Width);
    column.setCellEditor( new ValidateCellDataEditor(true) );
    if( column.getModelIndex() == 1) {
    column.setPreferredWidth(column1Width);
    column.setCellEditor(new AcceptenceComboBoxEditor(getAcceptenceOptions()));
    // If the cell should appear like a combobox in its
    // non-editing state, also set the combobox renderer
    //column.setCellRenderer(new AcceptenceComboBoxRenderer(getAcceptenceOptions()));
    if( column.getModelIndex() == 2 ) {
    column.setPreferredWidth(column2Width); // width of column
    column.setCellEditor( new ValidateCellDataEditor(false) );
    jScrollPane1 = new javax.swing.JScrollPane(jTable1);
    jScrollPane1.setPreferredSize(new java.awt.Dimension(480, 280));
    jTable1.setMinimumSize(new java.awt.Dimension(60, 70));
    //jTable1.setPreferredSize(new java.awt.Dimension(300, 70));
    //jScrollPane1.setViewportView(jTable1);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
    jPanel1.add(jScrollPane1, gridBagConstraints);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 0;
    add(jPanel1, gridBagConstraints);
    // set the row height
    jTable1.setRowHeight(rowHeight);
    // set selection color
    jTable1.setSelectionBackground(rowSelectionBackground);
    // set the single selection
    jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    // avoid table header to resize/ rearrange
    jTable1.getTableHeader().setReorderingAllowed(false);
    jTable1.getTableHeader().setResizingAllowed(false);
    // Table header font
    jTable1.getTableHeader().setFont( new Font( jTable1.getFont().getName(),Font.BOLD,jTable1.getFont().getSize() ) );
    jButton1.setMnemonic(KeyEvent.VK_A);
    // action of add button
    jButton1.addActionListener( new ActionListener(){
    public void actionPerformed(ActionEvent actionEvent){
    // If a button press is the trigger to leave a JTable cell and save the data in model
    if(jTable1.isEditing() ){
    //System.out.println("table is edition ");
    String text=((javax.swing.text.JTextComponent)jTable1.getEditorComponent()).getText();
    jTable1.setValueAt(text,jTable1.getSelectedRow(),jTable1.getSelectedColumn()) ;
    jTable1.getCellEditor().cancelCellEditing();
    // find out total available rows
    int totalRows = jTable1.getRowCount();
    int cols = jTable1.getModel().getColumnCount();
    if( jTable1.getModel() instanceof DefaultTableModel ) {
    ((DefaultTableModel)jTable1.getModel()).addRow(new Object[cols]);
    int newRowCount = jTable1.getRowCount();
    // select the first row
    jTable1.getSelectionModel().setSelectionInterval(newRowCount-1,newRowCount-1);
    jButton2.setMnemonic(KeyEvent.VK_D);
    // action of Delete button
    jButton2.addActionListener( new ActionListener(){
    public void actionPerformed(ActionEvent actionEvent){
    int totalRows = jTable1.getRowCount();
    // If there are more than one row in table then delete it
    if( totalRows > 0){
    int selectedOption = JOptionPane.showConfirmDialog(null,"Are you sure you want to delete this audit row?","Coeus", JOptionPane.YES_NO_OPTION);
    // if Yes then selectedOption is 0
    // if No then selectedOption is 1
    if(0 == selectedOption ){
    // get the selected row
    int selectedRow = jTable1.getSelectedRow();
    System.out.println("Selected Row "+selectedRow);
    if( selectedRow != -1 ){
    DefaultTableModel dm= (DefaultTableModel)jTable1.getModel();
    java.util.Vector v1=dm.getDataVector();
    System.out.println("BEFOE "+v1);
    v1.remove(selectedRow);
    jTable1.removeRowSelectionInterval(selectedRow,selectedRow);
    System.out.println("After "+v1);
    }else{
    // show the error message
    JOptionPane.showMessageDialog(null, "Please Select an audit Row", "Coeus", JOptionPane.ERROR_MESSAGE);
    } // end of initcomponents
    class AcceptenceComboBoxRenderer extends JComboBox implements TableCellRenderer {
    public AcceptenceComboBoxRenderer(String[] items) {
    super(items);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    if (isSelected) {
    setForeground(table.getSelectionForeground());
    super.setBackground(rowSelectionBackground);
    } else {
    setForeground(table.getForeground());
    setBackground(table.getBackground());
    // Select the current value
    setSelectedItem(value);
    return this;
    class AcceptenceComboBoxEditor extends DefaultCellEditor {
    public AcceptenceComboBoxEditor(String[] items) {
    super(new JComboBox(items));
    } // end editor class
    public class ValidateCellDataEditor extends AbstractCellEditor implements TableCellEditor {
    // This is the component that will handle the editing of the
    // cell value
    JComponent component = new JTextField();
    boolean validate;
    public ValidateCellDataEditor(boolean validate){
    this.validate = validate;
    // This method is called when a cell value is edited by the user.
    public Component getTableCellEditorComponent(JTable table, Object value,
    boolean isSelected, int rowIndex, int vColIndex) {
    if (isSelected) {
    component.setBackground(rowSelectionBackground);
    // Configure the component with the specified value
    JTextField tfield =(JTextField)component;
    // if any vaidations to be done for this cell
    if(validate){
    //tfield.setDocument(new JTextFieldFilter(JTextFieldFilter.NUMERIC,4));
    tfield.setText( ((String)value));
    // Return the configured component
    return component;
    // This method is called when editing is completed.
    // It must return the new value to be stored in the cell.
    public Object getCellEditorValue() {
    return ((JTextField)component).getText();
    // This method is called just before the cell value
    // is saved. If the value is not valid, false should be returned.
    public boolean stopCellEditing() {
    String s = (String)getCellEditorValue();
    return super.stopCellEditing();
    public void itemStateChanged(ItemEvent e) {
    super.fireEditingStopped();
    }//end of ValidateCellDataEditor class
    public static void main(String args[]){
    JFrame frame = new JFrame();
    AuditPanel auditPanel = new AuditPanel();
    frame.getContentPane().add(auditPanel);
    auditPanel.setAcceptenceOptions(new String[]{"Accepted", "Rejected", "Requested"} );
    java.util.Vector colVector = new java.util.Vector();
    colVector.add("Fiscal Year");
    colVector.add("Audit Accepted");
    colVector.add("Comment" );
    auditPanel.setColumnNames( colVector);
    auditPanel.renderPanel();
    frame.pack();
    frame.show();

    Hi,
    I've got the solution for it. As when the cursor is in cell of
    a row and hit the delete button, the data in that cell is not saved,
    So i'm trying to save the data first into the model then firing the action event by doing this ..
    jButton2.addActionListener( new ActionListener(){       
    public void actionPerformed(ActionEvent actionEvent){           
    // If a button press is the trigger to leave a JTable cell and save the data in model
    if(jTable1.isEditing() ){                   
    String text=((javax.swing.text.JTextComponent)jTable1.getEditorComponent()).getText();
    jTable1.setValueAt(text,jTable1.getSelectedRow(),jTable1.getSelectedColumn()) ;
    jTable1.getCellEditor().cancelCellEditing();
    // HERE DO THE DELETE ROW OPERATION
    <yaman/>

  • Tricky problem in JTable

    Hi there,
    I am trying to make a JTable display the keyText of all the keys pressed, meaning if I write an "A" I want it to be shown as " shift + a ". Now I'm not quite sure about the way to handle the focus and how to trigger of the action that makes the editing textField receive the focus. Currently, when the table is called for the first time or when I switch between the fields, no modifier or actionKey can be displayed until the first keyTypedEvent. E.g when I press the a-key I get to be shown an "a". After having done This I get "Aa" or, having pressed the shift-key, "shift" and then "AA". The keyListener is added to the textField and as new instance to the table as well. Can anybody tell me, how to modify myKeyListener to directly focus the textField or give me any idea for a different approach of this problem?
    Thanks in advance, Bjorn
    package com.brain.keymap;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class MyKeyListener implements KeyListener{
        public MyKeyListener() {
            super();
        public void keyTyped(KeyEvent e) {
        public void keyPressed(KeyEvent e) {
            boolean focus = false;
            Component c, editor;
            int keyCode = e.getKeyCode();
            c = (Component) e.getSource();
            if (c instanceof InputTable) {
                InputTable tbl = (InputTable) c;
                editor = tbl.getEditorComponent();
                if (editor instanceof JTextField) {
                    ((JTextField) editor).setText(KeyEvent.getKeyText(keyCode));
                    e.consume();
            }else {
                if( c instanceof JTextField){
                    ((JTextField) c).setText(KeyEvent.getKeyText(keyCode));
                    e.consume();
        public void keyReleased(KeyEvent e) {
    }

    Hey scheide,
    thanks, it was the tip about consuming the consuming the keyStroke that solved it. I simply had to consume the keyTypedEvent. Now It all works fine. Just in case you might want to have a look at it, here's the code.
    public class MyKeyListener implements KeyListener{
        String input = "", temp;
        public MyKeyListener() {
            super();
        public void keyTyped(KeyEvent e) {
            e.consume();
        public void keyPressed(KeyEvent e) {
            createInput(e);
        public void keyReleased(KeyEvent e) {
        public void createInput(KeyEvent e){
            Component c, editor = null;
            int keyCode = e.getKeyCode();
            //disable focusTraversal except for tab and enter
            if (!(keyCode == KeyEvent.VK_ENTER || keyCode == KeyEvent.VK_TAB)){
                try{
                    editor.setFocusTraversalKeysEnabled(false);
                }catch(NullPointerException ex){}
            c = (Component) e.getSource();
            if (c instanceof InputTable) {
                InputTable tbl = (InputTable) c;
                editor = tbl.getEditorComponent();
                //focussing the table in field [0/0] at first call of table
                if (editor == null) {
                    try{
                        int row = tbl.getSelectedRow();
                        int column = tbl.getSelectedColumn();
                        if( row == -1 )
                            row = 0;
                        if( column == -1)
                            column = 0;
                        tbl.editCellAt(row , column );
                        editor = tbl.getEditorComponent();
                    }catch(Exception ex){}
                if( editor instanceof JTextField && !(keyCode == KeyEvent.VK_TAB || keyCode == KeyEvent.VK_ENTER )){
                    if (input == ""){
                        input = (KeyEvent.getKeyText(keyCode));
                        ((JTextField) editor).setText(input);
                        temp = input;
                    }else{
                        input = input.concat(" + ").concat(KeyEvent.getKeyText(keyCode));
                        ((JTextField) editor).setText(input);
                        temp = input;
                //when editing the input call of method editFieldValue
            }else if( c instanceof JTextField){
                ((JTextField) c).setText(editFieldValue(temp, e));
            //clear the inputString in case of tab or enter
            if(keyCode == KeyEvent.VK_TAB || keyCode == KeyEvent.VK_ENTER ){
                input = "";
        public String editFieldValue(String val, KeyEvent event){
            int code;
            String value = val;
            code = event.getKeyCode();
            StringTokenizer tokenizer;
            switch(code){
                case KeyEvent.VK_BACK_SPACE:
                    int count = 0;
                    tokenizer = new StringTokenizer(value,"+");
                    value = "";
                    while ( count < tokenizer.countTokens()){
                        value = value.concat("+").concat(tokenizer.nextToken());
                        count++;
                    break;
            return value;
    }Now I am trying to design a way to edit the input when the JTextfield has the focus. I don't really think I am trying in the right spot, since both the JTable and the TextField get different instances of the KeyListener.
    I guess, I'll try and make a different Listener for the Textfield.
    One more time thanks a lot for your help, Bjorn

  • MouseListener event and ComboBox actionlistener event problem

    Hi Guys,
    I use combo box to get diffrent tables from microsoft access database.
    The table will allow user to click on the cell and the data in the cell will be puting into a text field.
    My problem now is when i refresh the table to get another table, the new table will coming out, but the getSelectedRow()is pointed at the wrong direction. Instead of the row that i want, the getSelectedRow() give me the value of -1. I debug for many days already and still don'y know how to fix it......
    please help me guys.

    i think you will need to post some code to get an answer to this problem.
    Maybe this is a problem with references - creating a new table is bound to cause problems?

  • JTable RowSelection Problem

    Hello,
    I have a JTable with the ListSeletionModel as MULTIPLE_INTERVAL_SELECTION. My requirement includes the use of Date-Chooser frame with which I can select a date and set the date related fields in the JTable.(foreg:validfrom and validto).This date-choosing part is working fine,but my probelm is with the row selection.
    The situation should be :
    - Select a Row
    - If the column name is Validfrom or Validto,date-chooser pops up and date can be choosen.
    - set the date to the related cells after choosing in the JTable using setValueAt method...
    But, my problem is when I first Select a Row and click on the cells related to ValidFrom or ValidTo,the Date-chooser doesnt popup,instead when I first Select the cells whose columnname is either Validfrom or Validto,the date-chooser pops and I can set the dates and this row is now the selected row,
    But I want to first select a row and then select the column as validfrom or validto and let the date-chooser pop up and then set the date to these fields for the row selected initially.
    Here is the code:
            int cols = table.getColumnModel().getColumnCount();
            cells = new JTextField(20);      
            for (int i = 0; i < cols; i++) {
                TableColumn col = table.getColumnModel().getColumn(i);
                col.setCellEditor(new DefaultCellEditor(cells));
    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
                public Date date;
                public Date present;
                boolean test = true;
                String key = null;
                public void valueChanged(ListSelectionEvent e) { 
                    int selectedRow = table.convertRowIndexToModel(table.getSelectedRow());
                    int selectedColumn = table.convertColumnIndexToModel(table.getSelectedColumn());
                    int columns = table.getColumnModel().getColumnCount();
                    key = (String)table.getColumnModel().getColumn(selectedColumn).getHeaderValue();             
                    if (key.equalsIgnoreCase("ValidFrom") || (key.equalsIgnoreCase("ValidTo"))) {
                        String tmpDate = (String) table.getModel().getValueAt(selectedRow, selectedColumn);
                        if (tmpDate == null) {
                            Date today = new Date();
                            DATE_FORMAT.format(today);
                            this.date = today;
                            DATE_CHOOSER.setLocationRelativeTo(cells);
                            Date newDate = DATE_CHOOSER.select(this.date);
                            if (newDate == null) {
                                return;
                            cells.setText(DATE_FORMAT.format(newDate));
                            table.getModel().setValueAt(cells.getText(), selectedRow, selectedColumn);
                            table.columnSelectionChanged(e);
                        } else {
                            Date currentDate = UfisTime.getTimeStamp(tmpDate);
                            this.present = currentDate;
                            //   DATE_FORMAT.format(currentDate);
                            DATE_CHOOSER.setLocationRelativeTo(cells);
                            Date newDate = DATE_CHOOSER.select(this.present);
                            if (newDate == null) {
                                return;
                            cells.setText(DATE_FORMAT.format(newDate));
                            table.getModel().setValueAt(cells.getText(), selectedRow, selectedColumn);
                            table.columnSelectionChanged(e);
            });

    Thanks!
    Do you know of any way to get around it. I've tried requestFocus() without success. Did your answer mean that there is a problem with this method too?
    Magnus

  • JTable select problem

    Hello,
    I have a great problem with my JTable. I have a JTable with few lines and two columns. The user can select one line and with the following statements
    int column = tblSearchResults.getSelectedColumn();
    int row = tblSearchResults.getSelectedRow();     
    Object value = tblSearchResults.getValueAt(row,column);
    I retrieve the value with which I display details of a second line in a new window (when the user presses a certain button). The problem is when I close this new window and want to select a new line the getSelectedColumn and the getSelectedRow returns always -1 which says that no line is marked although I have marked a line.
    Does anybody know what the problem can be? - it must concern the open and close of the detail window, because when I omit the code line which opens the detail window and only make System.out.println's with the getSelectedColumn and getSelectedRow it will always output the right line...
    thx
    pat

    Swing related questions should be posted in the Swing forum.
    You have not provided enough information to solve your problem. We don't know how you are invoking the dialog. Are you double clicking on a row, do you have a button the user clicks on to invoke processing?
    So for this, and future postings, you should learn how to create a simple demo program that shows your problem so we don't have to guess what you are doing.

Maybe you are looking for