2017-02-10 109 views
0

我正在构建使用JTable和DefaultTableModel的Java桌面应用程序。如何通过索引删除行

现在,我已经实现了此表的KeyEventListener。因此,如果我尝试点击我的键盘上的CANC按钮,我想删除选定的行。但有这种奇怪的行为。

这是我的第一个表:

enter image description here

现在我选择了倒数第二排,然后我按下键盘上的取消按钮。这是结果

enter image description here

正如你所看到的,删除了倒数第二排,但没有刷新JTable的。

这是evetListener:

public class KeyListenerTableFattura extends KeyAdapter { 
     private JTable table2; 
     private MyTableModelFatturaManuale tableModel; 

     public KeyListenerTableFattura(JTable table2) { 
      this.table2 = table2; 
      this.tableModel = (MyTableModelFatturaManuale)table2.getModel(); 
     } 

     public void keyReleased (KeyEvent ke) { 
      if (table2.getSelectedColumn() == 0) { 
       //tasto canc 
       if (ke.getKeyCode() == 127) { 
        try{ 
         int riga= table.getSelectedRow(); 
         ListSelectionModel selectionModel = table.getSelectionModel(); 
         selectionModel.setSelectionInterval(0,0); 
         tableModel.rimuoviSpesa(riga);  

        } 
        catch(Exception e) 
        { 
         log.logStackTrace(e); 
        } 
       } 
      } 

     } 
     @SuppressWarnings("unused") 
     private void printIt(String title, KeyEvent keyEvent) { 

     } 

    } 

这是TableModel的

package com.mcsolution.commercialista.table.tableModel; 

import java.util.ArrayList; 
import java.util.List; 
import java.util.Vector; 

import com.mcsolution.commercialista.beans.FatturaRighe; 
import com.mcsolution.common.supporto.VisualMessage; 



public class MyTableModelFatturaManuale extends defaultTableModel{ 


    /** 
    * 
    */ 
    private static final long serialVersionUID = -3163597322286902696L; 
    public List<FatturaRighe> v = new ArrayList<FatturaRighe>(); 
    public static String[] ColName = {"Descrizione","Importo"}; 
    private Double percEnpaCL=0.0,percIva=0.0,perRitenuta=0.0; 
    private Double imponibileIva =0.0,empaCL=0.0,iva=0.0,ritenutaAcconto=0.0,lordo=0.0,netto=0.0, 
      totale=0.0; 

    private int rigaParziale =7; 
    private int rigaEnpaCl =6; 
    private int rigaImponibileIva =5; 
    private int rigaIva =4; 
    private int rigaRitenuta =3; 
    private int rigaTotaleLordo =2; 
    private int rigaNetto =1; 
    private int rigaTotale =0; 
    public MyTableModelFatturaManuale() { 
     super(ColName,0); 
    } 

    @SuppressWarnings("rawtypes") 
    public void inserisciRigheFisse(){ 
     this.addRow(new Vector()); 
     super.setValueAt("PARZIALE", this.getRowCount()-1, 0); 
     super.setValueAt("0,00", this.getRowCount()-1, 1); 
     this.addRow(new Vector()); 
     super.setValueAt("ENPACL 0 %", this.getRowCount()-1, 0); 
     super.setValueAt("0,00", this.getRowCount()-1, 1); 
     this.addRow(new Vector()); 
     super.setValueAt("IMPONIBILE I.V.A.", this.getRowCount()-1, 0); 
     super.setValueAt("0,00", this.getRowCount()-1, 1); 
     this.addRow(new Vector()); 
     super.setValueAt("I.V.A. 0 %", this.getRowCount()-1, 0); 
     super.setValueAt("0,00", this.getRowCount()-1, 1); 
     this.addRow(new Vector()); 
     super.setValueAt("RIT.ACCONTO 0 %", this.getRowCount()-1, 0); 
     super.setValueAt("0,00", this.getRowCount()-1, 1); 
     this.addRow(new Vector()); 
     super.setValueAt("TOTALE LORDO", this.getRowCount()-1, 0); 
     super.setValueAt("0,00", this.getRowCount()-1, 1); 
     this.addRow(new Vector()); 
     super.setValueAt("NETTO", this.getRowCount()-1, 0); 
     super.setValueAt("0,00", this.getRowCount()-1, 1); 
     this.addRow(new Vector()); 
     super.setValueAt("TOTALE", this.getRowCount()-1, 0); 
     super.setValueAt("0,00", this.getRowCount()-1, 1); 
    } 

    public void settaSpesa(FatturaRighe f){ 
     this.v.add(f); 
     int riga = this.getRowCount()-1; 
     this.insertRow(riga, new Vector()); 
     super.setValueAt(f.getDescrizione(), riga, 0); 
     super.setValueAt("0.00", riga, 1); 
    } 

