2017-12-28 6 views
0

나는 FXML로 만든 열 부부와의 TableView 있습니다오브젝트를 JavaFX TableView에 표시하기 위해 문자열로 변환하는 방법은 어떻게 지정합니까?

<TableView fx:id="logTable" BorderPane.alignment="CENTER"> 
    <columns> 
     <TableColumn fx:id="timestampColumn" editable="false" text="Timestamp"> 
      <cellValueFactory> 
       <PropertyValueFactory property="timestamp"/> 
      </cellValueFactory> 
     </TableColumn> 
     <TableColumn fx:id="actionColumn" editable="false" text="Action"> 
      <cellValueFactory> 
       <PropertyValueFactory property="action"/> 
      </cellValueFactory> 
     </TableColumn> 
    </columns> 
</TableView> 
그때 객체는 다음과 같이 정의

:

다음의 TableView의 모델로 설정

private ObservableList<LogEntry> log = FXCollections.observableArrayList(); 

LogEntries

logTable.setItems(log); 
는 다음과 같다 :

import javafx.beans.property.SimpleObjectProperty; 
import javafx.beans.property.SimpleStringProperty; 
import org.joda.time.DateTime; 

public class LogEntry { 
    private SimpleObjectProperty<DateTime> timestamp = new SimpleObjectProperty<>(); 
    private SimpleStringProperty action = new SimpleStringProperty(); 

    public LogEntry(String format, Object... args) { 
     this.timestamp.setValue(new DateTime()); 
     String s = String.format(format, args); 
     System.out.println(s); 
     this.action.setValue(s); 
    } 

    public DateTime getTimestamp() { 
     return timestamp.getValue(); 
    } 

    public String getAction() { 
     return action.getValue(); 
    } 
} 

제 질문은 조다 타임 타임 스탬프를 표시하기 위해 문자열로 변환하는 방법을 어떻게 지정합니까? 현재 로케일을 사용하여 변환하려고합니다 (그러나 여전히 작동하도록 해당 열을 정렬하고 싶습니다).

+1

에게 OT를 업데이트하는 세포 공장을 사용 : 당신이 자바 7에 연결하거나 여기에 몇 가지 다른 이유로 Joda 시간을 사용하도록 강요하고 있는가? Java 8 시간 API는 기본적으로 Joda Time을 중복시킵니다 (Joda Time에 매우 많이 기반하며 API는 매우 유사합니다). [Joda Time 홈페이지] (http://www.joda.org/joda-time/)는 실제로 다음과 같이 말합니다 : ** "Java SE 8부터는 사용자가 java.time (JSR-310) -이 프로젝트를 대체하는 JDK의 핵심 부분입니다. "** –

+0

@James_D : 저는 실제로 Java 8을 사용하고 있습니다. Java 8에 대해서는 잘 모릅니다. 나는 그것을 조사해야 할 것이다. 고맙습니다. – Pablo

+0

@Pablo * java.time *을 정의하는 [JSR 310] (https://jcp.org/en/jsr/detail?id=310) 프로젝트는 * Joda-Time *, [Stephen Colebourne] (https://stackoverflow.com/users/38896/jodastephen). * java.time * 클래스는 배운 교훈을 사용하여 * Joda-Time *을 처음부터 다시 작성합니다. –

답변

1

나는 Joda Time과 일하지 않았지만 LocalDateTime과 비슷한 작업을 수행했다.

어떻게 작동하는지 예가 있습니다.

dateTimeColumn.setCellFactory(tc -> new LocalDateTimeTableCell<LogEntry>(true)); 
dateTimeColumn.setCellValueFactory(data -> data.getValue().timestampProperty()); 

이 같은 표 셀을 만들기 :

public class LocalDateTimeTableCell<S> extends TableCell<S, LocalDateTime> { 
    private final DateTimeFormatter myDateFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); 
    private final DateTimeFormatter myDateTimeFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm:ss a"); 
    private final boolean showTime; 

    public LocalDateTimeTableCell(boolean showTime){ 
     this.showTime = showTime; 
    } 
    @Override 
    protected void updateItem(LocalDateTime item, boolean empty) { 
     super.updateItem(item, empty); 
     if (item == null || empty) { 
      setText(null); 
      setStyle(""); 
     } else { 
      // Format date. 
      if(showTime) { 
       setText(myDateTimeFormatter.format(item)); 
      }else { 
       setText(myDateFormatter.format(item)); 
      } 
     } 
    } 
} 

첫째로 당신은 당신이 셀 공장과 셀 값 공장을 설정 한 다음 속성 ::

public class LogEntry { 
    private SimpleObjectProperty<LocalDateTime> timestamp = new SimpleObjectProperty<>(); 
    private SimpleStringProperty action = new SimpleStringProperty(); 
    public final SimpleObjectProperty<LocalDateTime> timestampProperty() { 
     return this.timestamp; 
    } 

    public final java.time.LocalDateTime getTimestamp() { 
     return this.timestampProperty().get(); 
    } 

    public final void setTimestamp(final java.time.LocalDateTime timestamp) { 
     this.timestampProperty().set(timestamp); 
    } 

    public final SimpleStringProperty actionProperty() { 
     return this.action; 
    } 

    public final java.lang.String getAction() { 
     return this.actionProperty().get(); 
    } 

    public final void setAction(final java.lang.String action) { 
     this.actionProperty().set(action); 
    } 
} 

을 노출해야

나는 이것이 당신이 조다 (Joda) 시간에 요구 한 것이 아니라는 것을 알고 있습니다. 그러나 당신에게 방향을 제시해야합니다.

+0

포매터를 생성자의 셀에 전달할 것을 권장합니다. 현재 사용중인 값을 사용하여 인수가없는 생성자를 제공 할 수 있습니다. 그러나 이러한 값을 전달하는 생성자를 제공하면 모든 단일 셀 인스턴스에 대해 하나씩 생성하는 대신 전체 열에 대해 포맷터를 다시 사용할 수 있습니다. – fabian

+0

정적 최종 설정은 어떻게됩니까? 그러면 내부 구현이 숨겨져 클래스 수준이 될 것입니다. –

+0

가능하지만 다른 형식 (예 : "유럽"날짜 형식 사용)을 전달할 수 있으므로 생성자에 전달하는 것이 더 유연합니다. 개인적으로 나는 이것을 선호하고 셀 팩터 리를 생성하기위한 정적'forTableColumn' 메쏘드를 생성 할 것입니다 (다른'TableCell' 구현으로 끝난 것처럼).그런 방법으로 포맷터를 로컬 변수로 선언하고 메소드에서 반환 된 람다 표현식/아노믹스 클래스에서 사용하는 것이 쉽습니다. – fabian

-1

private TableColumn<Customer, LocalDateTime> Col_date; 
    Col_date.setCellFactory((TableColumn<LogEntry, LocalDateTime> param) -> { 
     TableCell<LogEntry, LocalDateTime> cell = new TableCell<LogEntry, LocalDateTime>() { 
      @Override 
      public void updateItem(LocalDateTime item, boolean empty) { 
       if (item != null) { 
        setText(getDateTimeFormat(item,"yyyy/MM/dd HH:mm")); 

       } else { 
        setText(null); 
       } 
      } 
     }; 
     return cell; 
    }); 


public static String getDateTimeFormat(LocalDateTime dateTime,String format) throws DateTimeParseException { 
    return dateTime.format(DateTimeFormatter.ofPattern(format)); 
} 
관련 문제