【问题标题】:How to Check Jtable Values in IF Condition With For Loop如何使用 For 循环检查 IF 条件下的 Jtable 值
【发布时间】:2014-01-30 02:56:36
【问题描述】:

我的代码仅适用于第一行。如果它不在 JTable 中,我想添加一行。 Class_assing_tb 是我的 JTable。

当我单击“添加项目”按钮时,我想将从 JCombobox 获得的值添加到 JTable。它最多只能输入 4 个项目。我想这样做,如果我添加一个已经在 J​​Table 中的项目,我想给出一条消息“Denied”,否则将该项目添加到 JTable。

int count = Class_assing_tb.getRowCount();
if (count == 0) {
    addrow(); //this is to Command For Add new Row
} else if (count == 4) {
    System.out.println("maximum Row Count");
    // msg ****** Maximum Classes
} else {
    int a = Class_assing_tb.getRowCount();
    DefaultTableModel tm2 = (DefaultTableModel) Class_assing_tb.getModel();
    loop:
    for (int i = 0; i < a; i++) {
        //System.out.println("Row Count is" + a);
        // System.out.println("Sttate is"+i);
        if (tm2.getValueAt(i, 0).equals(mng_stu_classatnd.getSelectedItem()) & tm2.getValueAt(i, 2).equals(mng_stu_batch.getSelectedItem()) & tm2.getValueAt(i, 3).equals(mng_stu_type.getSelectedItem())) {
            System.out.println("Denied");
            break loop;
        } else {
            addrow();//this is to Command For Add new Row
            // continue loop;
        }
    }
}

【问题讨论】:

  • 请详细说明您的问题和代码。
  • 我想将从 Jcombobox 获取的值添加到 Jtable 当我单击“添加项目”按钮时,它只能输入最多 4 个项目,我想这样做,如果我添加已经添加的项目Jtable 我想给一条消息“拒绝”否则将项目添加到 jtable
  • “最多只能输入4个项目” - 究竟是什么“项目”?它是一个完整的行吗?它只是连续一个单元格吗?每行有多少个单元格?
  • 无关:请学习java命名约定并遵守。

标签: java swing loops


【解决方案1】:

试试这样的:

//全局声明

private Vector<Vector<String>> data; //used for data from database
private Vector<String> header; //used to store data header

//在表单加载时只显示标题

//create header for the table
header = new Vector<String>();
header.add("Column"); 
model=new DefaultTableModel(data,header);
table = new JTable(model);

//在actionPerformed()中

public void actionPerformed(ActionEvent ae){
    if(ae.getSource()==add){
    int count=table.getRowCount();
    for(int i=1;i<=count;i++){
    if(table.getValueAt(i,0).equals(jComboBox.getSelectedItem())){
           JOptionPane.showMessageDialog((Component) null,"Duplicate...");
           return;
    }
    }

    if(count==4){
           JOptionPane.showMessageDialog((Component) null,"Maximum Limit is crossed...");
    }else{
     Object d= jComboBox.getSelectedItem();
     model.addRow(d);
    }

}
}

【讨论】:

  • 您应该在答案中添加更多解释。尽管您的答案可能有效,但它并没有告诉读者他们做错了什么以及如何纠正错误。或者,如果您采用与 OP 完全不同的方法,仍然要在代码中解释您在做什么。它可以提供更好的答案:)
  • @peeskillet 好的,谢谢。我明白了,你想说什么。下次我也会注意解释部分。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-12
  • 1970-01-01
相关资源
最近更新 更多