javauser-interfaceswingjtablebeans-binding

Java Swing: How to bind a JLabel's text to a column in the selected row of a JTable?


I am using Netbeans and am trying to find a way for the IDE to auto-generate the code for me. I remember binding a JLabel's text to a column in the selected row of the JTable before, but in that case, the JTable's values were from an entity manager, and it was very easy. I was wondering if there is a way to do it even if the JTable is not tied to a database.

Also, how else could one do it? I was thinking of implementing a ListSelectionListener, and whenever an event got generated, just update the text of the label.


Solution

  • I think your second solution is best way to do it, something like this:

    public class LabelSyncer implements ListSelectionListener {
    
        private JLabel toSync;
        private int columnIndex;
    
        public LabelSyncer(JLabel toSync, int columnIndex) {
    
        }
    
        public void valueChanged(ListSelectionEvent e) {
            JTable table = (JTable) e.getSource();
            int row = table.getSelectedRow();
            toSync.setText(table.getModel().getValueAt(row, columnIndex).toString());
        }
    }
    

    and then

    table.getSelectionModel().addListSelectionListener(new LabelSyncer(label, columnIndex));
    

    Something like this. Probably a more generic solution, but this should work.