    private Integer getCountSpeseTaxFree(){ 
     int cont=0; 
     for (FatturaRighe object : this.v) { 
      if(!object.getSoggettoIVA()) 
       cont++; 
     } 
     return cont; 
    } 


    public void settaEnpaCl(Double enpa){ 
     this.percEnpaCL=enpa; 
     //modifico l'enpaCL 
     super.setValueAt("ENPACL "+this.percEnpaCL+" %", this.getRowCount()-1-rigaEnpaCl-getCountSpeseTaxFree(), 0); 
     calcolaTotale(); 
    } 

    public void settaIva(Double iva){ 
     this.percIva=iva; 
     //modifico l'enpaCL 
     super.setValueAt("I.V.A. "+this.percIva+" %", this.getRowCount()-1-rigaIva-getCountSpeseTaxFree(), 0); 
     calcolaTotale(); 
    } 

    public void settaRitenuta(Double ritenuta){ 
     this.perRitenuta=ritenuta; 
     //modifico l'enpaCL 
     super.setValueAt("RIT.ACCONTO "+this.perRitenuta+" %", this.getRowCount()-1-rigaIva-getCountSpeseTaxFree(), 0); 
     calcolaTotale(); 
    } 

    public boolean isCellEditable(int rowIndex, int columnIndex) { 
     //verifico quante solo le righe della tabella 
     int righeEsentiIva = getCountSpeseTaxFree(); 
     int righeIva = this.v.size() - righeEsentiIva; 
     //se è l'ultima riga non si modifica 
     if(rowIndex == this.getRowCount()-1) //metto il meno uno perchè a contare si paprte dallo 0 
      return false; 
     else if(rowIndex < righeIva) 
      return true; 
     else if(rowIndex >= righeIva+7 && rowIndex < this.getRowCount()) 
      return true; 
     return false; 

    } 
    public void inserisciRiga(){ 
     FatturaRighe f = new FatturaRighe(); 
     f.setImporto(0.00); 
     f.setSoggettoIVA(true); 
     this.v.add(0,f); 
     this.insertRow(0, new Vector()); 
     super.setValueAt("", 0, 0); 
     super.setValueAt("0.00", 0, 1); 
    } 

    public void rimuoviRiga(){ 
     //conto il numero di righe presenti 
     int righeEsistenti = this.v.size() - getCountSpeseTaxFree(); 
     if(righeEsistenti >0){ 
      this.v.remove(0); 
      this.removeRow(0); 
      calcolaTotale();  
     } 
    } 

    public void rimuoviSpesa(int nRiga){ 
     //conto il numero di righe presenti 
     int righeIvaEsente = getCountSpeseTaxFree(); 
     if(righeIvaEsente<=0) 
      return; 
     this.removeRow(nRiga); 
     //mi vado a calcolare nella lista dove si trova questa riga 
     int nPosizioneInLista = nRiga - 7; 
     this.v.remove(nPosizioneInLista); 
     calcolaTotale();  
    } 


