2017-12-14 8 views
1

당신이 나를 도울 수 있기를 바랍니다. 내 데이터베이스에서 검색된 이미지를 라운드 삼각형으로. 다음 이미지에서 이미지가 imageview.user에서 올바르게 표시되는지 확인할 수 있습니다. 사용자가 테이블에서 새 항목을 선택하고 올바른 이미지를 표시하기 위해 이미지가 변경되었습니다.이 기능은 문제없이 작동합니다.Java FX 서클 이미지

This is the program

은 내가 gestionarEventos에서이 코드를 시도 :

imgfotovisi.imageProperty().bind(imageRetrievalService.valueProperty()); 
     Image im = imgfotovisi.getImage(); 
     circulo.setFill(new ImagePattern(im)); 

그러나 자바 말 : 나는 (라인이 imgfotovisi.imageProperty 노호 삭제하면

... 58 more 
Caused by: java.lang.NullPointerException: Image must be non-null. 
    at javafx.scene.paint.ImagePattern.<init>(ImagePattern.java:235) 

프로그램이 실행) .bind (imageRetrievalService.valueProperty()); 선.

실행하면 이미지가 null 인 이유를 알 수 없습니다. 분명히 볼 수 있습니다.

import java.net.URL; 
    import java.sql.Connection; 
    import java.sql.PreparedStatement; 
    import java.util.ResourceBundle; 
    import java.util.function.Predicate; 
    import javafx.beans.property.ReadOnlyStringWrapper; 
    import javafx.beans.value.ChangeListener; 
    import javafx.beans.value.ObservableValue; 
    import javafx.collections.FXCollections; 
    import javafx.collections.ObservableList; 
    import javafx.collections.transformation.FilteredList; 
    import javafx.collections.transformation.SortedList; 
    import javafx.concurrent.Service; 
    import javafx.concurrent.Task; 
    import javafx.event.ActionEvent; 
    import javafx.fxml.FXML; 
    import javafx.fxml.Initializable; 
    import javafx.scene.Node; 
    import javafx.scene.control.Button; 
    import javafx.scene.control.Label; 
    import javafx.scene.control.TableColumn; 
    import javafx.scene.control.TableView; 
    import javafx.scene.control.TextField; 
    import javafx.scene.image.Image; 
    import javafx.scene.image.ImageView; 
    import javafx.scene.input.InputEvent; 
    import javafx.scene.layout.StackPane; 
    import javafx.scene.paint.Color; 
    import javafx.scene.paint.ImagePattern; 
    import javafx.scene.shape.Circle; 

    import javafx.stage.Stage; 

    public class ver_visitantes implements Initializable { 

     @FXML private TableView<visitantes> tbvisitantes; 
     @FXML private TableColumn<visitantes, String> clcedula,clnombres,clapellidos,clapartamento,clcelular,clobservaciones; 
     @FXML private ImageView imgfotovisiact,imgfotoact,imgfotovisi,imgfoto; 
     @FXML private TextField txtcedula,txtnombres,txtapto,txtapellidos,txtapt,txtcelular,txtobservaciones; 
     @FXML private Label lblinfovisiact,lblusuario,lblstatusvisi; 
     @FXML private Circle circulo; 

     private ObservableList<visitantes> visitorlist; 

     @Override 
     public void initialize(URL arg0, ResourceBundle arg1) { 


      ConexionSQL cnt = new ConexionSQL(); 
      cnt.conexion(); 

      visitorlist = FXCollections.observableArrayList(); 
      visitantes.llenarlistavisitas(cnt.conexion(), visitorlist); 
      tbvisitantes.setItems(visitorlist);// llenar table view con la lista 

      clcedula.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getcedula())); 
      clnombres.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getnombres())); 
      clapellidos.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getapellidos())); 
      clapartamento.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getapartamento())); 
      clcelular.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getcelular())); 
      clobservaciones.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getobservaciones())); 

      gestionarEventos(); 

      tbvisitantes.getSelectionModel().selectFirst(); 


     } 

     public void gestionarEventos() { 
      tbvisitantes.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<visitantes>() { 
       @Override 
       public void changed(ObservableValue<? extends visitantes> arg0, visitantes valorAnterior, 
         visitantes valorSeleccionado) { 
        imgfoto.setVisible(false); 
        btnmodificar.setDisable(false); 
        btncancelar.setDisable(false); 
        btneliminar.setDisable(false); 
        imageRetrievalService.restart(); 

        if (valorSeleccionado != null) { 

         txtcedula.setText(String.valueOf(valorSeleccionado.getcedula())); 
         txtnombres.setText(valorSeleccionado.getnombres()); 
         txtapellidos.setText(valorSeleccionado.getapellidos()); 
         txtapto.setText(String.valueOf(valorSeleccionado.getapartamento())); 
         txtcelular.setText(String.valueOf(valorSeleccionado.getcelular())); 
         txtobservaciones.setText(String.valueOf(valorSeleccionado.getobservaciones())); 
        } 
       } 
      }); 

     imgfotovisi.imageProperty().bind(imageRetrievalService.valueProperty()); 

     } 


     private final Service<Image> imageRetrievalService = new Service<Image>() {// cargar imagen en visitantes 
      @Override 
      protected Task<Image> createTask() { 
       final String id; 

       final visitantes visitante = tbvisitantes.getSelectionModel().getSelectedItem(); 
       if (visitante == null) { 
        id = null; 
       } else { 
        id = visitante.getcedula(); 
       } 
       return new Task<Image>() { 
        @Override 
        protected Image call() throws Exception { 
         if (id == null) { 
          return null; 
         } 
         return visitante.getImageById(id); 
        } 
       }; 
      } 
     }; 


    } 

