import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;

public class Calistir extends JFrame implements ActionListener {
     JTable jtb;
     DefaultTableModel dtm;
     JTextField[] jtext;
     String[] baslik= {"Ekle","Sil"};
	public Calistir() {
		this.setTitle("JTable Kullanımı");
		this.setSize(690,500);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setLayout(new FlowLayout());
		
		JPanel main_jpn=new JPanel();
		main_jpn.setPreferredSize(new Dimension(690,500));
		main_jpn.setLayout(new FlowLayout());
	    JPanel	jtb_jpn=new JPanel();
		jtb_jpn.setPreferredSize(new Dimension(600,300));
		JPanel jtext_jpn=new JPanel();
		jtext_jpn.setPreferredSize(new Dimension(400,60));
		
		String[] colum= {"Ad","Soyad","Yas","Sehir"};
	
		dtm=new DefaultTableModel();
		dtm.setColumnIdentifiers(colum);//Sutun baslıkları ayarlanıyor
		jtb=new JTable(dtm);
	
		JScrollPane jscp=new JScrollPane(jtb);//Kaydırma çubuğu
		jscp.setPreferredSize(new Dimension(400,300));
	
		jtext=new JTextField[colum.length];
		
		for(int i=0;i<jtext.length;i++) {
			
			jtext[i]=new JTextField();
			jtext[i].setPreferredSize(new Dimension(95,25));
            jtext_jpn.add(jtext[i]); 
		}
		for(int i=0;i<baslik.length;i++) {
			JButton btn=new JButton(baslik[i]);
			btn.setPreferredSize(new Dimension(95,25));
		    btn.addActionListener(this);
		    btn.setActionCommand(baslik[i]);
			jtext_jpn.add(btn);
		}
	 
		jtb_jpn.add(jscp);
		main_jpn.add(jtb_jpn);
		main_jpn.add(jtext_jpn);
		this.add(main_jpn);
		this.setVisible(true);
	}

 public static void main(String[] arg) {
	 new Calistir();
 }

@Override
public void actionPerformed(ActionEvent arg0) {
	
	switch(arg0.getActionCommand()) {
	
	case "Ekle":ekle();break;
	case "Sil":sil();break;
	
	}
}	
public boolean dogrula(JTextField[] jtxt) {
	
	int sayac=0;
	for(int i=0;i<jtxt.length;i++)
	{
		if(jtxt[i].getText().length()>0)
			sayac++;
	}
	if(sayac==jtxt.length)
		return true;
	else
		return false;
}
public int sayicevir(String s) {
	int sayi=0;
	try {
		sayi=Integer.parseInt(s);
		return sayi;
	}catch(Exception ex)
	{
		return -1;
	}
}
public void ekle() {
   	int yas=sayicevir(jtext[2].getText());
	if(dogrula(jtext)&&yas!=-1) {
	String[] veriler=new String[jtext.length];
	 for(int i=0;i<jtext.length;i++) {
		 veriler[i]=jtext[i].getText();
          jtext[i].setText("");    
	 }
	   dtm.addRow(veriler);//addRow fonksiyonu Dizi aldığı için    
	}
}
public void sil() {
	int secilen=jtb.getSelectedRow();//Secilen satir no
	if(secilen>-1)
	{
		dtm.removeRow(secilen);
	}	
}

}