Tag Archives: JAVA

Basics of GUI’s w/ Swing

often GUI (Graphical User Interface) development goes unmentioned. This is a quick lesson on how to get started with a Java-based GUI of your own.

Why do we care about GUIs?  Most software applications today have to have some sort of user control over them, and this is often accomplished through GUIs.

We’ll start with the idea of a frame. The frame is an box that can house your application, move around the window, resize etc. To make a frame in java is very simple.  All you have to do is create a JFrame object and tell it to be visible.

For example:

JFrame myFrame = new JFrame("Frame Title");

// Make sure to kill the process when you hit the close button
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Set the Size so that you will be able to see the frame
myFrame.setSize(400,400);

// Makes it show up!
myFrame.setVisible(true);

This example will simply make a frame with a title “Frame Title” and size 400px by 400px show up on your screen. When you hit the X button it will exit the process and close the frame. We can make our GUI’s cooler and more useful by using panels. Panels are containers for components that live inside of frames. In Java we use JPanel objects.  To add a JPanel to the above frame, simply add the following code:

JPanel firstPanel = new JPanel(new BorderLayout());
firstPanel.setSize(400,400);
myFrame.add(firstPanel);

This code will add a new JPanel called  firstPanel to the frame we created earlier. To a new user, all of the above code should be pretty straightforward except possibly new BorderLayout(). This piece of code allows the Panel to organize the components inside of it if it uses a specific layout manager. If this piece of code was omitted, the panels layout manager would be null and it would only be able to do absolute positioning of components inside it. There are a variety of layout managers already provided by default, so before trying to go make your own check out what is already offered here: http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html.

Additionally, you can add components to your panels. Components can be a variety of things such as text fields or text areas, buttons, or drop down lists.  A list of all Java premade components can be found here http://docs.oracle.com/javase/tutorial/ui/features/components.html

By using a combination of these components and panels you can create a variety of looks and input forms for your user to input data.

Hope you enjoyed this quick introduction. Make sure to play around with this stuff as next week we will discuss how to use events to make these components do a variety of tasks.

TJ

Let the Servlet’s Serve Us – Java Servlets 101

Yo yo yo… Hope everyone is having a grand old Thursday. Actually if you are reading this I am currently on a plane to Seattle…. can u say WIN :). O

Ok.. so as per the title above this post is about servlets. Now since I know you all know everything there is to know about the Internet, networking, http, etc. I am just going to skip to the good stuff… just kidding.

So it all starts with understanding the idea of a website, specifically http. OK, so you want to go to google.com, your browser or whatever application that is going to get the site for you sends an application layer (wikipedia: OSI layers) http request to the webserver that google.com points to (wikipedia: DNS). All this is done via socket connections, normally over port 80, the default http port.  Magically this request gets to the server and the server’s web hosting application must process it. This application interprets the request and then responds by sending back a stream of text, the html code of the webpage. Then your browser parses this code and finds other neccessary files. For example, it may pull images from other webpages in order to render the page. It requests these files from the server and the server responds in turn. So we have this sequence of events:
User ->(GIVE ME GOOGLE.COM)->browser Request index.html from google.com -> Server browser
<- Response index.html as text stream
browser Request img1.jpg from google.com -> Server User <- GOOGLE.COM <- browser <- Response img1.jpg as byte stream

This request/response structure is how all webpages are built by your browser… ok, wait, weren’t we talking about servlets? Right, so where do they fit in? Servlets can be thought of as mini-page servers, so if we take our block diagram for website hosting and we insert a java program that can handle these requests on the server by executing you write you would have a servlet container. I will show you.

So your Java code can run within the servlet container and serve web pages to your user. There are two ways to approach servlets, creating actual java servlets, extending that class from the api etc or you can use pages called jsp’s. Jsp’s stand for JavaServer Pages. These pages are java code are compiled by the container when a request for them is made, and can be very useful and simple to implement.

Ok before I wrap up a quick example on how/why to use a JSP. Say we want a website that can keep track of how many users have visited it, this would be a great place to use a jsp. First off install tomcat or another servlet/jsp hosting software on your local machine. I personally like tomcat, here is a link on how to get started with that http://tomcat.apache.org/

