Monday, February 12, 2018

JSON Array parsing in java

package App;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

public class App {
public static void main(String[] args) throws Exception {

URL url = new URL(
"http://openweathermap.org/data/2.5/weather?lat=17&lon=75&appid=b6907d289e10d714a6e88b30761fae22");

URLConnection con = url.openConnection();

BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));

JSONObject obj = (JSONObject) JSONValue.parseWithException(br);

JSONObject sys = (JSONObject) obj.get("sys");

// JSON ARRAY retrives the array

JSONArray weather = (JSONArray) obj.get("weather");

// First line of array and make JSON Object
JSONObject arr = (JSONObject) weather.get(0);

// Get by Key
String desc = (String) arr.get("description");

// Show
System.out.println(desc);

// JSONOBJECTS
long sunrise = (long) sys.get("sunrise");

long sunset = (long) sys.get("sunset");

double message = (double) sys.get("message");

String country = (String) sys.get("country");

br.close();

}

}

Tuesday, February 6, 2018

Show watch in Label JAVA

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Watch implements Runnable {

JFrame fr;
JPanel pa;
String time;
JLabel label;

public void UI() {

fr = new JFrame("Ding!");
label = new JLabel("Time");
pa = new JPanel();
pa.add(label);
fr.getContentPane().add(pa);
fr.setSize(200, 200);
fr.setVisible(true);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Thread t = new Thread(this);
t.start();

}
public void getTime() {

Date date = new Date();
SimpleDateFormat f = new SimpleDateFormat("hh:mm:ss");
time = f.format(date.getTime());

}

@Override
public void run() {

try {
while (true) {
getTime();
setTime();
Thread.sleep(1000);
}
} catch (Exception e) {}
}

public void setTime() {

label.setText(time);
}
public static void main(String[] args) {
new Watch().UI();
}
}