JTable - odświeżanie - temat po raz n-ty

0

Witam.
Mam problem z odświeżaniem tabeli. Wiem że temat był już na forum poruszany niestety nie rozwiązało to mojego problemu.
Mam taki kod

 
//insert do bazy
if (e.getSource()==okButton)
		{
			System.out.println("ok");
			try {
				Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
				conn = DriverManager.getConnection(url,user,password);	
				Statement ps = conn.createStatement();
				ps.executeUpdate(sqlinsert.toString());
                                // tutaj chciałbym odświeżyć table aby widać było dane po insercie
                                

			        
			    
		    
	
			} catch (Exception e2) {
				System.out.println(e2);
			}
		
		}

niestety kiedy wywołuje

km.fireTableDataChanged()

pojawia mi się komunikat
java.lang.IndexOutOfBoundsException: Index: -1, Size: 979
Nie mam pojęcia z czego to wynika.
Dane dodaje do bazy i do listy modelu
Niestety nic mi to nie daję.
Bardzo proszę o pomoc.
Pozdrawiam

ps.
Cały kod bez mojego kombinowania.


public class Window extends JFrame implements ListSelectionListener , ActionListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * 
	 */
	
	private JTextField lastNameField;
	private JTextField firstNameField;
	private JTextField telephoneField;
	private JTextField roomField;
	private JTextField emailField;
	private JTextField descriptionField;
	
	private JTextField idField;
	private JTextField idDivisionField;
	private JTextField divisionField;
	
	private JButton okButton;
	private JButton cancelButton;
	
	private static final StringBuilder sqlselect = new StringBuilder("select CustomerId, CustomerLastName, CustomerFirstName, CustomerEmail, CustomerTelephone, CustomerDivision,DivisionFullName, CustomerDescription, CustomerRoom from ITD.dbo.Customers left join ITD.dbo.Divisions on CustomerDivision=DivisionId order by CustomerId desc");
	
	
	
	
	private String user="";
	private String password="";
	private String url ="jdbc:sqlserver:";
	private Connection conn = null;
	private ResultSet rs = null;
	private List<TabelaWBazie> listaDoModelu = new LinkedList<TabelaWBazie>();
	private QueryTableModel km = new QueryTableModel();
	private JTable table = new JTable(km);
	private JScrollPane scrollpane = new JScrollPane(table);
	
	
	
	
	
	
	public Window (){
		super("Lista użytkowników");
		JFrame ramka = new JFrame();
		ramka.setSize(1000,500);
		ramka.setDefaultCloseOperation(EXIT_ON_CLOSE);
		ramka.setVisible(true);
		JPanel p1 = new JPanel();
		JPanel p2 = new JPanel();
		JPanel p = new JPanel();
		JPanel p3 = new JPanel();
		p3.setLayout(new FlowLayout());
		
		ramka.add(p);
		p1.setLayout(new GridLayout(1,1));
		p2.setLayout(new GridLayout(5,4,0,10));
		p.setLayout(new GridLayout(2,1));
		//p.setSize(1000, 500);
		p.add(p1,BorderLayout.NORTH);
		p.add(p2);
	

		p2.add(new JLabel("ID: "));
		p2.add(idField = new JTextField());
		p2.add(new JLabel("Imię: "));
		p2.add(firstNameField = new JTextField());
		p2.add(new JLabel("Nazwisko: "));
		p2.add(lastNameField = new JTextField());
		p2.add(new JLabel("e-mail: "));
		p2.add(emailField = new JTextField());
		p2.add(new JLabel("Telefon: "));
		p2.add(telephoneField = new JTextField());
		p2.add(new JLabel("ID Wydziału: "));
		p2.add(idDivisionField = new JTextField());
		p2.add(new JLabel("Nazwa Wydziału: "));
		p2.add(divisionField = new JTextField());
		p2.add(new JLabel("Pokój: "));
		p2.add(roomField = new JTextField());
		p2.add(new JLabel("Opis: "));
		p2.add(descriptionField = new JTextField());
		okButton = new JButton("Zapisz");
		cancelButton = new JButton("Anuluj");
		
		p3.add(okButton);
		p3.add(cancelButton);
		p2.add(p3);
		okButton.addActionListener(this);
		cancelButton.addActionListener(this);
		table.setModel(km);
		table.setFillsViewportHeight(true);
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		scrollpane.add(table);
		scrollpane.setViewportView(table);
		scrollpane.setPreferredSize(new Dimension(300,200));
		p1.add(scrollpane);
		
		//getContentPane().add(p1,BorderLayout.NORTH);
	    //getContentPane().add(p2,BorderLayout.NORTH);
	    
		table.getSelectionModel().addListSelectionListener(this);
		
		
		
		
		
	    //sql select CustomerId, CustomerLastName, CustomerFirstName,  CustomerDivision, DivisionFullName from ITD.dbo.Customers left join ITD.dbo.Divisions on CustomerDivision=DivisionId;
		//StringBuilder sql = new StringBuilder("select CustomerId, CustomerLastName, CustomerFirstName, CustomerEmail, CustomerTelephone, CustomerDivision, CustomerDescription, CustomerRoom from ITD.dbo.Customers");
		//StringBuilder sqlselect = new StringBuilder("select CustomerId, CustomerLastName, CustomerFirstName, CustomerEmail, CustomerTelephone, CustomerDivision,DivisionFullName, CustomerDescription, CustomerRoom from ITD.dbo.Customers left join ITD.dbo.Divisions on CustomerDivision=DivisionId order by CustomerId desc");
		try {
			
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			conn = DriverManager.getConnection(url,user,password);			
			PreparedStatement ps = conn.prepareStatement(sqlselect.toString());
			rs = ps.executeQuery();
			while (rs.next()){
				TabelaWBazie r = new TabelaWBazie();
				r.setCustomerId(rs.getInt(1));
				r.setCustomerLastName(rs.getString(2));
				r.setCustomerFirstName(rs.getString(3));
				r.setCustomerEmail(rs.getString(4));
				r.setCustomerTelephone(rs.getString(5));
				r.setCustomerDivisionId(rs.getInt(6));
				r.setCustomerDivisionName(rs.getString(7));
				r.setCustomerDescription(rs.getString(8));
				r.setCustomerRoom(rs.getString(9));
				listaDoModelu.add(r);		
				
			}
			km.setData(listaDoModelu);
			km.fireTableDataChanged();
			rs.close();
			conn.close();
									
		}catch(SQLException e){
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void valueChanged(ListSelectionEvent e) {
		    if (e.getSource() == table.getSelectionModel() && table.getRowSelectionAllowed()) {
		      int first = table.getSelectedRow();		      		      
		      firstNameField.setText(km.getValueAt(first, 2).toString());
		      lastNameField.setText(km.getValueAt(first, 1).toString());
		      telephoneField.setText(km.getValueAt(first, 4).toString());
		      roomField.setText(km.getValueAt(first, 8).toString());
		      emailField.setText(km.getValueAt(first, 3).toString());
		      descriptionField.setText(km.getValueAt(first, 7).toString());
		      idField.setText(km.getValueAt(first, 0).toString());
		      idDivisionField.setText(km.getValueAt(first, 5).toString());
		      divisionField.setText(km.getValueAt(first, 6).toString());
		      
		      
		    } 
		    
	}
	
	public void actionPerformed(ActionEvent e){
		StringBuilder sqlinsert = new StringBuilder("INSERT INTO ITD.dbo.Customers(CustomerId,CustomerLastName,CustomerFirstName,CustomerEmail,CustomerTelephone,CustomerDivision,CustomerDescription,CustomerRoom) VALUES ((select MAX(CustomerId)+1 from ITD.dbo.Customers),'"+lastNameField.getText()+"','"+firstNameField.getText()+"','"+emailField.getText()+"','"+telephoneField.getText()+"',"+idDivisionField.getText()+",'"+descriptionField.getText()+"','"+roomField.getText()+"');"); 
		

		if (e.getSource()==okButton)
		{
			System.out.println("ok");
			try {
				Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
				conn = DriverManager.getConnection(url,user,password);	
				Statement ps = conn.createStatement();
				PreparedStatement ps1 = conn.prepareStatement(sqlselect.toString());
			    ps.executeUpdate(sqlinsert.toString());
			    
			    
			    
			    
				
				
			} catch (Exception e2) {
				System.out.println(e2);
			}
		
		}
		
		if (e.getSource()==cancelButton)
		{
			System.out.println("cancel");
		}
	}
		
	

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Window w = new Window();
		
	    //w.setVisible(true);
		
 	}
0

Jest to model.

public class QueryTableModel extends AbstractTableModel {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String[] colname={"CustomerId", "CustomerLastName", "CustomerFirstName", "CustomerEmail", "CustomerTelephone", "CustomerDivision","DivisionFullName", "CustomerDescription", "CustomerRoom"};
	private List<TabelaWBazie> data = new LinkedList<TabelaWBazie>();
	
	public QueryTableModel(){
		
	}
	public void setData(List<TabelaWBazie> listaDoModelu){
		this.data=listaDoModelu;
	}
	@Override
	public int getColumnCount() {
		// TODO Auto-generated method stub
		return colname.length;
	}

	@Override
	public int getRowCount() {
		// TODO Auto-generated method stub
		return data.size();
	}
	@Override
	public String getColumnName(int columnIndex) {
		// TODO Auto-generated method stub
		return colname[columnIndex].toString();
	}

	@Override
	public Object getValueAt(int row, int col) {
		TabelaWBazie r = (TabelaWBazie) data.get(row);
		switch(col){
		case 0:
			return r.getCustomerId();
		case 1:
			return r.getCustomerLastName();
		case 2:
			return r.getCustomerFirstName();
		case 3:
			return r.getCustomerEmail();
		case 4:
			return r.getCustomerTelephone();
		case 5:
			return r.getCustomerDivisionId();
		case 6:
			return r.getCustomerDivisionName();
		case 7:
			return r.getCustomerDescription();
		case 8:
			return r.getCustomerRoom();
		
		}
		// TODO Auto-generated method stub
		return null;
	}

}
0

Błąd jest zapewne tu:

public void valueChanged(ListSelectionEvent e) {
       if (e.getSource() == table.getSelectionModel() && table.getRowSelectionAllowed()) {
           int first = table.getSelectedRow();                                            
           firstNameField.setText(km.getValueAt(first, 2).toString());

Metoda valueChanged() jest wywoływana automatycznie po fireTableDataChanged(). Skąd wiesz, że po zmianie danych jakikolwiek wiersz jest selected (zaznaczony)? A jak nic nie jest zaznaczone, to getSelectedRow() zwraca -1.

0

Przepraszam że dopiero teraz odpisuję ale wcześniej nie dałem rady.
Nie za bardzo rozumiem o co Ci chodzi. Tzn rozumiem że wiersz może nie być zaznaczony ale tzn że mam zrobić do tego if 'a else i to jakoś oprogramować. Bo wydaje mi się że tak funkcja działa tzn wyświetla mi zaznaczony wpis z bazy i wszystko jest ok. Problem polega tylko na tym że dane w jtabel nie są automatycznie odświeżane tzn mając coś dodając coś o indeksie 100 ( korzystając z funkcji poniżej) mimo że to się doda do bazy i program nie zwróci żadnego błędu to jtable mi nie odświeża tego wpisu , dopiero restart programu to pokazuje.
Ta funkcja wykonuję się poprawnie.
Niestety kiedy do niej dodam wpis km.fireTableDataChanged(); aby odświeżyło mi dane po ich zapisaniu do bazy.
Wywala mi komunikat <B>java.lang.IndexOutOfBoundsException: Index: -1, Size: 493</B>

public void actionPerformed(ActionEvent e){
		StringBuilder sqlinsert = new StringBuilder("INSERT INTO ITD.dbo.Customers(CustomerId,CustomerLastName,CustomerFirstName,CustomerEmail,CustomerTelephone,CustomerDivision,CustomerDescription,CustomerRoom) VALUES ((select MAX(CustomerId)+1 from ITD.dbo.Customers),'"+lastNameField.getText()+"','"+firstNameField.getText()+"','"+emailField.getText()+"','"+telephoneField.getText()+"',"+idDivisionField.getText()+",'"+descriptionField.getText()+"','"+roomField.getText()+"');"); 
		

		if (e.getSource()==okButton)
		{
			System.out.println("ok");
			try {
				Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
				conn = DriverManager.getConnection(url,user,password);	
				Statement ps = conn.createStatement();
				
			        ps.executeUpdate(sqlinsert.toString());
			        km.fireTableDataChanged(); 
			    
			    
			    
				
				
			} catch (Exception e2) {
				System.out.println(e2);
			}
		
		}
		
		if (e.getSource()==cancelButton)
		{
			System.out.println("cancel");
		}
	}
/

Prosiłbym bym o pomoc ewentualnie o fragment kodu.
Pozdrawiam

0

Kolega Ci wszystko napisał:
wywołujesz metodę valueChanged() w której masz:

int first = table.getSelectedRow();

ta zmienna przyjmuje wartość -1 jeśli żaden wiersz nie jest zaznaczony a potem próbujesz odwołać się do listy

firstNameField.setText(km.getValueAt(first, 2).toString());

gdzie odwołujesz się do listy o indeksie -1
przed tym musisz sprawdzić czy zmienna first nie jest mniejsza od zera i odpowiednio zareagować na taką sytuację.

0

Bardzo dziękuję za pomoc.

1 użytkowników online, w tym zalogowanych: 0, gości: 1