繁体   English   中英

将文件中的值刷新到JTable

[英]Refreshing values from a File to a JTable

我正在尝试从文件刷新JTable值,以便可以在表中显示它们。 我有一个模型,但是我不知道为什么它不起作用。 我已经尝试了几乎所有我能想到的东西。 这是GUI和TableModel的代码:

public void itemStateChanged(ItemEvent event) 
    {
        if(event.getStateChange()== ItemEvent.SELECTED)
        {
            outputFile.filename= "C:\\File Database\\"+Dropdown.getSelectedItem();
            outputFile.ReadData();

            int count=0;
            System.out.println("Array list size:" +outputFile.filedata.size());
            for(int i=0; i< datafield1.getRowCount(); i++)
            {
                for(int j=0; j< datafield1.getColumnCount(); j++)
                {
                    fval= outputFile.filedata.get(count); 
                    count++; 
                    datafield1.setValueAt(fval,i,j);
                }
            }
        }

桌子型号:

import javax.swing.table.AbstractTableModel;

public class PreviousDataRefresh extends AbstractTableModel  
{

    private static final long serialVersionUID = 1L;
    float[][] rowData = new float[15][11]; 

    public int getColumnCount() 
    {
        return 11;
    }

    public int getRowCount() 
    {
        return 15;
    }

    public Object getValueAt(int rowIndex, int columnIndex) 
    {
        return null;
    }
     public boolean isCellEditable(int row, int col) 
     {
            //Note that the data/cell address is constant,
            //no matter where the cell appears onscreen.
            if (col < 2) {
                return false;
            } else {
                return true;
            }
     }
    public void setValueAt(Object value, int row, int col) 
    {
        rowData[row][col] = (Float) value;
        fireTableCellUpdated(row, col);
    }

}

ArrayList之所以有效,是因为每次我从ComboBox选择一个新文件时,我都会看到float值发生变化,但看不到它们被输入到表中。

Hej UP2ME4ME,

我为您制作了一个非常小而简单的示例JPanel ,其中包含一个JTable和一个JButton来加载另一个File

因此,这是带有JComboBox的更新后的JPanel的代码,用于选择文件

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JTable;
import swingdemoapp.table.model.LoadDataFromFileModel;
import swingdemoapp.table.model.MyComboBoxModel;

public class LoadDataFromFilePanel extends JPanel implements ActionListener {

    private JTable myTable;
    private LoadDataFromFileModel model;
    private JButton loadNewFile;
    private JComboBox selectFile;
    private MyComboBoxModel boxModel;
    private JFileChooser chooser;

    private final String USER_HOME  = System.getProperty("user.home");

    public LoadDataFromFilePanel(final File file) {

        this.setLayout(new BorderLayout(10, 10));
        this.setPreferredSize(new Dimension(800, 600));


        File[] files = new File[1];
        files[0] = new File("resources/file1.dat");

        selectFile = new JComboBox(files);
        selectFile.addActionListener(this);
        this.add(selectFile, BorderLayout.NORTH);


        model = new LoadDataFromFileModel(file);
        myTable = new JTable(model);

        this.add(myTable, BorderLayout.CENTER);

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource().equals(loadNewFile)) {
            chooser = new JFileChooser(new File(USER_HOME));
            int showOpenDialog = chooser.showOpenDialog(getParent());
            if(showOpenDialog == 0) {
                File selectedFile = chooser.getSelectedFile();
                model.updateTableData(selectedFile);
            }
        }

        if(e.getSource().equals(selectFile)) {
            File selectedFile = (File) selectFile.getSelectedItem();
            model.updateTableData(selectedFile);
        }
    }
}

TableModel,它包含一个类,这是我从文件中获取数据的域类

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author Patrick Ott <Patrick.Ott@professional-webworkx.de>
 * @version 1.0
 */
public class LoadDataFromFileModel extends AbstractTableModel {

    private final String[] columnNames = {"Firstname", "Lastname", "City"};
    private List<DataFromFile> data;

