2012-08-08 6 views
2

지난 밤에 내 질문에 대한 답변 : SwingPropertyChangeSupport to dynamically update JTextArea, 텍스트 파일을 읽은 후 GUI를 새로 고치려고합니다.SwingPropertyChangeSupport 파일을 읽은 후 새로 고침 GUI

두 자리의 정수를 보유하는 배열이 있습니다. 텍스트 영역에 숫자 문자열을 입력 한 다음 수정할 색인을 선택하여 동적으로 업데이트 할 수 있습니다. 문자열은 두 자리 조각으로 분리되어 순차적으로 추가됩니다. 문자의 문자열을 입력하고 버튼을 클릭하면이 메서드를 호출합니다.

public void modifyArray() { 

    // show dialog to retrieve entered address 
    addressToModify = (String) JOptionPane 
      .showInputDialog("At which location?"); 

    // convert to integer if decimal address entered 
    memAddress = Integer.parseInt(addressToModify); 
    arrayForUpdate.instructionsIn(codeIn.getText(), memAddress); 
} 

이 코드 부분은 예상대로 작동합니다. 내가 "123456"을 입력하고 위치를 입력 한 경우 즉, "0"(또는 "0000"), 디스플레이가 같은으로 업데이트 : 나는 또한 구성된 문자열을 포함하는 텍스트 파일을

Index  0000 Value: 12 
Index  0001 Value: 34 
Index  0002 Value: 56 
Index  0003 Value: 00 

배열 색인을 기증하는 네 자리 숫자와 그 뒤에 배열에 추가 할 일련의 두 자리 값이옵니다. GUI 버튼/파일 선택기를 통해로드 할 수 있습니다. 예제 파일의 내용은 다음과 같습니다

000

내가 파일 처리하기 위해 다음과 같은 방법이 있습니다 위의 두 상황에서

public void readRecord(File fileName) { 

    // create file reader 
    try { 
     FileReader reader = null; 
     try { 
      // open input file 
      reader = new FileReader(fileName); 

      // create scanner to read from file reader 
      Scanner in = new Scanner(reader); 

      // read each line and remove whitespace 
      while (in.hasNextLine()) { 
       String line = in.nextLine().trim(); 
       parseRecord(line); 
      } 

     } finally { 
      // close reader assuming it was successfully opened 
      if (reader != null) 
       reader.close(); 
     } 
     } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    } 

public void parseRecord(String record) { 

    // create address substring from start, 4 long 
    String addrString = record.substring(0, 3); 
    int s1Address = Integer.parseInt(addrString); 

    // create binary data substring (4 from start, up to end) 
    String dataString = record.substring(4, record.length()); 

    // pass data string as parameter to InstructionsIn method 
    arrayForUpdate.instructionsIn(dataString, s1Address); 
} 

을은 "instructionsIn"메소드가 호출된다. 첫 번째 시나리오에서는 디스플레이가 업데이트되지만 두 번째 시나리오에서는 업데이트되지 않으므로 이유를 파악할 수 없습니다. 누군가 내가 놓친 것을 발견 할 수 있기를 바랬습니다.

import java.awt.BorderLayout; 
import java.awt.Color; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.event.FocusListener; 
import java.beans.PropertyChangeEvent; 
import java.beans.PropertyChangeListener; 
import java.io.File; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.Scanner; 

import javax.swing.JButton; 
import javax.swing.JFileChooser; 
import javax.swing.JFrame; 
import javax.swing.JOptionPane; 
import javax.swing.JPanel; 
import javax.swing.JTextArea; 
import javax.swing.event.SwingPropertyChangeSupport; 

public class PropertyChangeExample extends JFrame implements ActionListener { 

private static final long serialVersionUID = 1L; 
private String addressToModify, mList; 
private int memAddress; 
private JTextArea codeIn, displayOutput; 
private S_Record sRec; 
private JButton loadButton, modifyArrayButton; 
private FocusListener focusListener; 
private JPanel displayPanel; 
private ArrayForUpdate arrayForUpdate = new ArrayForUpdate(); 

public static void main(String[] arg) { 
    PropertyChangeExample display = new PropertyChangeExample(); 
    display.setVisible(true); 
} 

public PropertyChangeExample() { 
    setDefaultCloseOperation(EXIT_ON_CLOSE); 
    setSize(450, 170); 
    layoutLeft(); 
    layoutDisplay(); 
    layoutBottom(); 
} 

public void layoutDisplay() { 
    displayPanel = new JPanel(); 
    add(displayPanel, BorderLayout.CENTER); 
    displayOutput = new JTextArea(32, 38); 
    displayPanel.add(displayOutput); 
    displayOutput.addFocusListener(focusListener); 

    mList = arrayForUpdate.getBoundProperty(); 
    displayOutput.setText(mList); 

    arrayForUpdate.addPropertyChangeListener(new PropertyChangeListener() { 

     @Override 
     public void propertyChange(PropertyChangeEvent pcEvt) { 
      if (pcEvt.getPropertyName().equals(
        ArrayForUpdate.BOUND_PROPERTY)) { 
       mList = (pcEvt.getNewValue().toString()); 
       displayOutput.setText(mList); 
      } 
     } 
    }); 
} 

public void layoutLeft() { 
    JPanel left = new JPanel(); 
    add(left, BorderLayout.WEST); 
    codeIn = new JTextArea(10, 7); 
    left.add(codeIn, BorderLayout.NORTH); 
    codeIn.addFocusListener(focusListener); 
} 

public void layoutBottom() { 
    JPanel bottom = new JPanel(); 
    bottom.setBackground(Color.LIGHT_GRAY); 
    loadButton = new JButton("Load file"); 
    loadButton.addActionListener(this); 
    bottom.add(loadButton); 
    add(bottom, BorderLayout.SOUTH); 
    modifyArrayButton = new JButton("Add value to array"); 
    modifyArrayButton.addActionListener(this); 
    bottom.add(modifyArrayButton); 
} 

public void actionPerformed(ActionEvent ae) { 
    if (ae.getSource() == modifyArrayButton) { 
     modifyArray(); 
    } 

    if (ae.getSource() == loadButton) { 
     processInputFile(); 
    } 
} 

public void modifyArray() { 
    addressToModify = (String) JOptionPane 
      .showInputDialog("At which location?"); 

    // convert to integer if decimal address entered 
    memAddress = Integer.parseInt(addressToModify); 
    arrayForUpdate.instructionsIn(codeIn.getText(), memAddress); 
} 

public void processInputFile() { 

    sRec = new S_Record(); 
    JFileChooser chooser = new JFileChooser(); 
    int returnVal = chooser.showOpenDialog(getParent()); 
    if (returnVal == JFileChooser.APPROVE_OPTION) { 
     // create the file 
     File file = chooser.getSelectedFile(); 

     // pass to readRecord method in S_Record class 
     sRec.readRecord(file); 
    } 
} 
} 

