簡體   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