John
John

Reputation: 43

Display the item name on the table in a JLabel

I want to put the name of the item that I selected in a JTable in a JLabel that every time that i click a new item in the table the text in the JLabel also change can someone tell me what should I learn in java to produce that?

Upvotes: 0

Views: 463

Answers (2)

Elist
Elist

Reputation: 5533

You should know very basic Swing programming, and a little deeper understanding of a TableModel, SelectionModel and ListSelectionListener (which is the key to your goal).

A working example:

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class TableSelectionToLabel {
    private static JTable t = new JTable(new String[][]{{"1,1", "1,2"}, {"2,1", "2,2"}}, 
                            new String[]{"1", "2"});
    private static JLabel l = new JLabel("Your selction will appear here");
    private static JFrame f = new JFrame("Table selection listener Ex.");
    private static ListSelectionListener myListener = new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            int col = t.getColumnModel().getSelectionModel().getLeadSelectionIndex();
            int row = t.getSelectionModel().getLeadSelectionIndex();
            try {
                l.setText(t.getModel().getValueAt(row, col).toString());
            } catch (IndexOutOfBoundsException ignore) {

            }
        }
    };

    public static void main(String[] args) {
        t.getSelectionModel().addListSelectionListener(myListener);
        t.getColumnModel().getSelectionModel().addListSelectionListener(myListener);
        f.getContentPane().add(t, BorderLayout.NORTH);
        f.getContentPane().add(l, BorderLayout.CENTER);
        f.pack();
        f.setVisible(true);
    }
}

EDIT:

I modified the code to listen to both selection events from the model AND the column model to get a more accurate outcome.

Upvotes: 2

tbodt
tbodt

Reputation: 16987

First create the JLabel:

JLabel label = new JLabel();

Then add a listener to the table for selections:

table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent event) {
        label.setText(table.getValueAt(table.getSelectedRow(), table.getSelectedColumn()));
    }
});

Upvotes: 1

Related Questions