reda
reda

Reputation: 25

calling java class from button

i have a java class that convert csv to a shapefile it works fine ...now i want to create w java application with bouttons that can di that ... so i have to associate the button to the csv2shape class ... ana i really dont know how to do that .. here a part of my code that explains what i tried to do and it dosent works

               public class GestionTournee {

private JFrame frame;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                GestionTournee window = new GestionTournee();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public GestionTournee() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Button button = new Button("New button");
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            new Thread(new Runnable()  {
                 public void run() {
                     new Csv2shape();
                 }
            }).start();
        }
    });
    frame.getContentPane().add(button, BorderLayout.NORTH);
}

}

and also the code for the csv converter

        public class Csv2shape {


public static void main(String[] args) throws Exception {
    // Set cross-platform look & feel for compatability
    UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());

    File file = JFileDataStoreChooser.showOpenFile("csv", null);
    if (file == null) {
        return;
    }
    /*
     * We use the DataUtilities class to create a FeatureType that will describe the data in our
     * shapefile.
     * 
     * See also the createFeatureType method below for another, more flexible approach.
     */
    final SimpleFeatureType TYPE = DataUtilities.createType(    "Location",
            "the_geom:Point:srid=4326," + // <- the geometry attribute: Point type
            "Date:String," +   // <- a String attribute
            "NombreAr:Double," +   // <- a String attribute     
            "vitesse:String," +   // <- a String attribute
            "distance:Double"   // a number attribute


    );
    System.out.println("TYPE:"+TYPE);

     /* A list to collect features as we create them.
     */
    List<SimpleFeature> features = new ArrayList<SimpleFeature>();

    /*
     * GeometryFactory will be used to create the geometry attribute of each feature,
     * using a Point object for the location.
     */
    GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();

    SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);

    BufferedReader reader = new BufferedReader(new FileReader(file));
    try {
        /* First line of the data file is the header */
        String line = reader.readLine();
        System.out.println("Header: " + line);
        boolean foundAnyRowHigherThan4 = false;
        double s =0;
        boolean foundAnyRowHigherThan5 = false;
        boolean checker = true;
        double Longitude2 = 0;
        double Latitude2 = 0;
        double Dis = 0;
        double dis = 0;
        for (line = reader.readLine(); line != null; line = reader.readLine()) {
            if (line.trim().length() > 0) { // skip blank lines
                {
                    if(checker){
                    String currentTokens[] = line.split("\\,");
                    String currentName1 = currentTokens[0].trim();
                    String currentName2 = currentTokens[1].trim();
                    Longitude2 = Double.parseDouble(currentTokens[2]);
                    Latitude2 = Double.parseDouble(currentTokens[3]);
                    checker = false ;
                    continue;
                    } 




                String tokens[] = line.split("\\,");
                String name1 = tokens[0].trim();
                String name2 = tokens[1].trim();
                double longitude = Double.parseDouble(tokens[2]);
                double latitude = Double.parseDouble(tokens[3]);



                String speedString = tokens[5].trim();
                double dist = Double.parseDouble(tokens[4]);
                float speedFloat = Float.parseFloat(speedString);



              if(foundAnyRowHigherThan5 || speedFloat > 5.0) {
                // a partir de ce point on ajoutera touts les points ,
                if(!foundAnyRowHigherThan5) {
                  foundAnyRowHigherThan5 = true;
                }


                if(foundAnyRowHigherThan4 || speedFloat < 1.0) {
                    // a partir de ce point on ajoutera touts les points d'arrets,
                   if(speedFloat <0.1)
                    s = s+1 ;
                    else 
                      foundAnyRowHigherThan4 = true;
                    }


                /* Longitude (= x coord) first ! */
                Point point = geometryFactory.createPoint(new Coordinate(longitude, latitude));
                featureBuilder.add(point);

                double earthRadius = 6371; //km pour la changer en metres faut ajouter 000  a la fin 
                double dLat = Math.toRadians(latitude-Latitude2);
                double dLng = Math.toRadians(longitude-Longitude2);
                double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                           Math.cos(Math.toRadians(Latitude2)) * Math.cos(Math.toRadians(latitude)) *
                           Math.sin(dLng/2) * Math.sin(dLng/2);
                double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
                double d = (float) (earthRadius * c);

                dis = d+dis;




                featureBuilder.add(name1);
                featureBuilder.add(s);

                featureBuilder.add(speedString);
                featureBuilder.add(dis);
                SimpleFeature feature = featureBuilder.buildFeature(null);

                features.add(feature);

                Longitude2 = longitude;
                Latitude2 = latitude;

                }
            }
        }

        }  
    } 
        finally {
        reader.close();
    }

any help i ll be greatefull ... thank you

Upvotes: 0

Views: 79

Answers (2)

npinti
npinti

Reputation: 52185

You are wiring the event handler mostly correctly (more on that later).

The major problem is that your logic for the CSV is within the main method of your Csv2shape. You are not calling this method within your event handler, since you are just doing new Csv2shape();.

To fix this, you could simply do: Csv2shape.main(null);, this would call your main method which has the logic, however, this is not recommended (you should have, at most, 1 main method on your code, and you should refrain from calling it yourself). So solve your problem, I would recommend that you move your logic found in main into some other method, such as private void createCSV(). In your Csv2shape constructor, you do a call to this method: public Csv2shape() { this.createCSV();}.

