adesh kumar
adesh kumar

Reputation: 129

table generation runtime and mouse click event with jtable

Hello Developers i am using two buttons and a table in jframe when i click on a button new table with different no of rows should be generated and and while clicking on rows of table it should display the no of rows and columns again when i click on another button it should create the new table with new no of rows and while clicking on it again it should display the row no and column no

I am using the following code for it. First time on table creation it generates the correct result but when the table is created again then on clicking any row it gives the row no and column no -1 . and array index out of bounds exception whats wrong in my code plz help

JTable table;
JScrollPane jsp;
Button b1 = new JButton("1");
Button b2 = new JButton("2");
add(b1);
add(b2);
b1.addActionListener (this);
b1.addActionListener (this);

public void actionPerformed(ActionEvent ae) {
    int i = 0;
    if (ae.getActionCommand().equals("1")) {
        i = 1;
    }
    if (ae.getActionCommand().equals("2")) {
        i = 2;
    }
    String title[] = {""};
    Object obj[][] = new Object[i][1];
    table = new JTable(obj, title);
    jsp = new JScrollPane(table);
    add(jsp);
    table.addMouseMotionListener(this);
}

public void mouseClicked(MouseEvent me) {
    // first time it returns the true result but on new table creation 
    //i and j are returned -1 .
    int i = table.getSelectedRow();
    int j = table.getSelectedColumn();
    System.out.println("i is" + i);
    System.out.println("j is" + j);
}

Upvotes: 1

Views: 1356

Answers (1)

Nick Rippe
Nick Rippe

Reputation: 6465

There's a few other problems with this example, but to solve your immediate problem, you need to get the source of the MouseEvent and do your operations on that:

public void mouseClicked(MouseEvent me) {
    // first time it returns the true result but on new table creation 
    //i and j are returned -1 .
    JTable table = (JTable)me.getSource();
    int i = table.getSelectedRow();
    int j = table.getSelectedColumn();
    System.out.println("i is" + i);
    System.out.println("j is" + j);
}

The problem was in your ActionListener you were reassigning table to a new table (which doesn't have any row selected). So if you click on the first table, it's still going to do it's operations on the second table (which doesn't have any row selected).

Upvotes: 1

Related Questions