JTable with ListSelectionListener and getSelectedRow

The getSelectionRow () returns an integer value of the selected row .

Program

dsdsd

 

 

 

Program Source

import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
import java.awt.Dimension;
import java.awt.FlowLayout;

class Frame extends JFrame implements ListSelectionListener{
  
    private JTable jt;
    private JTextArea ta;
    private ListSelectionModel ls;
    private String[] heading = {"Rank","Name","Country","Rating"};
    private String[][] data = {{"1" ,"V.Kohli"        ,"INDIA"       ,"881"},
                           {"2" ,"A.B De villiers","SOUTH AFRICA","872"},
                           {"3" ,"G.J Bailey"     ,"AUSTRALIA"   ,"856"},
                           {"4" ,"H.M Amla"       ,"SOUTH AFRICA","840"},
                           {"5" ,"K.C Sangakkara" ,"SRI LANKA"   ,"833"},
                           {"6" ,"M.S Dhoni"      ,"INDIA"       ,"783"},
                           {"7" ,"I.J.L Trott"    ,"ENGLAND"     ,"725"},
                           {"8" ,"S Dhawan"       ,"INDIA"       ,"723"},
                           {"9" ,"T.M Dilshan"    ,"SRI LANKA"   ,"717"},
                           {"10","Misbah-ul-Haq"  ,"PAKISTAN"    ,"715"},};
    
    Frame()
    {
        setTitle("JTable with ListSelectionListener");
        setLayout(new FlowLayout());
        setJTable();
        setJTextArea();
        setAction();
        setSize(700,350);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    
    private void setJTable()
    {
        jt = new JTable(data,heading);
        JScrollPane js = new JScrollPane(jt);
        js.setPreferredSize(new Dimension(400,150));
        add(js);
    } 
    
    private void setJTextArea()
    {
        ta = new JTextArea();
        JScrollPane js = new JScrollPane(ta);
        js.setPreferredSize(new Dimension(400,150));
        add(js);
    }
    
    private void setAction()
    {
        ls = jt.getSelectionModel();
        ls.addListSelectionListener(this);
    }
    
    public void valueChanged(ListSelectionEvent eve)
    {
        int getRow = jt.getSelectedRow();
        for(int column=0;column<4;column++)
        {
            ta.append(data[getRow][column]+"------");
        }
        ta.append("n");
    }
}

public class Javaapp {
   
    public static void main(String[] args) {
        
       Frame fr = new Frame();
    }
}

Leave a Comment