Search code examples
javaswingjlabel

JLabel's text is not changing


EDIT: Huge code re-organisation, old question here: http://pastebin.com/Mbg4dYiY

I have created a basic program that is designed to show the weather in a window using Swing. I am developing using IntelliJ and I have used the UI builder in that. I am attempting to fetch some information from the Weather Underground servers and then make a JLabel called weatherlabel display this information. However, the JLabel doesn't actually change in the window; it just stays as 'Weather Will Go Here'. How do I fix this?

Here is my main.java:

public class main {
    public static void main(String[] args) {
        System.out.println("Hello World!");
        Display d = new Display();
        d.getandsetWeather();
    }

}

Here is my Display.java:

public class Display {

    Display disp = this;

    public JPanel myPanel;
    public JLabel weatherfield;
    private JButton button1;

    public void init() {
        JFrame frame = new JFrame("Display");
        frame.setContentPane(new Display().myPanel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setMinimumSize(new Dimension(480, 234));
        frame.pack();
        frame.setVisible(true);
    }

    public void getandsetWeather() {
        String editedline = null;
        init();
        try {
            // Construct data
            String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
            data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");

            // Send data
            URL url = new URL("http://api.wunderground.com/api/772a9f2cf6a12db3/geolookup/conditions/q/UK/Chester.json");
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            String line;
            while ((line = rd.readLine()) != null) {

                if( line.contains("\"weather\":")) {
                    System.out.println(line);
                    editedline = line.replace("\"weather\":\"", "");
                    editedline = editedline.replace("\",", "");
                    System.out.println(editedline);
                    weatherfield.setText(editedline);
                }


            }
            wr.close();
            rd.close();
            weatherfield.setText(editedline);
            System.out.println(weatherfield.getText());
            weatherfield.repaint();
            weatherfield.revalidate();
        } catch (Exception e) {
            System.out.println("Error!" + e);
        }


    }

}

When I run the program, this is printed to the log:

Hello World!
        "weather":"Scattered Clouds",
        Scattered Clouds
        Scattered Clouds

Solution

    1. You seem to have a strange understanding of OOP and code-flow
    2. You have to main methods, one of which you are trying to call the other main method. Don't do that. A program should only have one main method. You should never have to this

      Display.main(new String[]{});
      
    3. Why even have this ChangeWeatherLabelText class? There is only one method, that doesn't seem to be needed in it's own class. Your instantiation if Display in that method does nothing to the rest of the program. So you call has no effect on the label.

    4. Instead of 3, put that method in the class that actually has the label and just reference the label field in the method.
    5. Also, GetWeather just seems like a helper class with a helper method. "Helper" class methods are useless if they don't return something.
    6. IMHO, you should restructure your entire program. Some things may work now, but there's a lot of bad practice going on in your code
    7. If I were to write this program, all the code would be in one file. If you insist on them being in separate files, you need to learn how to use constructors and how to pass objects to them. That is how you are going to manipulate objects from other classes. That is unless you understand the MVC model, which may be a little advance at this point for you.

    UPDATE with OP update of code

    Test this out and be sure to read the comments so you can see what I did. Let me know if you have any question.

    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.URL;
    import java.net.URLConnection;
    import java.net.URLEncoder;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    
    public class main {
        public static void main(String[] args) {
            System.out.println("Hello World!");
            new Display();                        // <-- just instantiate
        }
    
    }
    
     class Display {
    
        Display disp = this;
    
        public JPanel myPanel;               // <--------- Haven't been initialized 
        public JLabel weatherfield;
        private JButton button1;
    
        public Display() {                   // you need constructor to call init
            init();
        }
    
        public void init() {
            myPanel = new JPanel(new BorderLayout());    // initialize
            weatherfield = new JLabel(" ");              // initialize
            button1 = new JButton("Button");              // initialize
            myPanel.add(weatherfield, BorderLayout.CENTER);
            myPanel.add(button1, BorderLayout.SOUTH);
    
            button1.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e) {
                    getandsetWeather();                       // <-------- add listener to call getandsetweather
                }
            });
    
            JFrame frame = new JFrame("Display");
            frame.setContentPane(myPanel);   //   <--------------------- fix 1
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setMinimumSize(new Dimension(480, 234));
            frame.pack();
            frame.setVisible(true);
        }
    
        public void getandsetWeather() {
            String editedline = null;
            init();
            try {
                // Construct data
                String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
                data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
    
                // Send data
                URL url = new URL("http://api.wunderground.com/api/772a9f2cf6a12db3/geolookup/conditions/q/UK/Chester.json");
                URLConnection conn = url.openConnection();
                conn.setDoOutput(true);
                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                wr.write(data);
                wr.flush();
    
                // Get the response
                BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    
                String line;
                while ((line = rd.readLine()) != null) {
    
                    if( line.contains("\"weather\":")) {
                        System.out.println(line);
                        editedline = line.replace("\"weather\":\"", "");
                        editedline = editedline.replace("\",", "");
                        System.out.println(editedline);
                        weatherfield.setText(editedline);
                    }
    
    
                }
                wr.close();
                rd.close();
                weatherfield.setText(editedline);
                System.out.println(weatherfield.getText());
                weatherfield.repaint();
                weatherfield.revalidate();
            } catch (Exception e) {
                System.out.println("Error!" + e);
            }
    
    
        }
    
    }