2017-02-10 119 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