Home > Enterprise >  Why getSelectedRow( ) method don't return the index of the selected row?
Why getSelectedRow( ) method don't return the index of the selected row?

Time:12-15

I use the method getSelectedRow() to get the index of the selected row in the first table. When I use it again to get the index of the selected row in the second table it still returns the index of the selected row in the first table. I can't figure out why!

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Selection extends JFrame {

    int row;
    String actualArray;
    JPanel panel = new JPanel();
    JPanel dialogPanel = new JPanel();
    DefaultTableModel model1 = new DefaultTableModel();
    DefaultTableModel model2 = new DefaultTableModel();
    JTable table1 = new JTable(model1);
    JTable table2 = new JTable(model2);
    JScrollPane scrollPane1 = new JScrollPane(table1);
    JScrollPane scrollPane2 = new JScrollPane(table2);
    JButton showSelectedRow = new JButton("Show");
    JButton switchTable = new JButton("switch");
    JDialog dialog = new JDialog();
    JLabel label = new JLabel();

    String [] columns = {"ID","Name"};
    String [][] array1 = {{"0001","Alice"},{"0002","Evanka"},{"0003","Steve"}};
    String [][] array2 = {{"0004","David"},{"0005","Mario"},{"0006","Marry"}};

    public Selection() {
        createAndShowGUI();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Selection();
            }
        });

    }

    private void createAndShowGUI() {
        model1.setDataVector(array1,columns);
        model2.setDataVector(array2,columns);
        panel.setBounds(15,20,500,480);
        scrollPane1.setBounds(20,25,50,50);
        scrollPane2.setBounds(20,25,50,50);
        showSelectedRow.setBounds(40,160,60,25);
        switchTable.setBounds(120,160,60,25);
        actions();
        panel.add(scrollPane1);
        actualArray="array1";
        panel.add(showSelectedRow);
        panel.add(switchTable);
        add(panel);
        setSize(550, 500);
        setLocation(230, 70);
        setLayout(null);
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    private void actions() {
        showSelectedRow.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                    if (actualArray.equals("array1")) {
                       row =table1.getSelectedRow();
                    } else {
                       row =table2.getSelectedRow();
                    }
                    showDialog();
            }
        });
        switchTable.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (actualArray.equals("array1")) {
                    panel.removeAll();
                    panel.add(scrollPane1);
                    actualArray = "array2";
                    panel.add(showSelectedRow);
                    panel.add(switchTable);
                    add(panel);
                    repaint();
                } else {
                    panel.removeAll();
                    panel.add(scrollPane2);
                    actualArray = "array1";
                    panel.add(showSelectedRow);
                    panel.add(switchTable);
                    add(panel);
                    repaint();
                }
            }
        });

    }
        private void showDialog() {
            dialogPanel.setBounds(5,5,50,30);
            label.setText(String.valueOf(row));
            label.setBounds(10,10,180,20);
            dialogPanel.add(label);
            dialog.add(dialogPanel);
            dialog.setSize(60, 50);
            dialog.setLocation(450, 250);
            dialog.setLayout(null);
            dialog.setResizable(false);
            dialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
            dialog.setVisible(true);
        }

    }

CodePudding user response:

I think your logic is backwards here...

When actualArray equals "array1", you're adding scrollPane1 and setting actualArray to "array2" ... shouldn't you be adding scrollPane2?

if (actualArray.equals("array1")) {
    panel.removeAll();
    panel.add(scrollPane1);
    actualArray = "array2";
    panel.add(showSelectedRow);
    panel.add(switchTable);
    add(panel);
    repaint();
} else {
    panel.removeAll();
    panel.add(scrollPane2);
    actualArray = "array1";
    panel.add(showSelectedRow);
    panel.add(switchTable);
    add(panel);
    repaint();
}

Having said that, I "accidentally" fixed you code trying to repair the null layout issues.

This example makes use of a CardLayout to switch between the tables instead...

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;

public class FixMe extends JFrame {

    int row;
    String actualArray;
    JPanel panel = new JPanel();
    JPanel dialogPanel = new JPanel();
    DefaultTableModel model1 = new DefaultTableModel();
    DefaultTableModel model2 = new DefaultTableModel();
    JTable table1 = new JTable(model1);
    JTable table2 = new JTable(model2);
    JScrollPane scrollPane1 = new JScrollPane(table1);
    JScrollPane scrollPane2 = new JScrollPane(table2);
    JButton showSelectedRow = new JButton("Show");
    JButton switchTable = new JButton("switch");
    JDialog dialog = new JDialog();
    JLabel label = new JLabel();

    String[] columns = {"ID", "Name"};
    String[][] array1 = {{"0001", "Alice"}, {"0002", "Evanka"}, {"0003", "Steve"}};
    String[][] array2 = {{"0004", "David"}, {"0005", "Mario"}, {"0006", "Marry"}};

