1

I'd like to get my values in an array. Later I'd like to use the array in another class. How can this be done?

table.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 1) {
                    JTable target = (JTable) e.getSource();
                    int row = target.getSelectedRow();
                    int column = target.getSelectedColumn();

                    row = table.convertRowIndexToModel(row);
                    String val1 = (String) table.getModel().getValueAt(row, 0);
                    String val2 = (String) table.getModel().getValueAt(row, 1);
                    String val3 = (String) table.getModel().getValueAt(row, 2);
                    String val4 = (String) table.getModel().getValueAt(row, 3);
                    String val5 = (String) table.getModel().getValueAt(row, 4);

                    System.out.println(val1 + " " + val2 + " " + val3 + " " + val4 + " " + val5);
                }
            }
        }); 
3
  • Well, have you learned how to use arrays and loops? Commented Mar 20, 2017 at 19:15
  • You could try looking at the documentation. As for using in another class, you can simply pass the array reference to that class. Try looking here for more details. Commented Mar 20, 2017 at 19:19
  • I'm learning right now. I used an array in another context. But in this case I'm not sure what I should do. Any help appreciated. Commented Mar 20, 2017 at 19:28

2 Answers 2

1

Instantiate a new array with the size of the values you are going to add. If you do not know the size you should look into using ArrayList

String[] arr = new String[5];

Add values to the array. You could probably put this in a loop so the code will be less verbose.

String val1 = (String) table.getModel().getValueAt(row, 0);
arr[0] = val1;

String val2 = (String) table.getModel().getValueAt(row, 1);
arr[1] = val2;

...

then return the array

return arr; 
Sign up to request clarification or add additional context in comments.

Comments

1

Another way, with collections, they normally easier to work with:

List<String> values = new ArrayList<>();
values.add((String) table.getModel().getValueAt(row, 0))
..
..
values.add((String) table.getModel().getValueAt(row, 4););

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.