【问题标题】:table generation runtime and mouse click event with jtable使用 jtable 生成表运行时和鼠标单击事件
【发布时间】:2012-10-10 10:44:15
【问题描述】:

您好开发人员我在 jframe 中使用两个按钮和一个表格 当我单击按钮时,应生成具有不同行数的新表,并且在单击表行时,它应显示行数和列数 当我再次单击另一个按钮时,它应该创建具有新行数的新表 再次单击它时,它应该显示行号和列号

我正在使用以下代码。第一次创建表时,它会生成正确的结果,但是当再次创建表时,单击任何行会给出行号和列号 -1 。和数组索引超出范围异常我的代码有什么问题请帮助

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);
}

【问题讨论】:

  • 异常发生在哪里,在哪一行?在您的代码中用注释表明这一点。此外,考虑在您的问题中添加一些标点符号、段落等。目前,它真的很难阅读和理解。
  • 1) 您将两次 ActionListener 添加到 b1 按钮 2) 您将 MouseMotionListener 添加到您的表中,但只有一个 mouseClicked 方法 3) 您每次都在向容器中添加新表单击按钮而不重新验证 4)您的代码是否有效?
  • 这只是你的代码的一部分,你应该发布更多

标签: java swing event-handling jtable mouseevent


【解决方案1】:

此示例还有一些其他问题,但要解决您当前的问题,您需要获取 MouseEvent 的来源并对其进行操作:

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);
}

问题出在您的ActionListener 中,您正在将table 重新分配给一个新表(没有选择任何行)。因此,如果您单击第一个表,它仍然会在第二个表(没有选择任何行)上执行它的操作。

【讨论】:

    猜你喜欢
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    • 1970-01-01
    • 1970-01-01
    • 2014-05-29
    • 1970-01-01
    • 2012-03-21
    相关资源
    最近更新 更多