JTable wyświetlanie idneksu zaznaczonej pozycji

0

Witam nie mogę sobie poradzić aby moja tabela zwracała index wyświetlonej pozycji w momencie kliknięcia na tą pozycję. Proszę o pomoc
Oto mój kod

 import java.awt.Dimension;
import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;


public class table extends JFrame {
	
	public table(){
		JTable table;
		setLayout(new FlowLayout());
		
		
	
		
	table = new JTable(new MyTableModel());
	int x = table.getSelectedRow();
	JLabel info = new JLabel(Integer.toString(x));
	
	table.setPreferredScrollableViewportSize(new Dimension(500,50));
	table.setFillsViewportHeight(true);
	JScrollPane scrollPane = new JScrollPane(table);
	
	add(scrollPane);
	add(info);
	}
	
	public class MyTableModel  extends AbstractTableModel {
		String[] kolumny = {"Imie", "Nazwisko", "Miasto"};
		Object[][] dane ={
			{"Karol", "Rudzin", "Warszawa"},
			{"Marcin", "Pawlowski", "Gliwice"},
			{"Anna", "Forma", "Katowice"}
		};
		@Override
		public int getColumnCount() {
			 return kolumny.length;
		}
		@Override
		public int getRowCount() {
			return dane.length;
		}
		public String getColumnName(int col) {
	        return kolumny[col];
	    }
		@Override
		public Object getValueAt(int rowIndex, int columnIndex) {
			// TODO Auto-generated method stub
			return dane[rowIndex][columnIndex];
		}
		
		
	}
	public static void main(String[] args) {
		table tablica = new table();
		tablica.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		tablica.setVisible(true);
		tablica.setSize(600, 200);
		
	}
	}
	


0

Tabela nie jest metodą (funkcją), nie może więc niczego zwracać. Napisz jaśniej o co Ci chodzi.

0

Wywal zmienne lokalne i daj jako prywatne:

private JTable table = null;
private JLabel info = null;

W konstruktorze natomiast:

	        table.getSelectionModel().addListSelectionListener(
	        		new ListSelectionListener(){
						@Override
						public void valueChanged(ListSelectionEvent arg0) {
							info.setText(Integer.toString(table.getSelectedRow()));
						}
	        });

możesz też ustawić single selection w modelu bo teraz jak zaznaczysz dwa wiersze zwróci indeks pierwszego zaznaczonego

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