我尝试从文件刷新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
选择一个新文件时,我都会看到浮动值发生变化,但我无法看到它们被输入到表中。
答案 0 :(得分:0)
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;
}
}
这是一个文本文件,我从这个文件中读取名字,姓氏和城市名称,它们由一个标签分隔,我在String
方法中稍后将readFile
分开。
Hans,Mayer,纽约 卡尔·路易斯,美国加州 玛利亚,莎,迈阿密
我希望它会对您有所帮助,您可以根据自己的应用进行调整。
帕特里克
答案 1 :(得分:0)
以下是我开始做任何事之前没有触及的所有代码,我知道它有点不干净但是因为我急于完成这个项目...真的很抱歉< / p>
主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);
}
ActionPerformed:
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");
}
}
最后但不是最少的文件管理器类:
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我将尝试创建一个内部类来存储所有数据看看是否有效再次感谢并且对于凌乱的代码感到抱歉:)