    public LoadDataFromFileModel(final File file) {
        data = readFile(file);
    }

    @Override
    public int getRowCount() {
        return data.size();
    }

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

    @Override
    public String getColumnName(int column) {
        return columnNames[column];
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        DataFromFile value = data.get(rowIndex);
        switch(columnIndex) {
            case 0:
                return value.getFirstName();
            case 1:
                return value.getLastName();
            case 2:
                return value.getCity();
        }

        return null;
    }

    private List<DataFromFile> readFile(final File file) {
        List<DataFromFile> data = new ArrayList<>();
        if(!file.isDirectory() && file.canRead()) {
            try {
                BufferedReader br = new BufferedReader(
                        new FileReader(file));
                String line = "";

                while((line = br.readLine()) != null) {
                    String[] split = line.split(",");
                    DataFromFile dff = new DataFromFile(split[0], split[1], split[2]);
                    data.add(dff);
                }
                System.out.println("Reading from file finished");
                br.close();
            } catch (FileNotFoundException ex) {
                Logger.getLogger(LoadDataFromFileModel.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(LoadDataFromFileModel.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            System.out.println("Sorry, i can not read your input file!");
        }

        return data;
    }

    public void updateTableData(final File file) {
        data = readFile(file);
        fireTableDataChanged();
    }
}


class DataFromFile {

    private String firstName;
    private String lastName;
    private String city;

    public DataFromFile(final String firstName, final String lastName, final String city) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.city = city;
    }

    /**
     * @return the firstName
     */
    public String getFirstName() {
        return firstName;
    }

    /**
     * @param firstName the firstName to set
     */
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    /**
     * @return the lastName
     */
    public String getLastName() {
        return lastName;
    }

    /**
     * @param lastName the lastName to set
     */
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    /**
     * @return the city
     */
    public String getCity() {
        return city;
    }

    /**
     * @param city the city to set
     */
    public void setCity(String city) {
        this.city = city;
    }
}

这是一个文本文件,我从该文件中读取名字,姓氏和城市名,这些文件由一个制表符分隔,稍后在readFile方法中将String拆分。

汉斯,梅耶,纽约卡尔,路易,加利福尼亚玛丽亚,莎拉波娃,迈阿密

希望对您有所帮助,并且您可以将其调整为适合您的应用程序。

帕特里克

这是我开始做任何事情之前未触及的所有代码,我知道这有点不干净,但这是因为我急于完成此项目...真的很抱歉

GUI主类:变量:

private static final long serialVersionUID = 1L; 
float fval=0; 
XBee xbee = new XBee();
XBeeResponse response; 
JFrame MainFrame;
JTextField OnOff;
JTable datafield0, datafield1;
JComboBox<String> Dropdown; 
Filer outputFile = new Filer(); 
XBeeDecoder decode = new XBeeDecoder();
CardLayout card = new CardLayout();
String[] FileNames = new File("C:/File Database/").list(); 
Queue<XBeeResponse> ConvertingQueue = new LinkedList<XBeeResponse>();
Queue<XBeeResponse> Rqueue = new LinkedList<XBeeResponse>(); 
DecimalFormat formatfloat = new DecimalFormat("0.000");
JButton XBee, Data, Graph, Pdata;

以前的数据面板:

public void MakePreviousDataPanel()
    {
        PdataBack.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        Dropdown = new JComboBox<String>(FileNames);
        Dropdown.addItemListener(this);
        gbc.gridy=0; 
        gbc.ipady=15;
        gbc.ipadx=30; 
        PdataBack.add(Dropdown,gbc);
        gbc.gridy=1;
        gbc.ipady=20; 
        PdataBack.add(CreateLabel("Accel X       Accel Y       Accel Z       Gyro X       Gryo Y       Gryo Z       Temp       Air Pressure       Alititude       Latitude       Longitude"), gbc);
        datafield1= new JTable(15,11);
        datafield1.setAutoscrolls(true);
        datafield1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        datafield1.setDragEnabled(true);
        datapanel1.setSize(700,500); 
        datapanel1.add(datafield1);
        gbc.gridy=2; 
        gbc.ipady=25;
        gbc.gridheight=1; 
        PdataBack.add(datafield1, gbc);
        gbc.gridy=3; 
        gbc.gridheight=1;
        gbc.ipady=10; 
        PdataBack.add(backbutton,gbc);
    }

执行的动作:

public void actionPerformed(ActionEvent event) 
    { 
            if(event.getSource() == XBee)
            {
                if(xbee.isConnected()==true)
                {
                    OpenCloseXBee(0);
                    OnOff.setText("XBee is Off");
                }
                else
                {
                    OpenCloseXBee(1);
                    OnOff.setText("XBee is On");
                }
            }
            if(event.getSource() == Data)
            {
                card.show(MainBack, "Data");
                //System.out.println("Values in queue: "+ ConvertingQueue.size());
                outputFile.responses.addAll(ConvertingQueue);   
                System.out.println("Responses in queue: "+ Rqueue.size());
                outputFile.filecounter= new File("C:/File Database/").listFiles().length;
                outputFile.filecounter++;
                outputFile.filename="C:/File Database/data"+outputFile.filecounter+".txt";
                outputFile.CreateFile();
                outputFile.ConvertToFloat();
                outputFile.WriteHeader();
                outputFile.WriteData();

                if(xbee.isConnected() == false)
                {
                    if(ConvertingQueue.isEmpty()==false)
                    {
                        for(int i=0; i< datafield0.getRowCount(); i++)
                        {
                            for(int j=0; j< datafield0.getColumnCount(); j++)
                            {
                                fval= decode.processfloat(ConvertingQueue.poll());
                                formatfloat.format(fval); 
                                datafield0.setValueAt(fval,i,j);
                            }
                        }
                    }   
                }
            }
            if(event.getSource() == Graph)
            {
                card.show(MainBack, "GraphBack");
            }
            if(event.getSource() == Pdata)
            {
                card.show(MainBack, "Previous Data");
            }
            if(event.getSource()==choose)
            {
                int showOpenDialog = chooseFile.showOpenDialog(getParent());
                if(showOpenDialog == 0) {
                    File selectedFile = chooseFile.getSelectedFile();
                    model.updateTableData(selectedFile);
                }
            }
            if(event.getSource()==back)
            {
                card.show(MainBack, "Main");
            }
        }

最后但并非最不重要的Filer类:

package com.rapplogic.xbee.examples.wpan;
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.rapplogic.xbee.api.*;


public class Filer 
{
    //Use PrintWriter to Open/Close File and use FileWriter to write/read to file
    String filename; 
    int filecounter;
    Queue<XBeeResponse> responses = new LinkedList<XBeeResponse>();
    LinkedList<Float> fvals = new LinkedList<Float>(); 
    ArrayList<Float> filedata = new ArrayList<Float>();
    DataOutputStream RunOutput;
    FileOutputStream Filewrite; 
    String newline = System.getProperty("line.separator");
    XBeeDecoder decode = new XBeeDecoder(); 
    File fileread; 
    Scanner Reader; 

    public Filer()
    {
        //filename = "C:/File Database/data"+filecounter;
    }
    public static void main (String[] args) throws IOException //Main Method Close the file here after operations finish 
    { 
        //Test Block DO NOT USE test block to only be used with file data0 
        Filer data = new Filer();
        data.filename= "C:/File Database/data12.txt";
        data.ReadData(); 
        //data.CreateFile(); 
        //data.WriteHeader();
        //data.WriteData();
        //data.RunOutput.close();

    }
    public void CreateFile()
    {
        try 
        {  
            this.Filewrite = new FileOutputStream(this.filename, false);
            this.RunOutput = new DataOutputStream(Filewrite); 
            System.out.println("File Created"); 
        } 
        catch (IOException e) 
        {
            System.out.println("File Not Opened/Not Created");
            System.out.println(e.getMessage());
        } 
    }
    public void ConvertToFloat()
    {       
        float fval=0;
        int size=responses.size(); 
        for(int i=0; i< size; i++)
        {
            fval= decode.processfloat(responses.poll());
            fvals.add(fval); 
        }
    }

    public void WriteData()
    {
        String fString=null; 
        try
        {
            while(fvals.isEmpty()==false)
            {
                if(fvals.peek() !=555)
                {
                    fString= Float.toString(fvals.poll());  
                    RunOutput.writeBytes(fString+",");
                }
                else
                {
                    RunOutput.writeBytes(newline);
                    fvals.remove(); 
                }
            }
        }
        catch(IOException e)
        {
            System.out.println("File not written to"); 
        }       
        System.out.println("Wrote data to file");
    }

    public void WriteHeader()
    {
        try 
        {
            RunOutput.writeBytes("Accel X,Accel Y,Accel Z,Gyro X,Gryo Y,Gryo Z,Temp,Air Pressure,Alititude,Latitude,Longitude");
            RunOutput.writeBytes(newline);  
        } 
        catch (IOException e) 
        {
            System.out.println(e.getMessage()); 
        }
    }
    public void ReadData()
    {
        fileread = new File(filename);
        System.out.println(this.filename); 
        try 
        {       
            Reader = new Scanner(fileread);
            Reader.nextLine();
            String text=""; 
            while(Reader.hasNext())
            {
                text+= Reader.nextLine();
            }
            System.out.println(text); 
            String[] collected = text.split(",");    
            for(int temp=0; temp<collected.length; temp++)
            {
                this.filedata.add(Float.parseFloat(collected[temp]));
                //System.out.println(temp); 
            }
            System.out.println("Filer Array list size:" + this.filedata.size());
            /*for(int temp=0; temp< filedata.size(); temp++)
                System.out.println(filedata.get(temp)); */
        } 
        catch (FileNotFoundException e) 
        {
            System.out.println(e.getMessage());
        }
        catch(NumberFormatException num)
        {
            System.out.println("No Numbers found/ Cannot format values");
        }

    }
    public List<Collection> ReadData(final File file) {
        List<Collection> data = new ArrayList<>();
        if(!file.isDirectory() && file.canRead()) {
            try {
                BufferedReader br = new BufferedReader(new FileReader(file));
                br.readLine(); 
                String line = "";
                while((line = br.readLine()) != null) {
                    String[] split = line.split(",");
                    Collection dff = new Collection(Float.parseFloat(split[0]),Float.parseFloat(split[1]),Float.parseFloat(split[2]),Float.parseFloat(split[3]),Float.parseFloat(split[4]),Float.parseFloat(split[5]),
                                                    Float.parseFloat(split[6]),Float.parseFloat(split[7]),Float.parseFloat(split[8]),Float.parseFloat(split[9]),Float.parseFloat(split[10]));
                    data.add(dff);
                }
                System.out.println("Reading from file finished");
                br.close();
            } catch (FileNotFoundException ex) {
                Logger.getLogger(PreviousTableModel.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(PreviousTableModel.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            System.out.println("Sorry, i can not read your input file!");
        }

        return data;
    }
    @SuppressWarnings("null")
    public List<Collection> SortData(ArrayList<Float> RawData)
    {
        List<Collection> sortedData = null; 
        while(RawData.isEmpty() ==false)
        {
            Collection fullCollect =new Collection(RawData.get(0),RawData.get(1),RawData.get(2),RawData.get(3),RawData.get(4),RawData.get(5),
                                    RawData.get(6),RawData.get(7),RawData.get(8),RawData.get(9),RawData.get(10));
            for(int i=0; i<11;i++)
                RawData.remove(0); 
            sortedData.add(fullCollect); 
        }
        return sortedData;

    }

    public class Collection 
    {
        float AccelX,AccelY,AccelZ,GyroX,GyroY,GyroZ,
              Temp,AirPressure,Altitude,Latitude,Longitude;

        public Collection( final float AccelX, final float AccelY, final float AccelZ, final float GyroX, final float GyroY, 
                            final float GyroZ, final float Temp, final float AirPressure, final float Altitude, final float Latitude, final float Longitude)
        {
            this.AccelX= AccelX; 
            this.AccelY=AccelY; 
            this.AccelZ=AccelZ; 
            this.AirPressure= AirPressure; 
            this.Altitude=Altitude;
            this.GyroX=GyroX;
            this.GyroY=GyroY; 
            this.GyroZ=GyroZ; 
            this.Latitude=Latitude; 
            this.Longitude=Longitude; 
            this.Temp=Temp; 
        }

        public float getAccelX() {
            return AccelX;
        }

        public void setAccelX(float accelX) {
            AccelX = accelX;
        }

        public float getAccelY() {
            return AccelY;
        }

        public void setAccelY(float accelY) {
            AccelY = accelY;
        }

        public float getAccelZ() {
            return AccelZ;
        }

        public void setAccelZ(float accelZ) {
            AccelZ = accelZ;
        }

        public float getGyroX() {
            return GyroX;
        }

        public void setGyroX(float gyroX) {
            GyroX = gyroX;
        }

        public float getGyroY() {
            return GyroY;
        }

        public void setGyroY(float gyroY) {
            GyroY = gyroY;
        }

        public float getGyroZ() {
            return GyroZ;
        }

        public void setGyroZ(float gyroZ) {
            GyroZ = gyroZ;
        }

        public float getTemp() {
            return Temp;
        }

        public void setTemp(float temp) {
            Temp = temp;
        }

        public float getAirPressure() {
            return AirPressure;
        }

        public void setAirPressure(float airPressure) {
            AirPressure = airPressure;
        }

        public float getAltitude() {
            return Altitude;
        }

        public void setAltitude(float altitude) {
            Altitude = altitude;
        }

        public float getLatitude() {
            return Latitude;
        }

        public void setLatitude(float latitude) {
            Latitude = latitude;
        }

        public float getLongitude() {
            return Longitude;
        }

        public void setLongitude(float longitude) {
            Longitude = longitude;
        }


    }
}

桌子型号:

package com.rapplogic.xbee.examples.wpan;
import java.io.File;
import java.util.List;
import javax.swing.table.AbstractTableModel;
import com.rapplogic.xbee.examples.wpan.Filer.Collection;

public class PreviousTableModel extends AbstractTableModel
{
private static final long serialVersionUID = 1L;
private final String[] columnNames={"AccelX", "AccelY","AccelZ","GyroX","GyroY","GryoZ","Temp","Air Pressure","Altitude","Latitude","Longitude"};
Filer tableFile = new Filer(); 
List<Collection> allCollections;

public PreviousTableModel()
{

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

@Override
public int getRowCount() 
{
    return allCollections.size(); 
}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
    Collection value = allCollections.get(rowIndex);
    switch(columnIndex) {
        case 0:
            return value.getAccelX();
        case 1:
            return value.getAccelY();
        case 2:
            return value.getAccelZ();
        case 3:
            return value.getGyroX();
        case 4:
            return value.getGyroY();
        case 5:
            return value.getGyroZ(); 
        case 6:
            return value.getTemp();
        case 7:
            return value.getAirPressure();
        case 8:
            return value.getAltitude(); 
        case 9:
            return value.getLatitude();
        case 10:
            return value.getLongitude();
    }

    return null;
}

public String getColumnName(int column) {
    return columnNames[column];
}

public void updateTableData(File selectedFile) { 
    allCollections = tableFile.ReadData(selectedFile);
    System.out.println("Changing table");
    fireTableDataChanged();
}

}

所以这就是我在进行任何表模型或任何重大更改之前所拥有的所有代码。再次,我非常感谢您帮助patrick,我将尝试制作一个内部类来存储所有数据,看看是否可行再次,抱歉为凌乱的代码:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM