0

enter image description hereI quite understand the implementation of GridView to achieve a representation of the image below, I do like to get an implementation of that also done in javafx, whereby the data will be fetched from MYSQL database.

I really do not know how to get about this implementation, i.e. fetching a data which will be dynamic and represented with the style above.

I sincerely appreciate your time.

public class Home_pageController extends Application {

    @FXML
    private GridPane myGrid;
    @FXML
    private JFXButton yes_button;

    /**
     * Initializes the controller class.
     */
    /**
     * Initializes the controller class.
     */
    @Override
    public void start(Stage stage) throws Exception {
        //    Parent root = FXMLLoader.load(getClass().getResource("Student.fxml"));
        getGrid();

        Parent root = FXMLLoader.load(getClass().getResource("home_page.fxml"));
        //GridPane root = new GridPane();

        Scene scene = new Scene(root);
        stage.setTitle("Some scene");
        stage.setScene(scene);

        stage.show();
    }

    /**
     * @param args the command line arguments
     */
    public void getGrid() {
        List<ImageDataObjs> imageURLs ; //you'll use something like this, but I've not for this little helper
        //here you'll want to make a database setup and a call: This is a really bad program, but it will demonstrate
        conn = javaconnect.ConnectDb();
        imageURLs = makeDBCall();
         GridPane gridPane = new GridPane();
//        myGrid.setGridLinesVisible(true);

        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                System.out.print("Just me here again "+imageURLs.get(i).the_image);

                Label label = new Label("Label " + i + "/" + j);
//                label.setMouseTransparent(true);
                GridPane.setRowIndex(label, i);
                GridPane.setColumnIndex(label, j);
                myGrid.getChildren().add(imageURLs.get(10).the_image);
            }
        }
    }

    public static void main(String[] args) {
        launch(args);
    }

    class ImageDataObjs {

        // final ImageView imageView;
        //  String imgURL, price;
        @FXML
        final ImageView the_image;
        String imgURL;
        byte[] price;

        public ImageDataObjs(String imgURL, byte[] price) throws IOException {
            this.imgURL = imgURL;
            this.price = price;
            InputStream in = new ByteArrayInputStream(price);

            WritableImage images = new WritableImage(50, 50);

            ByteArrayInputStream bis = new ByteArrayInputStream(price);
            BufferedImage read = ImageIO.read(bis);
            images = SwingFXUtils.toFXImage(read, null);
            this.the_image = new ImageView(images);
        }
    }

    Connection conn = null;
    ResultSet rs = null;
    PreparedStatement pst = null;
    static byte[] staff_image;
//there a million examples of theis on the web

    private List<ImageDataObjs> makeDBCall() {
        List<ImageDataObjs> imageDataObjList = new ArrayList<>();
        // String myPrice, myURL;
        byte[] myPrice;
        String myURL;
        try {
            String sql = "select * from phone_types";
            pst = conn.prepareStatement(sql);
            rs = pst.executeQuery();
            while (rs.next()) {
                myPrice = rs.getBytes("phone_image");
                myURL = rs.getString("phone_name");
                System.out.println("I am just here "+ myPrice);
                imageDataObjList.add(new ImageDataObjs(myURL, myPrice));
            }
            conn.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return imageDataObjList;
    }

}

I am getting

Caused by: java.lang.NullPointerException at controllers.Home_pageController.getGrid(Home_pageController.java:85) at controllers.Home_pageController.start(Home_pageController.java:54) at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863) at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326) at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295) at java.security.AccessController.doPrivileged(Native Method) at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294) at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95) at com.sun.glass.ui.win.WinApplication._runLoop(Native Method) at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)

