Conor Mac Aoidh
http://macaoidh.name
conor@macaoidh.name
 

Search

Archives

  • September 2010
  • August 2010
  • July 2010
  • June 2010
  • April 2010
  • March 2010
  • December 2009
  • November 2009
  • October 2009
  • September 2009
  • July 2009
  • June 2009
  • May 2009
  • April 2009
  • March 2009
  • February 2009
  • January 2009
  • December 2008
  • November 2008
  • October 2008

Spam

4,906 spam comments
blocked by
Akismet

Tag Cloud

    1.0 beta CMS conor's management system conormacaoidh conor mac aoidh content management system download drums Fedora fedora 10 furasta furasta cms furasta org gnome hello world HTML icsp Java javascript joomla jquery kde Linux Mandriva mc kennas Monaghan Music mysql php plugin release Scratch stealing the ceiling The Dominican Affair the pot smoking pirates the strats tutorial Twitter updates web design forum webme webworks weekly tweets wordpress

Ads

Java Visual Hello World Popup

Posted Nov 15th, 2009 by Conor in in College,Java,Languages

I spent yesterday going a bit deeper into Java with one of my lecturers. I decided to try and write a more complicated hello world app. It’s quite simple really once you get around the strict OOP and different syntax… This is how I did it:

First you need to import some of the java libraries that we will be using:

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;

Then add the class, Popup. Make sure to name the file Popup.java

public class Popup{
private JFrame frame=new JFrame("Hello!");
private JPanel panel=new JPanel();
private JButton button=new JButton("Say Hello");
private JLabel label=new JLabel("Click the button to say hello...",SwingConstants.CENTER);
private ButtonListener buttonListener=new ButtonListener();

What that actually means is create a new instance of JFrame, JPanel, JButton and JLabel and store them in the frame,panel, button and label variables. As for the ButtonListener, we will deal with that later. Now we will deal with the launchFrame function which does what it says on the tin – launches the frame! Basically it just connects all of the pieces of information stored into the variables above and displays them together.

public void launchFrame(){
int height=400, width=600;
frame.setSize(width,height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Above we create two new integers which store the width and height of our frame. The next line sets the variables to the frame size. The final line tells the Java application to close when the window, or JFrame, is closed. Now that we have the configuration out of the way we can move on to adding the variables to the frame.

frame.getContentPane().add(label,BorderLayout.CENTER);
panel.add(button);
frame.getContentPane().add(panel,BorderLayout.WEST);
button.addActionListener(buttonListener);
frame.setVisible(true);
}

The code above adds the label to the frame, then adds the button to the panel and then the panel to the frame. Once again disregard the button.addAction.. line for now. The final line simply sets the frame to visible so we can see it.

Now that we have the frame settled, we need to add our essential main function to start up the execution:

public static void main(String args[]){
Popup popup=new Popup();
popup.launchFrame();
}
}

This code basically creates an instance of our class, Popup and then executes the function launchFrame which we have created in that class.

That’s the guts of it, but now we need to talk about these lines:

private ButtonListener buttonListener=new ButtonListener();
 public void launchFrame(){
....
button.addActionListener(buttonListener);

Basically we have previously created a button, but these lines define what happens when the button is pressed. The second line of code tells the machine to listen out for the clicking of the button, and when that happens to execute the variable buttonListener. We have created the variable buttonListener, which creates a new instance of the ButtonListener class which we have yet to create.

That is the next step, to create that class. Create a new file called ButtonListener.java and add this code:

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonListener implements ActionListener{

The first four lines import the libraries that we are using. The final line is important. It states that our class, ButtonListener is implementing the ActionListener class. Below is the content of our new class:

private JFrame pressed=new JFrame("Hello World!");
public void actionPerformed(ActionEvent actionEvent){

First, we create a new JFrame for our popup just like we did in the other file. The function actionPerformed is a function from the ActionListener class that we are implementing. The parameters for the function are predefined so we need them. The rest of the code is very similar to the previous code so I won’t explain it in depth. Basically it just configures the new frame, adds the label and then displays it:

int height=160, width=200;
pressed.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel pressedtext=new JLabel("Hello World!",SwingConstants.CENTER);
pressed.getContentPane().add(pressedtext,BorderLayout.CENTER);
pressed.setSize(width,height);
pressed.setVisible(true);
}

Save that file and then compile both files by executing:

javac ButtonListener.java Popup.java

Now if you run the program you should see a nice visual dialogue:

java Popup

You can download a jar archive of the program here.

The full code is below. Popup.java:

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;

public class Popup{
        private JFrame frame=new JFrame("Hello!");
        private JPanel panel=new JPanel();
        private JButton button=new JButton("Say Hello");
        private JLabel label=new JLabel("Click the button to say hello...",SwingConstants.CENTER);
        private ButtonListener buttonListener=new ButtonListener();

        public void launchFrame(){
                int height=400, width=600;
                frame.setSize(width,height);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.getContentPane().add(label,BorderLayout.CENTER);
                panel.add(button);
                frame.getContentPane().add(panel,BorderLayout.WEST);
                button.addActionListener(buttonListener);
                frame.setVisible(true);
        }

        public static void main(String args[]){
                Popup popup=new Popup();
                popup.launchFrame();
        }
}

ButtonListener.java:

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;

public class ButtonListener implements ActionListener{
        private JFrame pressed=new JFrame("Hello World!");

        public void actionPerformed(ActionEvent actionEvent){
                int height=160, width=200;
                pressed.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                JLabel pressedtext=new JLabel("Hello World!",SwingConstants.CENTER);
                pressed.getContentPane().add(pressedtext,BorderLayout.CENTER);
                pressed.setSize(width,height);
                pressed.setVisible(true);
        }

}
3 responses so far

Creating A Jar Archive

Posted Apr 27th, 2009 by Conor in in Java,Languages

I made the HelloWorld class a few days ago in this post. I am getting a bit ahead of myself here but what if you have an application with many files? Do you let the user handle all those files yourself? No! The Java Archiving Format .jar is the solution. With it you can create an entire application and bring it down to one file. Then you can run the whole application from that file! This can be done with the option of compression aswell.

Anyway even though it seems useless to create a jar archive of one file I am going to create one for the HelloWorld.class. First I need to create a file in which to store the manifest. This file will contain crucial information about the application and how it is run. I am going to do the bare minimum at the moment but there are endless possibilities with this file! This is what I put in HelloWorld.mf:

Main-Class: HelloWorld
Name: class/
Sealed: true

The main class tells the application which class to load first. Name and sealed tell the application which folders to seal. You might want to seal a package to ensure version consistency among the classes in your software.

I now have two files; HelloWorld.class and HelloWorld.MF. Now I must compress them both into a jar archive and run the application. To create the jar archive execute:

jar cmf HelloWorld.mf HelloWorld.jar HelloWorld.class

Basically this says create a new jar archive including the manifest and the class file and locate it in a new file called HelloWorld.jar. Now the application is executable. To run it simply type:

java -jar HelloWorld.jar

You should see the same output from the original application:

[conor@host java]$ java -jar HelloWorld.jar
Hello World!

Simple as that!

No responses yet

Hello World – Java

Posted Apr 26th, 2009 by Conor in in Java,Languages,Linux

I wrote my first Java application today. Ir is traditional to start out with something simple and boy this is simple and it works!

First you need to download and install the Java Development Kit (JDK) from Sun here. Then change directory to your workspace – where ever you want! In my case it was:

cd /home/conor/java

Then open up a new file named HelloWorld.java in your favourite text editor. In my case it was:

vim HelloWorld.java

Now we start the coding:

class HelloWorld{
  public static void main(String[] args){
    System.out.println("Hello World!");
  }
}

This is basically just a class that tells Java to output the words ‘Hello World! Now the code must be turned into machine code so that it is faster to run. To do that simply type:

javac HelloWorld.java

This creates a new file named HelloWorld.class which is written in machine code. If you open this file in your text editor all you will see is a load of gobledeegook. Now the application is ready to run. Type the following command to run it:

java HelloWorld

You should then see Hello World! written on your screen like this:

[conor@host java]$ java HelloWorld
Hello World!

Another one in the bag!

3 responses so far

Collecting Data From Forms – PHP / MySQL

Posted Mar 20th, 2009 by Conor in in HTML,Languages,PHP

Today i had quite a few requests for the same thing on the Web Design Forum. So instead of writing a different answer to all of the threads I decided to summarise it all in a blog post on Collecting Data From Forms Using PHP and MySQL. Hopefully I will just be able to link back to this post when I get this question again!

What is PHP? PHP is a programing language with an easy to use syntax. It resembles C and Java. PHP is excecuted server side which means that if you want to do something with the language then you will have to send a request to the server. This is usually done by pointing to a PHP file to proccess information. It can also be done using AJAX without requiring a reload – but that’s a whole other ball game!

What is MySQL? MySQL is one of many Structured Query Languages. It is basically a language used to store and manipulate data through the use of databases. I have often compared it to Microsoft’s Excel – many people tell me that I’m wrong with that comparison but I think that it is valid!

PHP + MySQL = Dynamic Webpage. In my opinion MySQL and PHP have one common characteristic; they both have a user friendly syntax which is easy to learn and yet they both have the ability to unleash massive amounts of power once you delve into them! The combination of the two languages produces a constantly changing, dynamic website. For example you could have page content being called from the database and then to update that content all you need to do is update the database – rather than trawling through code.

If you are finding this all hard to follow don’t worry, I’m sure it will be a bit more self-explanatory when we look at some code. I am not going to go into the detail of downloading and installing PHP and MySQL. The following assumes that you have done so yourself – or that you are working on an online server with these packages pre-installed.

Setting Up MySQL

First you will need to create a new database and a new table for all of the information to be stored in. Enter this command to create the database:

create database form;

Quickly select that database – tell MySQL that you want to use it.

use form;

Then you will need to create a table which will store our information.

create table users (
user_id int not null auto_increment primary key,
username text,
email text,
password char(40) default null
);

Now that you have the MySQL side of things running you will need to connect to MySQL with PHP. The file below should be named ‘connect.php’.  /*These things are comments */

<?php

/* The name of the database that we have just created */

$dbname = 'form';

/* The hostname which will usually be localhost but change if appropriate */

$hostname = 'localhost';

/* Database Username and Password - you must change these to your own values*/

$dbuser = 'root';

$dbpass = '';

$connect = mysql_connect($hostname,$dbuser,$dbpass) or die('Could not connect to MySQL please insure that the connection information is correct');

mysql_select_db($dbname,$connect) or die('Could not select the database');

?>

Writing The Form

Now that we have written our connection information with PHP we must include that file in our main PHP file and write a form. This is a normal HTML form which collects information from users wishing to register to whatever.

<form method="post">
Username: <input type="text" name="username"/><br/>
Email: <input type="text" name="email"/><br/>
Password: <input type="password" name="password"/><br/>
Confirm: <input type="password" name="confirmpass"/><br/>
<input type="submit" name="save" value="Register"/>
</form>

That is alright as it is but it doesn’t really do anything. If we want to collect that information then we must work our PHP magic! This file contains the same HTML form but it is written in PHP and is named ‘form.php’.

<?php

/* Include the connection file that we created earlier */

require_once 'connect.php';

/* If the user presses the submit save the information to the database and display a thank you message */

if(isset($_POST['save'])){

/* Get the values submitted from the form */

$username = addslashes($_POST['username']);

$email = addslashes($_POST['email']);

$pass = $_POST['password'];

$password = sha1(strip_tags($pass));

/* Check to see if the two password values are correct */

if($pass!=$_POST['confirmpass'] || $pass=='') die('Passwords do not match. <a href="form.php">Return to form.</a>');

/* Update the database with the new information or die with the mysql error */

mysql_query("insert into users values ('','$username','$email','$password')") or die(mysql_error());

/* Display thank you message and exit */

echo '

<h1>',$username,' Thank You For Registering!</h1>

';

exit;

}

/* Else display the form so the user can register */

echo '

<form method="post">

Username: <input type="text" name="username"/><br/>

Email: <input type="text" name="email"/><br/>

Password: <input type="password" name="password"/><br/>

Confirm: <input type="password" name="confirmpass"/><br/>

<input type="submit" name="save" value="Register"/>

</form>

';

/* Close MySQL, exit and close PHP */

mysql_close();

exit;

?>

Woah! Thank god that’s over. If all goes well you will not have any errors running that script. Anyway that’s all the advice I can give you for one day. Good luck!

Please feel free to use or adapt this code as you will. I understand that this isn’t a prime example but it sets the foundation of what you can customise in order to create a brilliant user freindly form! You could also try adding more verification to the form or even using some unobstructive JavaScript to make it look nice. These are all things that I might write a tutorial about in the future but that’s it for now!

No responses yet



Conor's Blog is powered by Wordpress | Template design by Conor Mac Aoidh