JTable klase tiek izmantota datu attēlošanai tabulas veidā. Tas sastāv no rindām un kolonnām.
JTabulas klases deklarācija
Apskatīsim deklarāciju klasei javax.swing.JTable.
Visbiežāk izmantotie konstruktori:
Konstruktors | Apraksts |
---|---|
JTable() | Izveido tabulu ar tukšām šūnām. |
JTable (Object[][] rindas, Object[] kolonnas) | Izveido tabulu ar norādītajiem datiem. |
Java JTable piemērs
import javax.swing.*; public class TableExample { JFrame f; TableExample(){ f=new JFrame(); String data[][]={ {'101','Amit','670000'}, {'102','Jai','780000'}, {'101','Sachin','700000'}}; String column[]={'ID','NAME','SALARY'}; JTable jt=new JTable(data,column); jt.setBounds(30,40,200,300); JScrollPane sp=new JScrollPane(jt); f.add(sp); f.setSize(300,400); f.setVisible(true); } public static void main(String[] args) { new TableExample(); } }
Izvade:
Java JTable piemērs ar ListSelectionListener
import javax.swing.*; import javax.swing.event.*; public class TableExample { public static void main(String[] a) { JFrame f = new JFrame('Table Example'); String data[][]={ {'101','Amit','670000'}, {'102','Jai','780000'}, {'101','Sachin','700000'}}; String column[]={'ID','NAME','SALARY'}; final JTable jt=new JTable(data,column); jt.setCellSelectionEnabled(true); ListSelectionModel select= jt.getSelectionModel(); select.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); select.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { String Data = null; int[] row = jt.getSelectedRows(); int[] columns = jt.getSelectedColumns(); for (int i = 0; i <row.length; i++) { for (int j="0;" < columns.length; j++) data="(String)" jt.getvalueat(row[i], columns[j]); } system.out.println('table element selected is: ' + data); }); jscrollpane sp="new" jscrollpane(jt); f.add(sp); f.setsize(300, 200); f.setvisible(true); pre> <p>Output:</p> <img src="//techcodeview.com/img/java-swing/64/java-jtable-2.webp" alt="JAVA Jtable 2"> <p>If you select an element in column <strong>NAME</strong> , name of the element will be displayed on the console:</p> <pre> Table element selected is: Sachin </pre></row.length;>