0

I am trying to create an java/swing based application which shows weather. So far I have created background and textfield + button to get the location but I do not know how to connect it so it shows and changes the background to another image. I am sorry if that's a noob question, but I never did java before (just processing and arduino plus web design) and my uni forced me to use advanced java with knowledge I never did anything like that before.

Here is my code so far:

package AppPackage;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class ApplicationWidget extends JFrame implements ActionListener {

    ImageIcon basic;
    JLabel label1;
    JFrame frame;
    JLabel label;
    JTextField textfield;
    JButton button;




    public static void main (String[]args){        
        ApplicationWidget gui = new ApplicationWidget();
        gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gui.setVisible(true);
        gui.setSize(320, 480);






    }

    public ApplicationWidget() {

        setLayout(new FlowLayout());
        WeatherAPI weather = new WeatherAPI("44418");
        System.out.println(WeatherAPI.theWeatherRSS);
        for(int i = 0; i < WeatherAPI.weatherForecastList.size(); i++)
        {
            System.out.println(WeatherAPI.weatherForecastList.get(i).lowTemp + " " +
            WeatherAPI.weatherForecastList.get(i).highTemp);
        }

        label = new JLabel("Welcome! Please Enter your location");
        add(label);

        textfield = new JTextField(15);
        add(textfield);
        for(int i = 0; i < WeatherAPI.weatherForecastList.size(); i++)
        {
            System.out.println(WeatherAPI.weatherForecastList.get(i).lowTemp + " " +
            WeatherAPI.weatherForecastList.get(i).highTemp);
        }


        button = new JButton("Check weather");

        add(button);



        basic = new ImageIcon(getClass().getResource("basicback.jpg"));
        label1 = new JLabel(basic);
        add(label1);

        /*add design here*/
        /*add mouse interaction*/
        /*add image capture*/   
}

    @Override
    public void actionPerformed(ActionEvent e){

        JButton button = (JButton) e.getSource();
        if (e.getSource() == button){
            String data = textfield.getText();
            System.out.println(data);
        }

    }





}

And the WeatherAPI code:

    package AppPackage;
import java.net.*;
import java.util.regex.*;
import java.util.ArrayList;
import java.io.*;

public class WeatherAPI
{
    static String theWeatherRSS;
    static String theCity;
    static ArrayList<Forecast> weatherForecastList;

    //WeatherAPI(String string) {
   //     throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
   // }

    public class Forecast
    {
        String lowTemp;
        String highTemp;
    }

    /**
     *
     * @param city
     */
    public WeatherAPI(String city)
    {
        theCity = city;
        theWeatherRSS = getWeatherAsRSS(city);
        parseWeather(theWeatherRSS);
    }

    void parseWeather(String weatherHTML)
    {
        weatherForecastList = new ArrayList<Forecast>();
        int startIndex = 0;
        while(startIndex != -1)
        {
            startIndex = weatherHTML.indexOf("<yweather:forecast", startIndex);
            if(startIndex != -1)
            { // found a weather forecast
                int endIndex = weatherHTML.indexOf(">", startIndex);
                String weatherForecast = weatherHTML.substring(startIndex, endIndex+1);

                // get temp forecast                
                String lowString = getValueForKey(weatherForecast, "low");
                String highString = getValueForKey(weatherForecast, "high");

                Forecast fore = new Forecast();
                fore.lowTemp = lowString;
                fore.highTemp = highString;
                weatherForecastList.add(fore);

                // move to end of this forecast
                startIndex = endIndex;
            }
        }
    }

    String getValueForKey(String theString, String keyString)
    {
        int startIndex = theString.indexOf(keyString);
        startIndex = theString.indexOf("\"", startIndex);
        int endIndex = theString.indexOf("\"", startIndex+1);
        String resultString = theString.substring(startIndex+1, endIndex);
        return resultString;
    }

    String getWeatherAsRSS(String city)
    {
        try{
            /*
            Adapted from: http://stackoverflow.com/questions/1381617/simplest-way-to-correctly-load-html-from-web-page-into-a-string-in-java
            Answer provided by: erickson
            */
            URL url = new URL("http://weather.yahooapis.com/forecastrss?w="+city+"&u=c");
            URLConnection con = url.openConnection();
            Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*");
            Matcher m = p.matcher(con.getContentType());
            /* If Content-Type doesn't match this pre-conception, choose default and 
             * hope for the best. */
            String charset = m.matches() ? m.group(1) : "ISO-8859-1";
            Reader r = new InputStreamReader(con.getInputStream(), charset);
            StringBuilder buf = new StringBuilder();
            while (true) {
              int ch = r.read();
              if (ch < 0)
                break;
              buf.append((char) ch);
            }
            String str = buf.toString();
            return(str);
        }
        catch(Exception e) {System.err.println("Weather API Exception: "+e);}
        return null;
    }

}

Thanks for any help, I am truly desperate because I have mixed up the dates of submission and I have not much time left....

Swirly
  • 11
  • 1
  • 3
  • is `label1` your background? And where are you getting the new images from? – Paul Samsotha Mar 11 '14 at 18:05
  • Welcome to Stack Overflow. Please don't dump all your code here, just show us what you have tried to solve your problem, so we can have guidelines to help you. – Cthulhu Mar 11 '14 at 18:15
  • my background is label1 so 'basic' and images I have in AppPackage package, thanks. @Cthulhu Sorry for that as I've said programming isn't my thing and I never had trouble with processing which I;ve done last year to ask anywhere. Thanks – Swirly Mar 11 '14 at 19:01

1 Answers1

1

Assuming label1 is your background label, just use label1.setIcon(...). What you will pass to it is a new ImageIcon

Also you haven't registered the ActionListener to your button. If you don't register a listener to the button, it won't do anything. Do this

button = new JButton("Check weather");
button.addActionListener(this);
add(button); 

You haven't specified where the new image is coming from, so I really can't help you any further than this.

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • Hi thanks for help! Button works now but I am not sure how to connect it to check the weather from WeatherAPI to display correct background according to the forecast itself. I was thinking about if...else if statements – Swirly Mar 11 '14 at 19:05
  • I see nothing wrong with if/else statements. `if (something) { label1.setIcon(someIcon); }` – Paul Samsotha Mar 11 '14 at 19:17
  • There is only one thing I don't really get how to connect to the statement though - how to match up the input (data string) with WEather API (f.ex. if they put 'London' it displays the data connected just to london). Any idea? Sorry for so many questions, I have tried to look that up but came out with nothing at all (or things so complicated that I don't even know where is what). Thanks – Swirly Mar 11 '14 at 19:41
  • Sorry but I have no idea how your WeatherAPI works. For instance what is returned back from what that will determine what image to pop up. – Paul Samsotha Mar 11 '14 at 19:50
  • The WeatherAPI is Yahoo one, thanks. We got it on our class, the whole code we were provided with is on my question. Cheers – Swirly Mar 11 '14 at 20:10