class S_Record { 

private ArrayForUpdate arrayForUpdate = new ArrayForUpdate(); 

public void readRecord(File fileName) { 

    // create file reader 
    try { 
     FileReader reader = null; 
     try { 
      // open input file 
      reader = new FileReader(fileName); 

      // create scanner to read from file reader 
      Scanner in = new Scanner(reader); 

      // read each line and remove whitespace 
      while (in.hasNextLine()) { 
       String line = in.nextLine().trim(); 
       parseRecord(line); 
      } 
     } finally { 
      // close reader assuming it was successfully opened 
      if (reader != null) 
       reader.close(); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

public void parseRecord(String record) { 

    // create address substring from start, 4 long 
    String addrString = record.substring(0, 3); 

    int s1Address = Integer.parseInt(addrString); 

    // create binary data substring (4 from start, up to end) 
    String dataString = record.substring(4, record.length()); 

    // pass data string as parameter to InstructionsIn method 
    arrayForUpdate.instructionsIn(dataString, s1Address); 
} 
} 

class ArrayForUpdate { 

public static final String BOUND_PROPERTY = "bound property"; 
private String boundProperty = ""; 
private SwingPropertyChangeSupport spcSupport = new SwingPropertyChangeSupport(
     this); 
private int[] myArray; 
private final int MEM_LOCATIONS = 6; 
/** StringBuilder object for displaying memory */ 
private StringBuilder mList; 

public ArrayForUpdate() { 

    myArray = new int[MEM_LOCATIONS]; 
    for (int i = 0; i < myArray.length; i++) { 
     myArray[i] = 0; 
    } 
    setArrayyDisplayString(); 
} 

/** 
* method to create formatted string of array 
*/ 
public void setArrayyDisplayString() { 

    // create StringBuilder for display in memory tab 
    mList = new StringBuilder(); 
    for (int i = 0; i < myArray.length; i++) { 

     mList.append(String.format("%10s %04x %10s %02x", "Index: ", i, 
       "Value: ", myArray[i])); 
     mList.append("\n"); 
    } 
    setBoundProperty(mList.toString()); 
} 

/** 
* This method takes in a string passed through from the GUI 
*/ 
public void instructionsIn(String codeIn, int loc) { 

    String code = codeIn.trim(); 
    int len = code.length(); 
    int chunkLength = 2; // the length of each chunk of code 
    int i = 0; 

    // traverse entered code and split into 2 digit chunks 
    for (i = 0; i < len; i += chunkLength) { 

     String chunk = code.substring(i, Math.min(len, i + chunkLength)); 
     int oc = Integer.parseInt(chunk, 16); 

     // add the data to the array 
     setArrayData(loc, oc); 
     loc++; 
    } 
} 

/** 
* method to add data to the array 
*/ 
public void setArrayData(int a, int memData) { 
    myArray[a] = memData; 
    setArrayyDisplayString(); 
} 

public String getBoundProperty() { 
    return boundProperty; 
} 

/** 
* Method to implement changes to array for display 
* 
* @param boundProperty - the String representing the memory array 
*/ 
public void setBoundProperty(String boundProperty) { 
    String oldValue = this.boundProperty; 
    String newValue = boundProperty; 
    this.boundProperty = newValue; 
    spcSupport.firePropertyChange(BOUND_PROPERTY, oldValue, newValue); 
} 

public void addPropertyChangeListener(PropertyChangeListener listener) { 
    spcSupport.addPropertyChangeListener(listener); 
} 
} 

답변

3

이 참조의 문제 같습니다 여기

는 실행 코드의 전체, 단순화 된 버전입니다.

두 개 이상의 ArrayForUpdate 개체가 있고 GUI에서 수신하는 개체와 S_Record 클래스 내부에있는 완전히 다른 개체가 있습니다. 후자는 파일에서 정보를 얻는 것이고, 이전 것은 GUI에 의해 청취되는 것입니다. 해결 방법 : 두 위치 모두에서 사용되는 ArrayForUpdate 객체가 하나만 있는지 확인하십시오. 아마도 생성자를 통해 GUI 인스턴스의 참조를 S_Record 객체에 전달할 수 있습니까?

+0

대단히 감사합니다. 저것은 대접을 일한 것처럼 보인다. 지난 주 많은 도움을 주셨습니다! – Robert

+1

@ 로버트 : 천만에요. 이제 백그라운드 스레드에서 파일 읽기 비즈니스를 수행하는 것을 잊지 마십시오. –

+0

죄송합니다. 프로그래밍에 익숙하지 않고 백그라운드 스레드가 무엇을 의미하는지 확신 할 수 없습니까? – Robert