    @Override 
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) { 
     try{ 
      //verifico se la riga è già esistente oppure va modificata 
      //altero il valore di rowIndex perchè ci sono le 6 righe fisse 
      int rigaIniziale = rowIndex; 
      if(rowIndex >7) 
       rowIndex = rowIndex-7; 
      FatturaRighe f = rowIndex< this.v.size() ? this.v.get(rowIndex) : null; 
      if(f==null){ 
       f = new FatturaRighe(); 
       f.setSoggettoIVA(true); 
       //mi calcolo quante spese ci sono 
       int spese = getCountSpeseTaxFree(); 
       if(spese>0){ 
        this.v.add(rowIndex-spese,f); 
       }else 
        this.v.add(f); 
      } 
      if(columnIndex==0){ 
       //descrizion 
       f.setDescrizione(aValue.toString()); 
      }else if(columnIndex==1){ 
       //importo 
       try{ 
        Double importo = Double.parseDouble(aValue.toString()); 
        f.setImporto(importo); 
       }catch(Exception e){ 
        VisualMessage.getErrore(); 
       }    
      } 

      super.setValueAt(f.getDescrizione(), rigaIniziale>7 ? rigaIniziale : rowIndex, 0); 
      super.setValueAt(f.getImporto(), rigaIniziale>7 ? rigaIniziale : rowIndex, 1); 

      calcolaTotale(); 
     }catch(Exception e){ 
      log.logStackTrace(e); 
     } 
    } 

    public void calcolaTotale(){ 
     try{ 
      Double parziale=0.0; 
      Double totaleSpese=0.0; 
      for (FatturaRighe fattura : this.v) { 
       if(fattura.getSoggettoIVA()==true){ 
        parziale += fattura.getImporto()!=null ? fattura.getImporto() : 0.00; 
       }else 
        totaleSpese += fattura.getImporto()!=null ? fattura.getImporto() : 0.00; 
      } 
      empaCL=parziale*this.percEnpaCL/100; 
      imponibileIva = parziale + empaCL; 
      iva = imponibileIva*percIva/100; 
      ritenutaAcconto= parziale*perRitenuta/100; 
      lordo = imponibileIva+iva; 
      netto = lordo-ritenutaAcconto; 
      totale = netto+ totaleSpese; 
      int righeSenzaTasse = getCountSpeseTaxFree(); 
      //io so che l'ultima riga conterrà sempre il parziale 
      super.setValueAt(decimalFormatter.format(parziale), this.getRowCount()-1-rigaParziale-righeSenzaTasse, 1); 
      super.setValueAt(decimalFormatter.format(empaCL), this.getRowCount()-1-rigaEnpaCl-righeSenzaTasse, 1); 
      super.setValueAt(decimalFormatter.format(imponibileIva), this.getRowCount()-1-rigaImponibileIva-righeSenzaTasse, 1); 
      super.setValueAt(decimalFormatter.format(iva), this.getRowCount()-1-rigaIva-righeSenzaTasse, 1); 
      super.setValueAt(decimalFormatter.format(ritenutaAcconto), this.getRowCount()-1-rigaRitenuta-righeSenzaTasse, 1); 
      super.setValueAt(decimalFormatter.format(lordo), this.getRowCount()-1-rigaTotaleLordo-righeSenzaTasse, 1); 
      super.setValueAt(decimalFormatter.format(netto), this.getRowCount()-1-rigaNetto-righeSenzaTasse, 1); 
      //super.setValueAt("TOTALE", this.getRowCount()-1-rigaTotale, 0); 
      super.setValueAt(decimalFormatter.format(totale), this.getRowCount()-1-rigaTotale, 1); 
     }catch(Exception e){ 
      log.logStackTrace(e); 
      VisualMessage.getErrore(); 
     } 

    } 



    public Class<Float> getColumnClass(Float columnIndex) { 
     return Float.class; // Le due colonne sono numeri interi 
    } 

    @SuppressWarnings("rawtypes") 
    public void stampaTabella(List<FatturaRighe> v){ 
     int i=0; 
     this.v=v; 
     Double totale=0.0; 
//  for(Iterator<FatturaText> it=v.iterator(); it.hasNext();){ 
//   FatturaText fattura =it.next(); 
//   this.addRow(new Vector()); 
//   super.setValueAt(fattura.getCodFattura(), i,0); 
//   super.setValueAt(fattura.getDataFormattata(), i,1); 
//   if(fattura.getCliente()!=null) 
//    super.setValueAt(fattura.getCliente().getRagioneSociale(), i,2); 
//   
//   super.setValueAt(decimalFormatter.format(fattura.getTotale())+" €", i, 3); 
//   totale+=fattura.getTotale(); 
//   i++; 
//  } 
     this.addRow(new Vector()); 
     super.setValueAt("TOTALE", i, 0); 
     super.setValueAt(decimalFormatter.format(totale)+" €", i, 3); 
    } 
} 
+1

如果您需要更多帮助,请发布适当的[mcve]。我们对您的仅显示问题的应用程序代码不感兴趣。所以你只需要用DefaultTableModel创建一个带有JTable的框架。不需要自定义TableModel来演示问题。 – camickr

回答

1

我已经实现了这个表的KeyEventListener。所以,如果我尝试单击我的键盘上的按键CANC,我想删除所选行

什么做KeyListener和按钮上“点击”与彼此呢?

当你点击一个按钮,你应该添加一个ActionListener到按钮来处理一个事件。

如果(ke.getKeyCode()== 127)所有的

首先,你不应该使用的KeyListener监听的KeyEvent进行。如果你确实使用听众,那么不要使用魔术数字,没有人知道“127”是什么。请使用KeyEvent API中定义的变量。例如:KeyEvent.VK_A。

在任何情况下,您遇到的问题是JTable将在收到任何KeyEvent时将单元置于编辑模式。

如果您需要对特殊的KeyStroke进行特殊处理,那么您应该使用Key Bindings。然后KeyStroke通过绑定进行处理,编辑器将不会被调用。

阅读有关How to Use Key Bindings的Swing教程的部分以获取更多信息和示例。请注意,您在设置密钥绑定时将使用WHEN_ANCESTOR_OF_FOCUSED_COMPONENT InputMap

+0

感谢您的回复,但是您能否给我一个实用的例子? – bircastri

+0

@bircastri,教程有示例代码。这[链接](https://tips4java.wordpress.com/2008/10/10/key-bindings/)试图简单地创建一个绑定所需的基本代码。你所需要做的就是编写Action。该论坛还充满了使用密钥绑定的例子。如果你需要更多的帮助,然后发布一个适当的[mcve],显示你的尝试。整个班级将大约20行代码。几行创建框架,另一对创建一个表和几个关键绑定。 “MCVE”的意义在于学习一个概念,然后将这个概念应用到你的代码中。 – camickr