-1

I'm writing a simple MySQL editor. My problem is that after I select from the combobox a new table from the database and load it and then select a row and try to delete it, getSelectedRow() returns -1 and generates an exception, but that doesn't happen when I delete a row from the table that is loaded at the start of my program.

Here's the crucial code parts from 2 files (in the same code quote):

package omnisql;

import java.sql.*;
import java.util.*;

public class getData 
{
static Connect c = new Connect();

static GUI g = new GUI();

static ResultSet result;

public static Vector<Vector<String>> data = new Vector<Vector<String>>();

public static String table="pracownicy";

public static Vector <String> d;

public static List <String> id;

    void getData() throws SQLException
    {       
        result=c.stmt.executeQuery("select * from "+table);

        id = new ArrayList<String>();

            while(result.next())
            {
            d=new Vector<String>();

            id.add(result.getString("id"));

            d.add(result.getString("id"));
            d.add(result.getString("Nazwisko"));
            d.add(result.getString("Imię"));
            d.add(result.getString("Płeć"));
            d.add(result.getString("Ulica"));
            d.add(result.getString("Miejscowość"));
            d.add(result.getString("Kod_pocztowy"));
            d.add(result.getString("Województwo"));
            d.add(result.getString("Telefon"));

            data.add(d);
            }
    } 
    }



package omnisql;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.*;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.util.*;
    import javax.swing.event.*;


    public class GUI extends JFrame implements ActionListener, TableModelListener
    {
    static Connect c = new Connect();

    static getData gd = new getData();

JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT,10,5));
JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.LEFT,10,5));
JPanel panel2 = new JPanel(new FlowLayout(FlowLayout.CENTER,10,5));
JPanel panel3 = new JPanel(new FlowLayout(FlowLayout.LEFT,10,5));

JLabel typbazy = new JLabel("Typ bazy: ");
JLabel wybtab = new JLabel("Wybierz tabelę: ");

JRadioButton postgre = new JRadioButton("PostgreSQL");
JRadioButton mysql = new JRadioButton("MySQL");
JRadioButton sqlite = new JRadioButton("SQLite");

ButtonGroup grupa = new ButtonGroup();

public static JComboBox tabela = new JComboBox();

JButton addrec = new JButton("Dodaj rekord");
JButton delrec = new JButton("Usuń rekord");
JButton reftab = new JButton("Odśwież tabelę");

JTable table;

public static DefaultTableModel model;

TableColumn column;

Vector<String> headers = new Vector<String>();

JScrollPane scroll;

static int rownumber,addrow,delrow,updaterow;       

PreparedStatement pst;

String value="";

public static int height,i,firstrow=0, klick=1;

public GUI()
{  

   panel.add(typbazy);

   grupa.add(postgre);
   panel.add(postgre);
   postgre.addActionListener(this);

   grupa.add(mysql);
   panel.add(mysql);
   mysql.setSelected(rootPaneCheckingEnabled);
   mysql.addActionListener(this);

   grupa.add(sqlite);
   panel.add(sqlite);
   sqlite.addActionListener(this);

   panel1.add(wybtab);
   panel1.add(tabela);

   tabela.setPreferredSize(new Dimension(120,20));
   tabela.setBackground(Color.white);
   tabela.removeAllItems();
   tabela.addItem(" ");
   tabela.addItem("Pracownicy");
   tabela.addItem("Pracownicy 2");
   tabela.setSelectedIndex(0);
   tabela.addActionListener(this);

   headers.add("ID");
   headers.add("Nazwisko");
   headers.add("Imię");
   headers.add("Płeć");
   headers.add("Ulica");
   headers.add("Miejscowość");
   headers.add("Kod_pocztowy");
   headers.add("Województwo");
   headers.add("Telefon");

   model = new DefaultTableModel(gd.data, headers);
   table = new JTable(model);
   table.setRowSelectionAllowed(true);  
   table.getModel().addTableModelListener(this); 
   table.setPreferredScrollableViewportSize(new Dimension(740,159));

   column = table.getColumnModel().getColumn(0);
   column.setPreferredWidth(20);

   column = table.getColumnModel().getColumn(1);
   column.setPreferredWidth(100);

   column = table.getColumnModel().getColumn(2);
   column.setPreferredWidth(70);

   column = table.getColumnModel().getColumn(3);
   column.setPreferredWidth(70);

   column = table.getColumnModel().getColumn(4);
   column.setPreferredWidth(100);

   column = table.getColumnModel().getColumn(5);
   column.setPreferredWidth(100);

   column = table.getColumnModel().getColumn(6);
   column.setPreferredWidth(100);

   column = table.getColumnModel().getColumn(7);
   column.setPreferredWidth(100);

   column = table.getColumnModel().getColumn(8);
   column.setPreferredWidth(80);

   scroll = new JScrollPane(table);
   panel2.add(scroll);

   panel3.add(addrec);
   addrec.addActionListener(this);
   panel3.add(delrec);
   delrec.addActionListener(this);
   panel3.add(reftab);
   reftab.addActionListener(this);

   getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
   getContentPane().add(panel);
   getContentPane().add(panel1);
   getContentPane().add(panel2);
   getContentPane().add(panel3);  

}     

