Conseils java

Fermé
nathaliej - Modifié le 8 avril 2020 à 18:19
KX Messages postés 16737 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 18 mai 2024 - 8 avril 2020 à 18:10
Bonjour,

Je débute en Java et j'aimerais avoir un avis et des conseils sur une "application météo" que j'ai créée et notamment sur l'organisation du code (classes et constructeur).

Voici le lien du repo : https://github.com/nathaliejouet/application-meteo

Merci par avance :)

import java.awt.*;

public class Main {

        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new Window("Station");
                }
            });
        }
    }

import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;

public class Component {

    private String text;
    private String tempMin;
    private String tempMax;

    public Component() {
    }

    public String getTempMin() {
        return tempMin;
    }

    public void setTempMin(String tempMin) {
        this.tempMin = tempMin;
    }

    public String getTempMax() {
        return tempMax;
    }

    public void setTempMax(String tempMax) {
        this.tempMax = tempMax;
    }
}

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONObject;


    public class Window extends JFrame {

        private JPanel panel;
        private JPanel otherInfo;
        private JLabel tempMin;
        private JLabel tempMax;
        private JTextField text;
        private JButton button1;
        private int minimumValue;
        private int maximumValue;

        Component comp = new Component();

        public void getMeteo(String ville) {

            String apiKey = "Mm9MUoEpVsLqE2GpuoorkdcWH7rNaGHx";
            String req1 = "http://dataservice.accuweather.com/locations/v1/cities/search?apikey=" + apiKey + "&q=" + ville;

            OkHttpClient client = new OkHttpClient();
            Request request1 = new Request.Builder()
                    .url(req1)
                    .build();
            Call call = client.newCall(request1);
            call.enqueue(new Callback() {
                @Override
                public void onResponse(Call call, Response response) throws IOException {

                    if (response.isSuccessful()) {
                        JSONArray array = new JSONArray(response.body().string());
                        if(array.length() != 0) {
                            JSONObject item = (JSONObject) array.get(0);
                            String key = (String) item.get("Key");

                            String req2 = "http://dataservice.accuweather.com/forecasts/v1/daily/1day/" + key + "?apikey=" + apiKey + "&language=fr-FR&metric=true";

                            Request request2 = new Request.Builder()
                                    .url(req2)
                                    .build();
                            Call call2 = client.newCall(request2);

                            call2.enqueue(new Callback() {
                                @Override
                                public void onResponse(Call call, Response response2) throws IOException {
                                    if (response2.isSuccessful()) {
                                        JSONObject object = new JSONObject(response2.body().string());
                                        JSONArray dailyForecasts = object.getJSONArray("DailyForecasts");

                                        JSONObject day = (JSONObject) dailyForecasts.get(0);

                                        JSONObject temperature = (JSONObject) day.get("Temperature");

                                        JSONObject minimum = (JSONObject) temperature.get("Minimum");
                                        minimumValue = minimum.getInt("Value");

                                        JSONObject maximum = (JSONObject) temperature.get("Maximum");
                                        maximumValue = maximum.getInt("Value");

                                        comp.setTempMin(minimumValue+ "°");
                                        tempMin.setText(comp.getTempMin());
                                        System.out.println("Température minimum : " + tempMin.getText() + System.getProperty("line.separator"));

                                        comp.setTempMax(maximumValue+ "°");
                                        tempMax.setText(comp.getTempMax());
                                        System.out.println("Température minimum : " + tempMax.getText() + System.getProperty("line.separator"));
                                    }
                                }

                                @Override
                                public void onFailure(Call call, IOException e) {
                                    System.out.println("Erreur");
                                }
                            });
                        } else {
                            text.setText("Cette ville n'existe pas");
                        }
                    }
                }
                @Override
                public void onFailure(Call call, IOException e) {
                    System.out.println("Erreur");
                }
            });

        }

        public Window(String title) {

            setSize(600, 400);
            setTitle(title);
            setLocationRelativeTo(null);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);

            panel = new JPanel();
            otherInfo = new JPanel(new GridLayout(2,2));
            tempMin = new JLabel("Température minimale", SwingConstants.CENTER);
            tempMin.setBorder(BorderFactory.createEmptyBorder(-50, 0, 0, 0));
            tempMax = new JLabel("Température maximale", SwingConstants.CENTER);
            tempMax.setBorder(BorderFactory.createEmptyBorder(-50, 0, 0, 0));


            otherInfo.add(tempMin);
            otherInfo.add(tempMax);
            add(panel, BorderLayout.NORTH);
            add(otherInfo, BorderLayout.CENTER);

            text = new JTextField();
            text.setPreferredSize(new Dimension(150,60));
            panel.add(text);

            button1 = new JButton("OK");
            button1.setPreferredSize(new Dimension(100,60));
            button1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    getMeteo(text.getText());
                }
            });

        panel.add(button1);

        }
    }
A voir également:

1 réponse

KX Messages postés 16737 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 18 mai 2024 3 015
8 avril 2020 à 18:10
Bonjour,

Tu devrais séparer dans des classes distinctes ce qui manipule les données de accuweather d'une part et ce qui les affiche dans ta fenêtre Swing d'autre part (ce qui nécessitera de créer au moins une classe supplémentaire pour représenter la donnée que tu affiches).

Je t'invite aussi à revoir la pertinence de OkHttp, car il existe déjà une API HttpClient fournie de base par Java.
https://openjdk.java.net/groups/net/httpclient/intro.html

Tu pourrais également configurer des rapports sur la qualité de ton projet pour repérer d'éventuelles erreurs.
https://forums.commentcamarche.net/forum/affich-37597173-generer-des-rapports-sur-la-qualite-d-un-projet
0