    public FixMe() {
        createAndShowGUI();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new FixMe();
            }
        });

    }

    private CardLayout cardLayout;

    private void createAndShowGUI() {
        setLayout(new BorderLayout());

        label.setBorder(new EmptyBorder(16, 16, 16, 16));
        label.setHorizontalAlignment(JLabel.CENTER);

        dialog.add(label);

        cardLayout = new CardLayout();
        panel.setLayout(cardLayout);

        model1.setDataVector(array1, columns);
        model2.setDataVector(array2, columns);
        actions();
        actualArray = "array1";
        panel.add(scrollPane1, "array1");
        panel.add(scrollPane2, "array2");

        JPanel actions = new JPanel(new GridBagLayout());
        actions.add(showSelectedRow);
        actions.add(switchTable);

//        panel.add(showSelectedRow);
//        panel.add(switchTable);
        add(panel);
        add(actions, BorderLayout.SOUTH);
        pack();
        setLocationRelativeTo(null);
//        setSize(550, 500);
//        setLocation(230, 70);
//        setLayout(null);
//        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    private void actions() {
        showSelectedRow.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (actualArray.equals("array1")) {
                    row = table1.getSelectedRow();
                } else {
                    row = table2.getSelectedRow();
                }
                showDialog();
            }
        });
        switchTable.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (actualArray.equals("array1")) {
//                    panel.removeAll();
//                    panel.add(scrollPane1);
                    actualArray = "array2";
                    cardLayout.show(panel, actualArray);
//                    panel.add(showSelectedRow);
//                    panel.add(switchTable);
//                    add(panel);
//                    repaint();
                } else {
//                    panel.removeAll();
//                    panel.add(scrollPane2);
                    actualArray = "array1";
                    cardLayout.show(panel, actualArray);
//                    panel.add(showSelectedRow);
//                    panel.add(switchTable);
//                    add(panel);
//                    repaint();
                }
            }
        });

    }

    private void showDialog() {
        label.setText(String.valueOf(row));
        dialog.pack();
        dialog.setLocationRelativeTo(panel);
        dialog.setVisible(true);
//        label.setBounds(10, 10, 180, 20);
//        dialogPanel.add(label);
//        dialog.add(dialogPanel);
//        dialog.setSize(60, 50);
//        dialog.setLocation(450, 250);
//        dialog.setLayout(null);
//        dialog.setResizable(false);
//        dialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
//        dialog.setVisible(true);
    }

}

I recommend having a read through of Laying Out Components Within a Container

Now, having said all that, I would recommend just switching the models...

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {

                String[] columns = {"ID", "Name"};
                String[][] array1 = {{"0001", "Alice"}, {"0002", "Evanka"}, {"0003", "Steve"}};
                String[][] array2 = {{"0004", "David"}, {"0005", "Mario"}, {"0006", "Marry"}};

                TableModel model1 = new DefaultTableModel(array1, columns);
                TableModel model2 = new DefaultTableModel(array2, columns);

                JFrame frame = new JFrame();
                frame.add(new TestPane(new TableModel[]{model1, model2}));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JTable table;
        private TableModel[] models;
        private int currentModel = 0;
        private JLabel selectedRowLabel;

        public TestPane(TableModel[] models) {
            setLayout(new BorderLayout());
            table = new JTable();

            this.models = models;
            table.setModel(models[0]);

            setLayout(new BorderLayout());
            add(new JScrollPane(table));

            selectedRowLabel = new JLabel("...");

            JButton switchButton = new JButton("Switch");
            switchButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    currentModel  = 1;
                    if (currentModel >= models.length) {
                        currentModel = 0;
                    }
                    table.setModel(models[currentModel]);
                    updateSelectionInformation();
                }
            });

            JPanel infoPane = new JPanel(new GridBagLayout());
            infoPane.add(switchButton);
            infoPane.add(selectedRowLabel);

            add(infoPane, BorderLayout.SOUTH);

            table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
                @Override
                public void valueChanged(ListSelectionEvent e) {
                    updateSelectionInformation();
                }
            });
        }

        protected void updateSelectionInformation() {
            if (table.getSelectedRow() > -1) {
                selectedRowLabel.setText(Integer.toString(table.getSelectedRow()));
            } else {
                selectedRowLabel.setText("---");
            }
        }

    }
}

Now, if the previously selected row is important, simply keep track of it when you switch and re-apply it, for example...

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {

                String[] columns = {"ID", "Name"};
                String[][] array1 = {{"0001", "Alice"}, {"0002", "Evanka"}, {"0003", "Steve"}};
                String[][] array2 = {{"0004", "David"}, {"0005", "Mario"}, {"0006", "Marry"}};

                TableModel model1 = new DefaultTableModel(array1, columns);
                TableModel model2 = new DefaultTableModel(array2, columns);

                JFrame frame = new JFrame();
                frame.add(new TestPane(new TableModel[]{model1, model2}));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JTable table;
        private TableModel[] models;
        private int[] lastSelectedRow;
        private int currentModel = 0;
        private JLabel selectedRowLabel;

        public TestPane(TableModel[] models) {
            setLayout(new BorderLayout());
            table = new JTable();

            lastSelectedRow = new int[models.length];
            Arrays.fill(lastSelectedRow, -1);

            this.models = models;
            table.setModel(models[0]);

            setLayout(new BorderLayout());
            add(new JScrollPane(table));

            selectedRowLabel = new JLabel("...");

            JButton switchButton = new JButton("Switch");
            switchButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    lastSelectedRow[currentModel] = table.getSelectedRow();
                    currentModel  = 1;
                    if (currentModel >= models.length) {
                        currentModel = 0;
                    }
                    table.setModel(models[currentModel]);
                    if (lastSelectedRow[currentModel] > -1) {
                        table.setRowSelectionInterval(lastSelectedRow[currentModel], lastSelectedRow[currentModel]);
                    }
                    updateSelectionInformation();
                }
            });

            JPanel infoPane = new JPanel(new GridBagLayout());
            infoPane.add(switchButton);
            infoPane.add(selectedRowLabel);

            add(infoPane, BorderLayout.SOUTH);

            table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
                @Override
                public void valueChanged(ListSelectionEvent e) {
                    updateSelectionInformation();
                }
            });
        }

        protected void updateSelectionInformation() {
            if (table.getSelectedRow() > -1) {
                selectedRowLabel.setText(Integer.toString(table.getSelectedRow()));
            } else {
                selectedRowLabel.setText("---");
            }
        }

    }
}
  • Related