Next we have to write a jsp. So once you have tomcat running you will have to make a JSP file in a new web-application folder. To do this make a new file called index.jsp in new folder called watever you like, i will call mine bob in this directory TOMCAT_INSTALL_DIRECTORY/web-apps/. Now open index.jsp in your favorite text editor I recommend notepad++(google is your friend). Once in there paste in this code

<%!
int count = 0;
%>
<%
count++;
out.println(count);
%> 

First thing to note about above that all code between the <% %> is java code that will be compiled by tomcat when your webpage is polled. the <%! means that block is global and that variable will reside between webpage calls on the server and can be updated. So this page when called will simply print out the value of count after it is incremented, visit http://localhost:8080/bob/index.html  in your browser to see this effect. out is the default print out stream for an http response. Every jsp is passed impliciet information from the request and is given the ability to modify its response to that request. This is done by interacting with the request and the response objects that you magically have access to in your jsp. To see kinda what im talking about add the line out.println(request.getParameter(“HELLOWORLD”)); after the print out of count. Now when you call your webpage in tomcat at http://localhost:8080/bob/index.html it should print out the number and null. If you modify this page request with the parameter HELLOWORLD you can have it print out what you pass. So try this, http://localhost:8080/bob/?HELLOWORLD=OMG_IT_WORKS!!!

Hope you enjoyed getting your feet wet in Servlets, hit me up on facebook or at m5 with any questions

-TJ http://umassamherstm5.org/about/people/staffers/tj-pavlu

 

Starting with Sockets – Java Style

Ok this week its time to switch it up. Last week was about what has been happening today I think I’m going to go for a more technical approach.

 

So Sockets… What are they. It all starts with Network theory.. Don’t worry I’m not going to get that technical because honestly its DRY. For all intents and purposes a network, usually the internet we can call a magical highway of information. This information is routed using addresses called ip-addresses. I am not going to explain how this is done or etc just that if you put in my address and send information it should end up at me, well most of the time. Another thing about the internet is that its underlying structure provides 0 guarantee that information will actually arrive at its destination, that being said using different protocols namely TCP(Transmission Control Protocol) that guarantee can be provided.

Once again… So Sockets. A socket can simply be though of as an organizational bin within your address. Each application on your machine that uses the network can open different sockets. These sockets will be the location it will transmit and receive information only meant for itself at. Each socket has an associated port number which acts as the address of that socket on that machine.

 

Sockets can allow applications to communicate data over a network. The simplest example would be a turn by turn communication between two different applications. A really good example for this is provided on the java website. Its called a knock knock server. Lets Take a look…

The whole Example is located at http://download.oracle.com/javase/tutorial/networking/sockets/clientServer.html.

The example is simple. You have a server and a client, in this situation the server could be any machine that could run the “server” application not necessarily some big honking web server out there. The main difference between the server and client applications is that that the server is the “listener” and the client is the initiator. The server must start running and be waiting for a client to connect. Once the client application runs and connects then communication can commence, at the application level. So how does the server application listen for a connection, simple you use a ServerSocket :). In there code you will see the following

serverSocket = new ServerSocket(4444);

clientSocket = serverSocket.accept();

The first line simply opens a listening socket on port 4444. This tells us that our client application will have to try to connect on this port. The second line waits for a client to connect and then accepts that connection and stores it in another Socket object once the client connects which will allow communication to continue. Those two lines are the only real java.net code being used in this application the rest is just using input/output streams to send data just like you would to any file handler.

Lets take a look at the client side now, which is even simpler.

kkSocket = new Socket(“taranis”,4444);

This line simply says make a new Socket object and try to connect it to a computer hostname taranis, if this throws you off google DNS or hostnames, on port 4444 (like we said earlier). This code could also be modified to simply take in the IP address of taranis and it should work just as well. ex. kkSocket = new Socket(“192.168.1.2”,4444); Once again the rest of the code is just manipulation of streams in java.

Well that was the basics, if your interested like you should be check out the following to really get your teeth in… Continue onto the multi-user chat section of this tutorial, also look into Threads in java, UDP/Datagram Sockets, Java’s NIO Package. As always Oracle’s website, javaworld.com, and stackoverflow.com are probably your best resources for assistance investigating all of these, and feel free to send me some mail or stop on by to ask me some questions.

 

Happy Coding 🙂

-TJ

http://umassamherstm5.org/about/people/staffers/tj-pavlu