简体   繁体   English

从按钮调用Java类

[英]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 我有一个将csv转换为shapefile的java类,它可以正常工作...现在,我想创建带有boutton的w Java应用程序,以便... ...因此我必须将按钮与csv2shape类关联... ana我真的不知道该怎么做..这是我的代码的一部分,它解释了我尝试做的事情并且它确实起作用

               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 以及csv转换器的代码

        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 任何帮助,我都会很高兴...谢谢

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 . 主要问题是CSV的逻辑在Csv2shapemain方法之Csv2shape You are not calling this method within your event handler, since you are just doing new Csv2shape(); 您没有在事件处理程序中调用此方法,因为您只是在做new Csv2shape(); .

To fix this, you could simply do: Csv2shape.main(null); 解决此问题,您只需执行以下操作: 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). ,这将调用具有逻辑的main方法,但是,不建议这样做(您的代码最多应有1个main方法,并且应避免自己调用它)。 So solve your problem, I would recommend that you move your logic found in main into some other method, such as private void createCSV() . 因此,解决您的问题,我建议您将main找到的逻辑移到其他方法中,例如private void createCSV() In your Csv2shape constructor, you do a call to this method: public Csv2shape() { this.createCSV();} . Csv2shape构造函数中,您对此方法进行了调用: 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. 这样做的问题在于,您正在处理事件分派线程(EDT)上的文件,该线程是处理所有UI操作的线程,因此,对该线程执行沉重的非UI操作将对用户的体验产生不利影响。

To solve this problem, simply launch the Csv2shape constructor in a new thread. 要解决此问题,只需在新线程中启动Csv2shape构造函数即可。 This will take off the load from the EDT: 这将减轻EDT的负担:

Thus, replace new Csv2shape(); 因此,替换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: 如果您在以下位置跟随我的示例,这就是Csv2shape类的外观:

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();
    }
}

I am seeing that in actionPerformed method you are only making the object of your Csv2shape class. 我看到在actionPerformed方法中,您仅使Csv2shape类的对象。 In order to do your work pull your code from main method to some other method say convertToShape(). 为了完成您的工作,请将代码从main方法拉到其他方法,例如convertToShape()。 Now from your actionPerformed method call your this method as new Csv2shape().convertToShape(). 现在,从actionPerformed方法中将此方法作为新的Csv2shape()。convertToShape()进行调用。 This will work. 这将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM