2014-05-13 3 views
0

파일에서 JTable의 값을 새로 고쳐서 테이블에 표시 할 수 있습니다. 모델이 있지만 작동하지 않는 이유를 모르겠습니다. 나는 내가 생각할 수있는 모든 것을 시도했다.파일에서 JTable으로 값 새로 고침

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); 
       } 
      } 
     } 

표 모델 : 다음은 GUI의 코드와 TableModel

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); 
    } 

} 

나는 ComboBox에서 새 파일을 선택 할 때마다 내가 플로트 값이 변경 볼 수 있기 때문에 ArrayList 작동하지만 나는 그들이 테이블에 입력되는 것을 볼 수 없다.

+0

나는 'itemStateChange) '메소드 – TeamIncredibles

+0

'setValueAt'에서'yourTableVariable.revalidate()'를 시도 했습니까? 레이아웃을 다시 작성하거나 다시 칠할 필요가 없을 수도 있습니다. – DankMemes

+0

'public void setValueAt (Object value, int row, int col) \t { \t \t rowData [row] [col] = (Float) value; \t \t guitable.datafield1.revalidate(); \t \t //this.fireTableCellUpdated(row, col); \t \t \t} ' 편집을했지만 스택에 오버로드가 발생했습니다. 또한 tableChanged를 구현하려고했지만 실제로 데이터를 가져 와서 테이블에 넣는 작업을 모릅니다. @TeamIncredible 어떤 종류 또는 의심 당신은 내가 그것에 대해 뭔가 할 수 있을지 모르겠다 – UP2ME4ME

답변

0

HEJ UP2ME4ME는

내가 다른 File을로드 할 JTableJButton을 포함하는 당신을 위해 매우 작고 간단한 예를 JPanel했다.

그래서 여기가하는 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 <[email protected]> 
* @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; 
    } 
} 

여기 하나의 텍스트 파일이 있는데,이 파일에서 FirstName, Lastname 및 Cityname을 읽습니다.이 파일은 StringreadFile 방법으로 나눌 때 하나의 탭으로 구분됩니다.

한스 메이어, 뉴욕 칼, 루이스, 캘리포니아 마리아 샤라포바, 마이애미

는 나는 당신을 도울 것입니다 희망 당신은 당신의 응용 프로그램을 위해 그것을 적용 할 수 있습니다.

패트릭

다음
+0

고마워요. 패트릭 ... 잘하면 내 데이터가 모두 쉼표로 구분되어 있지만 그 개념은 확실합니다. 나는 JFileChooser를 사용하지 않는다. 왜냐하면 나는 부모 파일이 어디에나 정의되어 있기 때문에 대신 JComboBox를 사용한다. 데이터 파일과 함께 원한다면 내가 볼 수있는 코드를 줄 수있다. – UP2ME4ME

+0

@ UP2ME4ME 예, 질문을 편집하여 코드를 추가하십시오. – Patrick

0

난 아무것도 할 시작되기 전에 유엔 - 감동 모든 코드는, 내가 조금 부정한 알고하지만 난 정말 죄송합니다 ...이 프로젝트를 완료하기 위해 서두르고있어 그것 때문에입니다

메인 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); 
    } 
,451,515,

은의 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(); 
} 

}

그래서이 내가 가진 모든 코드를 테이블 모델이나 중요한 변경을하기 전에다시 정말 당신이 패트 릭 도움이 돼 주셔서 감사합니다 모든 데이터를 저장할 수있는 내부 클래스를 시도하고 지저분한 코드에 대해 다시 감사드립니다 및 미안 해요 참조하십시오 :)

+0

안녕하세요 @ 패트릭 나는 파일에서 JFileChooser를 사용하는 테이블 모델을 만들 수 있었고 데이터에서 개체를 만들도록했지만 여전히 어떤 이유에서든 업데이트 된 코드가 위에있는 컬렉션 클래스를 만들 수있었습니다. – UP2ME4ME

관련 문제