void initGUI()        
{
    setSize(800,340);        
    setTitle("OmniSQL 1.0");
    setResizable(false);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public void tableChanged(TableModelEvent e) 
{
       rownumber = table.getSelectedRow();

       if (rownumber==-1) rownumber=0;

       updaterow = Integer.parseInt(gd.id.get(rownumber));

       switch (e.getType())
       {

       case TableModelEvent.UPDATE:
       table.getRowCount(); 
       value=table.getValueAt(table.getSelectedRow(),table.getSelectedColumn()).toString();

       try
       {   
       pst = c.con.prepareStatement("UPDATE "+gd.table+" SET "+table.getColumnName(table.getSelectedColumn())+" = '"+value+"' where id = "+updaterow+";");
       pst.executeUpdate();
       }
       catch (SQLException err)
       {
       }
       break;   
       }
}


 public void actionPerformed(ActionEvent e)
 {

    /*if (e.getActionCommand().equals("MySQL"))
    {
        try
        { 
        c.con.close();    
        c.connect("jdbc:mysql://localhost:3306/omnisql","root","sqlek","com.mysql.jdbc.Driver");
        }
        catch (ClassNotFoundException er) 
        {
        }
        catch(SQLException err)
        {
        }
    }*/

      if (tabela.getSelectedItem()=="Pracownicy")
     { 
        gd.table="pracownicy";

        try 
        {
        model.setRowCount(0);
        table.removeAll();   
        gd.getData();
        }

        catch (SQLException er) 
        {
        }
    }

     if (tabela.getSelectedItem()=="Pracownicy 2")
     { 

       gd.table="pracownicy2";
       try 
        {


        model.setRowCount(0);

        gd.getData();
        table.revalidate();

        }

        catch (SQLException er) 
        {

        }
    }

      /*if(postgre.isSelected())
      {
      tabela.removeAllItems();
      tabela.addItem("Adresy");
      tabela.addItem("Adresy 2");
      tabela.setSelectedIndex(0);
      }
      */
      /*if(mysql.isSelected())
      {
      tabela.removeAllItems();
      tabela.addItem(" ");
      tabela.addItem("Pracownicy");
      tabela.addItem("Pracownicy 2");
      }*/
     /*
      if(sqlite.isSelected())
      {
      tabela.removeAllItems();
      tabela.addItem("Zakłady");
      tabela.addItem("Zakłady 2");
      tabela.setSelectedIndex(0);
      }*/


    if (e.getActionCommand().equals("Dodaj rekord")) 
    {
        model.setRowCount(gd.id.size());
        rownumber = model.getRowCount()-1;

        if(rownumber==-1 && gd.id.size()==0)
        {
        rownumber=0;
        gd.id.add(0, "1");
        addrow=Integer.parseInt(gd.id.get(rownumber));
        }
        else
        {
        addrow=Integer.parseInt(gd.id.get(rownumber));
        addrow++;
        }

        try
        {     
        pst = c.con.prepareStatement("INSERT INTO "+gd.table+" (id) VALUES("+addrow+")");
        pst.executeUpdate();  
        model.setRowCount(0);
        gd.getData();
        height = (int)table.getPreferredSize().getHeight();
        table.scrollRectToVisible(new Rectangle(0,height,10,10));
        }

         catch (SQLException exc)
         {

         }    
    }

      rownumber=table.getSelectedRow();


    if (e.getActionCommand().equals("Usuń rekord")) 
    {
        try
        {

        model.setRowCount(gd.id.size());

        System.out.println(rownumber);

        delrow = Integer.parseInt(gd.id.get(rownumber));

        pst = c.con.prepareStatement("DELETE from "+gd.table+" where id="+delrow);
        pst.executeUpdate();
        model.setRowCount(0);
        gd.getData();
        }

        catch (SQLException exc)
        {

        }

    }

    if (e.getActionCommand().equals("Odśwież tabelę")) 
    {
    try
    {    
    model.setRowCount(0);
    gd.getData();
    }
    catch (SQLException exc)
         {

         }    
    }
}
}

I will be really grateful for any help with this problem.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Archer
  • 35
  • 3
  • 7
  • 3
    Unrelated to your current problem, but it will solve a different problem in your code: Read [How do I compare strings in Java](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – jlordo Jan 15 '13 at 11:45
  • 1
    This is a massive wall of code. A small example that demonstrates the same problem would be much more helpful. – Dennis Jan 15 '13 at 11:51

1 Answers1

2

If getSelectedRow() returns -1 that means that nothing is selected.

Archer
  • 5,073
  • 8
  • 50
  • 96
  • Then what does mean the fact that on the default table which I load at the start getSelectedRow() returns proper values, but when I load a new table from my database then it returns -1 as if no row was selected, but in fact it is selected. – Archer Jan 15 '13 at 11:49
  • I think once you load new data into `JTable` selection is reset. – Archer Jan 15 '13 at 11:50
  • It should be reset, but it's not. – Archer Jan 15 '13 at 11:58
  • Could you try to manually select an item after you load new data from table. Does exception still exist? – Archer Jan 15 '13 at 11:59
  • I don't quite understand what you mean by selecting manually. Problem occurs when I select the second table from the combobox. New data is loaded. I click on the row that I want to delete and press the delete button in my program. Then I get the exception. I even get the error when I reload the default table from the combobox. – Archer Jan 15 '13 at 12:06