The above should trigger the calls you need.

As I said in the beginning, the event handler creation is mostly correct. The problem with that is that you are processing the file on the Event Dispatching Thread (EDT) which is the thread which handles all of your UI operations, thus, performing heavy non UI operations on this thread will have a detrimental effect on your user's experience.

To solve this problem, simply launch the Csv2shape constructor in a new thread. This will take off the load from the EDT:

Thus, replace new Csv2shape(); with:

new Thread(new Runnable()  {
     @Override
     public void run() {
         new Csv2shape();
     }
}).start();

EDIT:

This is how the Csv2shape class should look if you where to follow my example:

public class Csv2shape {

public Csv2shape() {
    try {
        this.createCSV();
    }
    catch(Exception e) {
        e.printStackTrace();  //Or someother means of logging.
    }

}
private void createCSV() throws Exception {
    // Set cross-platform look & feel for compatability
    UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());

    File file = JFileDataStoreChooser.showOpenFile("csv", null);
    if (file == null) {
        return;
    }
    /*
     * We use the DataUtilities class to create a FeatureType that will describe the data in our
     * shapefile.
     * 
     * See also the createFeatureType method below for another, more flexible approach.
     */
    final SimpleFeatureType TYPE = DataUtilities.createType(    "Location",
            "the_geom:Point:srid=4326," + // <- the geometry attribute: Point type
            "Date:String," +   // <- a String attribute
            "NombreAr:Double," +   // <- a String attribute     
            "vitesse:String," +   // <- a String attribute
            "distance:Double"   // a number attribute


    );
    System.out.println("TYPE:"+TYPE);

     /* A list to collect features as we create them.
     */
    List<SimpleFeature> features = new ArrayList<SimpleFeature>();

    /*
     * GeometryFactory will be used to create the geometry attribute of each feature,
     * using a Point object for the location.
     */
    GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();

    SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);

    BufferedReader reader = new BufferedReader(new FileReader(file));
    try {
        /* First line of the data file is the header */
        String line = reader.readLine();
        System.out.println("Header: " + line);
        boolean foundAnyRowHigherThan4 = false;
        double s =0;
        boolean foundAnyRowHigherThan5 = false;
        boolean checker = true;
        double Longitude2 = 0;
        double Latitude2 = 0;
        double Dis = 0;
        double dis = 0;
        for (line = reader.readLine(); line != null; line = reader.readLine()) {
            if (line.trim().length() > 0) { // skip blank lines
                {
                    if(checker){
                    String currentTokens[] = line.split("\\,");
                    String currentName1 = currentTokens[0].trim();
                    String currentName2 = currentTokens[1].trim();
                    Longitude2 = Double.parseDouble(currentTokens[2]);
                    Latitude2 = Double.parseDouble(currentTokens[3]);
                    checker = false ;
                    continue;
                    } 




                String tokens[] = line.split("\\,");
                String name1 = tokens[0].trim();
                String name2 = tokens[1].trim();
                double longitude = Double.parseDouble(tokens[2]);
                double latitude = Double.parseDouble(tokens[3]);



                String speedString = tokens[5].trim();
                double dist = Double.parseDouble(tokens[4]);
                float speedFloat = Float.parseFloat(speedString);



              if(foundAnyRowHigherThan5 || speedFloat > 5.0) {
                // a partir de ce point on ajoutera touts les points ,
                if(!foundAnyRowHigherThan5) {
                  foundAnyRowHigherThan5 = true;
                }


                if(foundAnyRowHigherThan4 || speedFloat < 1.0) {
                    // a partir de ce point on ajoutera touts les points d'arrets,
                   if(speedFloat <0.1)
                    s = s+1 ;
                    else 
                      foundAnyRowHigherThan4 = true;
                    }


                /* Longitude (= x coord) first ! */
                Point point = geometryFactory.createPoint(new Coordinate(longitude, latitude));
                featureBuilder.add(point);

                double earthRadius = 6371; //km pour la changer en metres faut ajouter 000  a la fin 
                double dLat = Math.toRadians(latitude-Latitude2);
                double dLng = Math.toRadians(longitude-Longitude2);
                double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                           Math.cos(Math.toRadians(Latitude2)) * Math.cos(Math.toRadians(latitude)) *
                           Math.sin(dLng/2) * Math.sin(dLng/2);
                double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
                double d = (float) (earthRadius * c);

                dis = d+dis;




                featureBuilder.add(name1);
                featureBuilder.add(s);

                featureBuilder.add(speedString);
                featureBuilder.add(dis);
                SimpleFeature feature = featureBuilder.buildFeature(null);

                features.add(feature);

                Longitude2 = longitude;
                Latitude2 = latitude;

                }
            }
        }

        }  
    } 
        finally {
        reader.close();
    }
}

Upvotes: 1

Rahul
Rahul

Reputation: 317

I am seeing that in actionPerformed method you are only making the object of your Csv2shape class. In order to do your work pull your code from main method to some other method say convertToShape(). Now from your actionPerformed method call your this method as new Csv2shape().convertToShape(). This will work.

Upvotes: 0

Related Questions