이는 visitantes 클래스는, 이미지를 얻을 수있는 imageRetrievalService에서 호출 :

imgfotovisi.imageProperty().bind(imageRetrievalService.valueProperty()); 
: 나는 문제가 여기에있다 생각

package application; 

import java.io.IOException; 
import java.io.InputStream; 
import java.sql.Blob; 
import java.sql.Connection; 
import java.sql.PreparedStatement; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.sql.Statement; 



import javafx.beans.property.SimpleStringProperty; 
import javafx.beans.property.StringProperty; 
import javafx.collections.ObservableList; 
import javafx.scene.image.Image; 


public class visitantes { 
    private StringProperty cedula; 
    private StringProperty nombres; 
    private StringProperty apellidos; 
    private StringProperty apartamento; 
    private StringProperty celular; 
    private StringProperty observaciones; 



    public visitantes(String cedula,String nombres,String apellidos,String apartamento,String celular,String observaciones){ 

     this.cedula = new SimpleStringProperty(cedula); 
     this.nombres = new SimpleStringProperty(nombres); 
     this.apellidos = new SimpleStringProperty(apellidos); 
     this.apartamento = new SimpleStringProperty(apartamento); 
     this.celular = new SimpleStringProperty(celular); 
     this.observaciones = new SimpleStringProperty(observaciones); 



    } 




    public String getnombres(){ 
     return nombres.get(); 
    } 

    public void setnombres(String nombres){ 
     this.nombres = new SimpleStringProperty(nombres); 
    } 

    public String getcedula(){ 
     return cedula.get(); 
    } 

    public void setcedula(String cedula){ 
     this.cedula = new SimpleStringProperty(cedula); 
    } 
    public String getapellidos(){ 
     return apellidos.get(); 
    } 

    public void setapellidos(String apellidos){ 
     this.apellidos = new SimpleStringProperty(apellidos); 
    } 

    public String getapartamento(){ 
     return apartamento.get(); 
    } 

    public void setapartamento(String apartamento){ 
     this.apartamento = new SimpleStringProperty(apartamento); 
    } 

    public String getcelular(){ 
     return celular.get(); 
    } 

    public void setcelular(String celular){ 
     this.celular = new SimpleStringProperty(celular); 
    } 




      public Image getImageById(String id) throws SQLException, IOException { 
       try (
         ConexionSQL cn = new ConexionSQL(); 
         Connection con = cn.conexion(); 
        PreparedStatement ps = con.prepareStatement(
         "SELECT foto_visi FROM visitantes WHERE cedula_visi = ?"); 
       ) { 
        ps.setString(1, id); 
        ResultSet results = ps.executeQuery(); 
        Image img = null ; 
        if (results.next()) { 
         Blob foto = results.getBlob("foto_visi"); 
         InputStream is = foto.getBinaryStream(); 
         img = new Image(is) ; // false = no background loading 
         is.close(); 
        } 
        results.close(); 
        return img ; 
       } catch (Throwable e) { 
        String info = e.getMessage(); 
        System.out.println(info); 
       } 
       return null; 
      } 
    } 

은 ver_visitantes 클래스

은퇴 한 이미지가이 줄의 imageivew에로드되어 있는지 알지 못합니다. 예, 부 t 할 경우 Image im = imgfotovisi.getImage(); , 자바 말 null.then 나는 원으로 이미지를 얻을 수 없습니다. 미리 :)

답변

1

bind 이미지 자체를로드하지 않을 , 단지 하나 개의 변수가 변경됩니다 그래서 바인딩에

감사 때 (이 경우, 상기 서비스의 값 속성) 소스 변경 서비스가 비동기 적으로 실행될 때 곧바로 실행되지는 않습니다. 따라서 바인드 문을 실행 한 직후 값을 쿼리하면 소스가 아직 변경되지 않았으므로 예상 한 결과를 얻지 못합니다.

대신 이미지를 실제로 사용할 수있게되면 조치를 취해야합니다. 예를 들어

:

imageRetrievalService.valueProperty().addListener((obs, oldVal, newVal) -> 
    if (newVal != null) 
     circulo.setFill(new ImagePattern(newVal)) 
); 

이 서비스에 직접 연결을 원하지 않는 경우 또는, 그리고 imgfotovsi 이미지 속성이 이미 서비스 값에 바인딩 주어진 :

imgfotovisi.imageProperty().addListener((obs, oldVal, newVal) -> 
    if (newVal != null) 
     circulo.setFill(new ImagePattern(newVal)) 
); 
+0

"바인드는 이미지 자체를로드하지 않을 것입니다."그렇습니다.하지만 프로그래밍 능력은 부족합니다. Thaks a jewelsea : D –

+0

안녕하세요, 코드가 작동하고 있지만, "image"를 변경할 때 오류가 발생합니다. "JavaFX Application Thread"스레드에서 예외가 발생했습니다. java.lang.NullPointerException : 이미지가 null이 아니어야합니다. 나도 몰라 그 중요한 경우 오류가 프로그램을 실행 good.i 초기화 Othe 이미지를 사용하여 작성하려고 시도하지만 청취자가 chages을 감지하면 오류가 나타납니다. –

+0

리스너에 if 문을 넣을 수 있으며 이미지가 null 값으로 변경되면 새 채우기를 설정하지 않습니다. 나는 그것을 반영하기 위해 답을 업데이트했다. – jewelsea