0

此应用程序从文本文件中提取数据并将其插入到JTable. 如果Observer文件发生更改并重新加载数据,则每 300 毫秒检查一次。我的班上有setChanged()and 。notifyObservers()Observer

当数据被添加到表中时,agetRowCount()报告该行已添加,通知器正在运行。几乎所有东西都在工作,除了repaint(). 我已经尝试过revalidate()fireTableDataChanged()但都无济于事。我将不胜感激这方面的一些帮助。整个过程不报告编译错误。

表模型

package HardwareDbFile;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.swing.table.AbstractTableModel;

public class HardwareFileTableModel extends AbstractTableModel{
    protected Vector data;
    protected Vector columnNames ;
    protected String datafile;

    public HardwareFileTableModel(String file){
        datafile = file;
        initVectors();  
    }

    public void initVectors() {
        String aLine ;
        data = new Vector();
        columnNames = new Vector();
        try {
            FileInputStream fin =  new FileInputStream(datafile);
            try (BufferedReader br = new BufferedReader(new InputStreamReader(fin))) {
                StringTokenizer st1 = new StringTokenizer(br.readLine(), "|");
                while(st1.hasMoreTokens()) {
                    columnNames.addElement(st1.nextToken());
                }
                // extract data
                while ((aLine = br.readLine()) != null) {
                    StringTokenizer st2 = new StringTokenizer(aLine, "|");
                    while(st2.hasMoreTokens()) {
                        data.addElement(st2.nextToken());
                    }
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    public int getRowCount() {
        return data.size() / getColumnCount();
    }

    @Override
    public int getColumnCount(){
        return columnNames.size();
    }

    @Override
    public String getColumnName(int columnIndex) {
        String colName = "";

        if (columnIndex <= getColumnCount()) {
            colName = (String)columnNames.elementAt(columnIndex);
        }
        return colName;
    }

    @Override
    public Class getColumnClass(int columnIndex){
        return String.class;
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return false;
    }


    public Object getValueAt(int rowIndex, int columnIndex) {
        return (String)data.elementAt( (rowIndex * getColumnCount()) + columnIndex);
    }


    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
    }
}

观察者类

package HardwareDbFile;

import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.Timer;

 public class HardwareFileObserver extends Observable implements ActionListener {
     Timer time = new Timer(300,this); // check every 300ms
     long lastModified;
     String file ;

     HardwareFileObserver (String string) {
         file = string;
         File f = new File(file);
         lastModified = f.lastModified(); // original timestamp
         time.start();
     }

     @Override
     public void actionPerformed(ActionEvent e) {
         File f = new File(file);
         long actualLastModified = f.lastModified();
         if (lastModified != actualLastModified) {
             // the file have changed
             lastModified = actualLastModified;
             setChanged();
             notifyObservers();
         }
     }
}

主班

    public class HardwareInventoryUI extends javax.swing.JFrame implements Observer {

    private String datafile = "hardware.dat";
    private String dataFilePath = "C:\\Windows\\Temp\\hardware.dat";
    protected HardwareFileTableModel model;

    /**
     * Creates new form HardwareInventoryUI
     */
    public HardwareInventoryUI() {
        initComponents();

        model = new HardwareFileTableModel(dataFilePath);
        HardwareFileObserver  fileWD;

        // this Observable object is monitoring any file change
        fileWD = new HardwareFileObserver(dataFilePath);
        fileWD.addObserver(this);
    }

    @Override
    public void update(Observable o, Object arg) {
        // reload data because data file have changed
        model.initVectors();
        jTable.repaint();
    }

添加录制按钮

    private void jAddRecordActionPerformed(java.awt.event.ActionEvent evt) {                                           

        String toolID = jToolID.getText();
        String toolName = jToolName.getText();
        String quantity = jQuantity.getText();
        String itemPrice = jItemPrice.getText();
        try {
            model = new HardwareFileTableModel(dataFilePath);
            FileWriter fstream = new FileWriter(dataFilePath, true);
            try (BufferedWriter newRecord = new BufferedWriter(fstream)) {
                newRecord.newLine();
                newRecord.write(toolID + "|"+ toolName + "|" + quantity + "|" + itemPrice );
            }
        } catch (IOException ex) {
            Logger.getLogger(HardwareInventoryUI.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
4

1 回答 1

2
  1. TableModel应该实施Observer,而不是您的观点。在update()方法中,更新datafireTableDataChanged(). AJTable监听它TableModel并自动更新自身作为响应。

  2. 还要考虑这里提到的观察者模式的替代实现。

  3. 如此处所示,您的实现setValueAt()不正确。您需要触发将通知监听表更改的事件:

    @Override
    public void setValueAt(Object value, int row, int column) {
        // update data
        fireTableCellUpdated(row, column);
    }
    
  4. 如果您的内容datafile可以作为命令的标准输出获得,您可以使用此处概述的方法消除该文件。

附录:正如@kleopatra 评论的那样,“请注意,使用表现良好的模型,您无需考虑视图更新,它们只是自动发生 :-) 或者反过来:如果手动重绘视图(例如表、树、列表)似乎是一个解决方案,模型实现不正确。”

于 2012-12-02T03:39:54.530 回答