Java 如何检查是否选择了一行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24500048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:36:39  来源:igfitidea点击:

How can i check to see if a row has been selected?

javaif-statementjtableindexoutofboundsexceptionselected

提问by

I have a button click event on which i am getting a column value, if a Tablerow is selected. But if i don't select the row and click the button i get the error: java.lang.ArrayIndexOutOfBoundsException:-1my question is how can i check to see if a row has been selected pseudocode: if(Row == selected) { execute }

如果Table选择了一行,我有一个按钮单击事件,我将在该事件上获取列值。但是,如果我不选择行并单击按钮,java.lang.ArrayIndexOutOfBoundsException:-1则会出现错误:我的问题是如何检查是否选择了一行伪代码:if(Row == selected) { execute }

java code i have:

我有Java代码:

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try 
        {
            int row = Table.getSelectedRow();
            String Table_click = (Table.getModel().getValueAt(row, 0).toString());            

           //... implementation hire   

        } catch (Exception e) 
        {
            JOptionPane.showMessageDialog(null, e);
        }        
    }  

Thank you for your help.

感谢您的帮助。

采纳答案by MarsAtomic

Stop and think logically about your problem before you're tempted to post. Take a break from coding if you need to -- once you take a break, the solution to the problem often presents itself in short order.

在你想发帖之前停下来并合乎逻辑地思考你的问题。如果需要,请从编码中休息一下——一旦休息一下,问题的解决方案通常会在短时间内出现。

int row = Table.getSelectedRow();

if(row == -1)
{
    // No row selected
    // Show error message
}
else
{
    String Table_click = (Table.getModel().getValueAt(row, 0).toString());
    // do whatever you need to do with the data from the row
}

回答by Davie Brown

if row > -1 then you know a row has been selected. see: http://docs.oracle.com/javase/7/docs/api/javax/swing/JTable.html#getSelectedRow()

如果 row > -1 则您知道已选择一行。见:http: //docs.oracle.com/javase/7/docs/api/javax/swing/JTable.html#getSelectedRow()

回答by gilly3

When no row is selected, getSelectedRow()returns -1.

当没有选择行时,getSelectedRow()返回-1

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
   try {
      int row = Table.getSelectedRow();
      if (row > -1) {
         String Table_click = (Table.getModel().getValueAt(row, 0).toString());
         //... implementation here
      }
   }
   catch (Exception e) {
      JOptionPane.showMessageDialog(null, e);
   }
}