Derin S
  • 55
  • 1
  • 10
  • 2
    JavaFX literally has a GridPane – Steven Aug 02 '17 at 02:55
  • thanks for that, i do not know how to go about it's implementation, i.e. how to dynamically populate/represent data like the picture above using the GridPane just like use adapter on Android. Thanks for your response once again. – Derin S Aug 02 '17 at 03:10
  • What have you tried? What is the format of the data being fetched? Are you having trouble with the GUI or the fact that it's dynamic? – Steven Aug 02 '17 at 04:13
  • 1
    controlsfx even has a [`GridView` class](https://controlsfx.bitbucket.io/org/controlsfx/control/GridView.html)... – fabian Aug 02 '17 at 14:53
  • @Steven, I am having issue with it for the fact that it is dynamic. I really do not know how to go about it – Derin S Aug 03 '17 at 05:19

1 Answers1

1

I presume your really after JavaFX FXML, but I'll point you towards JDBC and some hand coded JavaFX.

The steps are install MYSQL, install ConnectorJ (this is a way to connect from your code into MySQL ( a driver)) Record passwords, and make a fresh database, add a table, and the columns you need.

Caveat: this is big question to ask, and already available in many places, but you've asked, so I've provided some code. The GUI part will run, the database part will need tweaking.

I've also demonstrated a GridPane below for you. But I think what you'll want, so that your view updates automatically, are bound variables-- as a start, as I've commented in the code, please check out TableView and Cell Factories. Also check out data binding, and classes like: https://docs.oracle.com/javase/8/javafx/api/javafx/beans/property/SimpleStringProperty.html

There are a million things wrong with this code: you should never make a DB call from your GUI thread, etc.etc. But you've got to start somewhere. If this helped, please mark accordingly.

import com.techtalix.util.Const;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;


public class Test extends Application {

Connection connect = null;

public static void main(String[] args) {
    launch(args);
}

@Override
public void start(Stage stage) {

    List<ImageDataObjs> imageURLs = null; //you'll use something like this, but I've not for this little helper
    //here you'll want to make a database setup and a call: This is a really bad program, but it will demonstrate
    connectToDB();
    imageURLs = makeDBCall();

    GridPane root = new GridPane();
    Scene theScene = new Scene(root);
    stage.setTitle("Some scene");
    stage.setScene(theScene);

    root.setPadding(new Insets(10,10,10,10));
    root.setHgap(10);
    root.setVgap(10);

    int cols=2, colCnt = 0, rowCnt = 0;
    for (int i=0; i<imageURLs.size(); i++) {
        root.add(imageURLs.get(i).imageView, colCnt, rowCnt);
        colCnt++;
        if (colCnt>cols) {
            rowCnt++;
            colCnt=0;
        }
    }


    // in terms of auto update, instead of gridpane, I suggest you look into TableView, and cell factories.
    // once you have bound your cell factories, you can make calls to your DB, and the values bound will update automatically
    //http://www.java2s.com/Tutorials/Java/JavaFX/0650__JavaFX_TableView.htm

    stage.initStyle(StageStyle.UNDECORATED); //remove this is you want to see the title bar etc.
    stage.show();
}

class ImageDataObjs {
    final ImageView imageView;
    String imgURL, price;

    public ImageDataObjs(String imgURL, String price) {
        this.imgURL = imgURL;
        this.price = price;
        Path imagePath = Paths.get(imgURL);
        File imageFile = imagePath.toFile();
        Image image = new Image(imageFile.toURI().toString());
        this.imageView = new ImageView(image);
    }
}

//there a million examples of theis on the web
private List<ImageDataObjs> makeDBCall() {
    List<ImageDataObjs> imageDataObjList = new ArrayList<>();
    String myPrice, myURL;
    try {

        Statement statement = connect.createStatement();
        ResultSet resultSet = statement
                .executeQuery("select * from myProductList"); //you need to have a table called myProductList in your database

        while (resultSet.next()) {
            myPrice = resultSet.getString("myImageURL"); //these are the SQL cols that you should have already created in your database
            myURL = resultSet.getString("somePriceData");
            imageDataObjList.add(new ImageDataObjs(myURL, myPrice));
        }
        connect.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

    /*
    JUST FOR EXAMPLE - this would come from your database query
     */

    imageDataObjList.add(new ImageDataObjs(Const.BASE_DIRECTORY + "png/bridge.png", "1.99"));
    imageDataObjList.add(new ImageDataObjs(Const.BASE_DIRECTORY + "png/bridge.png", "2.99"));
    imageDataObjList.add(new ImageDataObjs(Const.BASE_DIRECTORY + "png/bridge.png", "3.99"));
    imageDataObjList.add(new ImageDataObjs(Const.BASE_DIRECTORY + "png/bridge.png", "4.99"));
    imageDataObjList.add(new ImageDataObjs(Const.BASE_DIRECTORY + "png/bridge.png", "5.99"));
    imageDataObjList.add(new ImageDataObjs(Const.BASE_DIRECTORY + "png/bridge.png", "6.99"));
    imageDataObjList.add(new ImageDataObjs(Const.BASE_DIRECTORY + "png/bridge.png", "6.99"));

    return imageDataObjList;
}

private void connectToDB() {
    //Note: you'll still it in tutorials, but Class.forName() is not needed since JDBC 4.0.
    //make sure but this point that MYSQL is installed, and that ConnectorJ is also installed.
    //create a database called "someDatabase" - make sure user and password are are you installed them.
    try {
        connect =
                DriverManager.getConnection("jdbc:mysql://localhost/someDatabase" +
                        "?user=root&password=root");
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

}

wax_lyrical
  • 922
  • 1
  • 10
  • 22
  • hello, thanks so much for your response and i sincerely do appreciate. I already tried out the code you helped with, but couldn't see the images represented on my ImageView. and there is no error being catched. – Derin S Aug 08 '17 at 23:44
  • Okay, I've changed the code to images for you. Hope that helps. You'll need to change the Const.BASE_DIRECTORY to something on your local drive. Please remark correct, if this helped. – wax_lyrical Aug 09 '17 at 08:35
  • thanks so much @wax_lyrical, i sincerely do appreciate your time to helping out resolve this issue. what if i do like to get the image already saved in my database, which will be used to create my dynamic GridPane, how can i go about it, because i have tried converting from byte to image to be viewed, but nothing was coming up on the screen, moreoever, i am not getting any error. – Derin S Aug 09 '17 at 10:21
  • If it's an actual image, it will likely be a BLOB type, I think (without checking). Here is an example http://www.java2s.com/Code/Java/Database-SQL-JDBC/GetBLOBdatafromresultset.htm – wax_lyrical Aug 09 '17 at 11:23
  • Then you need to go here, to convert a Blob to an image. https://stackoverflow.com/questions/2150265/retrieve-an-image-stored-as-blob-on-a-mysql-db . Good luck. – wax_lyrical Aug 09 '17 at 11:33
  • it works, thanks so much for your time and explanation, i sincerely do appreciate. One more thing i do like to ask is, how can i get root.add(imageURLs.get(0).imageView, 0, 0); root.add(imageURLs.get(1).imageView, 0, 1); root.add(imageURLs.get(2).imageView, 0, 2); root.add(imageURLs.get(3).imageView, 1, 0); dynamic i.e, using a for loop statement to declare all these, instead of having to code it in my program. Should in case more images are added to the database. – Derin S Aug 10 '17 at 06:52
  • I've added something simple to your code. Now, I wish you good luck, you should have enough information now to proceed. – wax_lyrical Aug 10 '17 at 12:41
  • i am just seeing this now. Thanks so much @wax_lyrical , i sincerely do appreciate your assistance. I don't know if you see the updated code of mine, because i am finding it difficult to use my fxml generated code with it. that's the structure i updated above please. – Derin S Aug 10 '17 at 14:46
  • moreover, I am getting null pointer, if i should use the GridPane i created with my FXML. How can i get it resolved please? – Derin S Aug 10 '17 at 17:31
  • now working as expected, thanks so much for your support @wax_lyrical – Derin S Aug 10 '17 at 20:16