Wednesday, September 19, 2007

Java packages you should know and use

Here is a list of the main and most commonly used java packages. Packages are imported using import <package name>;, for example import java.net.*;

  • java.applet: includes class Applet and other methods that allow applet creation. javax.swing.JApplet is used when an applet enhances GUI swing components
  • java.io: includes classes for data input and output
  • java.net: includes classes for network programming like socket and datagram programming.
  • java.rmi: incudes classes and methods for creating applications for distributed computing.
  • java.security: includes classes for authorisation and data encryption.
  • javax.swing: incudes classes for GUI.
  • java.sql: incudes classes for connection with SQL databases.

Monday, July 30, 2007

Create a Colour Chooser Window with Java

Here a simple piece of code on how you can easily create a Colour Chooser window. The program uses JColorChooser method which is part of the java.swing packet. The code is:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

class ColorChooser extends JFrame {
private JButton changeColor;
private Color color = Color.lightGray;
private Container c;

public ColorChooser()
{
super( "Using JColorChooser" );

c = getContentPane();
c.setLayout( new FlowLayout() );

changeColor = new JButton( "Change Color" );
changeColor.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent e )
{
color =
JColorChooser.showDialog( ColorChooser.this,
"Choose a colour", color );

if ( color == null )
color = Color.blue;

c.setBackground( color );
c.repaint();
}
}
);
c.add( changeColor );

setSize( 400, 130 );
show();
}

public static void main( String args[] )
{
ColorChooser app = new ColorChooser();

app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
}

User is able to choose colors using RGB, HSB or Swatch modes.

Wednesday, May 16, 2007

The bad co-worker: recognise him!

Everybody of us has experienced the phenomenon "bad co-worker", but let me explain what I learned from my experience (web-developing, coding, graphics):
  1. He (the bad co-worker) designs a layout and then he sends it to me for slicing. BUT when I open the layout in Photoshop, I realise that it consists of 200 layers, ungrouped and named with names "layer 1, layer 2, layer 3, ......., layer 200". Believe me pal it is much easier for me to deal with grouped layers in categories like Header, Footer etc and names like Title, sidebar background etc than guessing or right clicking its layout's component to find the appropriate layer.
  2. If I am out of luck at all the layout file is merged down and in .jpg format with the sample text (which should be deleted) on it.
  3. When he writed code, he does not use "ENTER" button for changing line. The code is a mess, without comments and looks like simple text.
  4. When his pc has a problem, he asks the others first and then tries to fix it on his own.
  5. He prefer asking the others for finding information (like a website's URL) than using Google.
  6. His computer is a mess. The desktop is full of icons and files are totally unorganised so he (and everybody else) cannot find them when it is needed.
  7. When a serious problem occurs in his pc, it means data-loss as he does not know the very simple word "BACKUP".
  8. He leaves on time even if he is a click away from completing a serious task.

Thursday, May 10, 2007

Create a drop-down menu for image selection using java

The following code uses JCombo class for creating a drop down menu that provides the user the ability to choose and see the selected image. Note that the images you want to inlcude in your app should be saved in the main directory of your program (if you use netbeans for example open the project folder and save the images there).

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

class ComboBoxTest extends JFrame {
private JComboBox images;
private JLabel label;
private String names[] =
{ "cutlass_32.png", "pet-monkey_32.png",
"pirate-captain_32.png", "first-mate_32.png" };
private Icon icons[] =
{ new ImageIcon( names[ 0 ] ),
new ImageIcon( names[ 1 ] ),
new ImageIcon( names[ 2 ] ),
new ImageIcon( names[ 3 ] ) };

public ComboBoxTest()
{
super( "Psy2k-Photo Selection" );

Container c = getContentPane();
c.setLayout( new FlowLayout() );

images = new JComboBox( names );
images.setMaximumRowCount( 3 );

images.addItemListener(
new ItemListener() {
public void itemStateChanged( ItemEvent e )
{
label.setIcon(
icons[ images.getSelectedIndex() ] );
}
}
);

c.add( images );

label = new JLabel( icons[ 0 ] );
c.add( label );

setSize( 350, 100 );
show();
}

public static void main( String args[] )
{
ComboBoxTest app = new ComboBoxTest();

app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
}
The icons I used in this app are from Iconbuffet's Amsterdam High Seas collection (pirate icon yeah). Iconbuffet is a free social community for trading small icons with others. If you would like to join the madness feel free. It is very addicting!

Thursday, April 26, 2007

Read data from a URL and show them on screen with Java

The following code reads data from a URL and then it shows them on screen. This is an amateur example of the use of java.net packet. If you are an experienced user, you can use ContentHandler and ContentHandlerFactory to choose who can be a data controller.
import java.io.*;
import java.net.*;
public class ReadUrl
{
public static void main (String[] args)
{
for (int i = 0; i < url =" new" connect =" url.openConnection();" in =" connect.getInputStream();" bytes =" new" len =" in.read(bytes))">= 0)
System.out.write(bytes, 0, len);
}
}

Wednesday, April 25, 2007

Tips for debugging your web pages

After building your site, it comes the hard stuff: testing and debugging the page. There are a few rules that you can follow to make your life easier:
  1. Make sure that you spelled everything correctly (for example img is not written igm)
  2. Make sure that the Doctype of your pages matches the (x)html you are using (for example if you use deprecated tags in your code, you should choose (x)html transitional instead of (x)html strict).
  3. Follow the rules of nesting. If you open a <p> tag and then a <a> make sure that the closing </a> comes before the closing </p>
  4. Avoid the use of non-standard tags as they may lead browsers to conflicts.
  5. For elements that have content avoid the use of <p ...... /> and prefer <p> ...... </p>. Both of them are valid (x)html but the first may cause problems to some older browsers. Use the first method though for elements that are empty or contain data, for example <img src="picture.jpeg" alt="picture" />
  6. Validate your code using W3C's validator. If you see a lot of mistakes to your code do not panic, as a missing closing tag can cause the validator to show lot of mistakes. Begin from top to bottom, correct few mistakes at a time, validate again and continue correcting after with the remaining mistakes. Tip: Make sure you use a correct Doctype before you validate your markup!
  7. Download the most famous and common used browsers (Firefox, Internet Explorer, Opera) and see how your site appears by yourself.

Tuesday, April 24, 2007

Build a digital clock with Java

Here is a piece of code to build a Java clock applet that uses threads, gets the data for time automatically and is not interrupted if you click something else on the web page. There are some comments around the code to help you understand what's happening. Program build and tested with Netbeans 5.5. If I find a way, I will upload the applet here to see it running in real time!
import java.awt.*;
import javax.swing.*;
import java.util.Date;
import java.text.DateFormat;
// builds the clock
class MyClock extends JApplet implements Runnable
{ private Thread myThread; // the thread
private JLabel clock; // the label
private final int interval = 1000; // time in
// milliseconds
public void init()
{ clock = new JLabel("", SwingConstants.CENTER);
clock.setFont (new Font ("Verdana", Font.BOLD,
28));
clock.setBackground(Color.BLUE());
clock.setForeground(Color.WHITE);
clock.setOpaque(true);
getContentPane().add(clock);
setSize(250, 100);
}
public void start()
{ if (myThread == null)
{ myThread = new Thread(this, "clock");
myThread.start();
}
} // start

public void run()
{
while (myThread == Thread.currentThread())
{ // gets data for the clock

Date time = new Date();
clock.setText(DateFormat.getTimeInstance
(DateFormat.MEDIUM).format(time));
try
{ //thread sleeps for a sec
myThread.sleep(interval);
}
catch (InterruptedException e) {}
}
} // run
public void stop()
{
myThread = null;
}
}

Draw stars using Java

Here is a tutorial to make your way into drawing graphics with Java. This program creates a semi-circle line of stars. The stars are randomly colored. I made the program using Netbeans 5.5, and I tested the code also with Sun Java Studio Enterprise 8.1. Both of them are free. The output is what you see above (star color may differ as they are randomly colored).
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.geom.*;

class psy2k extends JFrame {
public psy2k()
{
super( "Psy2k star draw" );

setBackground( Color.white );
setSize( 400, 400 );
show();
}
public void paint( Graphics g )
{
int xPoints[] = { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 };
int yPoints[] = { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 };

Graphics2D g2d = ( Graphics2D ) g;

GeneralPath star = new GeneralPath();
star.moveTo( xPoints[ 0 ], yPoints[ 0 ] );

for ( int k = 1; k < xPoints.length; k++ ) star.lineTo( xPoints[ k ], yPoints[ k ] ); star.closePath();
g2d.translate( 200, 200 );
for ( int j = 1; j <= 20; j++ ) {
g2d.rotate( Math.PI / 20.0 );
g2d.setColor( new Color( ( int ) ( Math.random() * 256 ),
( int ) ( Math.random() * 256 ),
( int ) ( Math.random() * 256 ) ) );
g2d.fill( star );
}
}
public static void main( String args[] )
{
psy2k app = new psy2k();
app.addWindowListener( new WindowAdapter()
{
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
}

Monday, April 23, 2007

Download my first Wallpaper!

I made an attemp to make a wallpaper with Adobe Photoshop CS2. I used lot of gradients and layer effects. Feel free to download it by clicking the folder icon below and tell me your comments. I love minimal things: that's why my wallpaper looks like this. In the .zip file there are three versions of the wallpaper: 1600x1200, 1280x1024, 1024x768 pixels. If you use a different screen resolution feel free to mail me and I will send you a version that fits your screen.

Download Wallpaper

Read and print a serial file using C

If you have a serial .dat file that has data like these below, you can easily import and use them with C (for C++ it is almost the same).
Sample file:
If the file is named customers.dat, use the code below to read and print the data with C.
#include <stdio.h>
int main()
{
int number;
char name[30];
double bill;
FILE *cfPt; /*File pointer .dat */
if ((cfPtr=fopen("customers.dat", "r"))==NULL)
printf("File could not be opened\n");
else {
printf("%-10s%-13s%s\n", "Number", "Name", "Bill");
fscanf(cfPtr, "%d%s%lf", &number, name, &amp;amp;amp;amp;bill);
while (!feof(cfPtr)) {
printf("%-10d%-13s%7.2f\n", number, name, bill);
fscanf(cfPtr, "%d%s%lf", &number, name, &amp;amp;amp;amp;bill);
}
fclose(cfPtr);
}
return 0;
}

Friday, April 20, 2007

Validate the Youtube embed code!

I wrote about it here and it is really usefull. As we now the embed code of youtube is a mess as it uses the embed tag which does not validate as xhtml. Using the code this tip you can embed a youtube or google video to your site or blog and keep your code validated:
<object type="application/x-shockwave-flash" data="http://www.youtube.com/v/moviecode" width="400" height="326"><param name="movie" value="http://www.youtube.com/v/moviecode" /></object>
The moviecode is a code found in each youtube video adress and is after v= until the first ampersand (&). For example in this URL http://www.youtube.com/watch?v=xmHHjUZPyMY, the code is xmHHjUZPyMY.

Sunday, February 25, 2007

Microsoft Word became crazy?

Searching around on the Internet I found this trick: Open an empty Word file (I have not tested it in Word 2007), type = rand (200,99) and press enter. Wait for 3 seconds and then a lot of pages will be filled with a repeating sentense (I use the Greek version of Word 2003 and the sentense that appears is part from a poem). As I released after, this is not a bug, it is an easy way to transfer text and Microsoft knows that it happens. If with a single line like this, Word could write down pages from my exercises, it would be for sure my favorite program to use.

Tuesday, February 13, 2007

Blogger navbar and Internet Explorer 7

As you may have noticed, if you use Blogger with a blogger template, Internet explorer 7 displays your blog with a problem on the top (Blogger nav bar is hiding part of the header). The solution for this problem is to put some html code into your template and hide the navbar (very few people use the nav bar, so it is better to hide it and have your site being displayed correctly). Between <head> and </head> tags paste the following code under the */layout*/ line. (everything between /*....*/ is comments and it does not affect your site, so be carefull to paste the code under the comment line).
#navbar-iframe {
height: 0px;
visibility: hidden;
display: none;
}
Save your template, view your blog and enjoy how Internet Explorer 7 displays it!

Monday, January 22, 2007

How to find your MAC adress

It is very easy to discover your MAC adress (MAC adress is needed sometimes to make operations on your network or router). So follow these steps and you will discover your MAC adress:
  1. Click Start, Run and type cmd in the text box
  2. When the command promt window opens, type ipconfig/all
The 12-digit Physical adress is the same as your MAC adress.
You will have multiple MAC adresses if you have both wired and wireless connection on your system.

Monday, January 15, 2007

Another way to track your blog traffic

Searching through the Internet, I found 103bees. 103bees is a service, with which you can track the visitors of your blog or site. I use it alongside with Google Analytics, because 103bees offers the option to see what search terms did users entered and reached your pages through search engines (like google, yahoo and live) and what was your page ranking in the results. It is very easy to track your visitors with 103bees, you just have to register an account (it is completely free), add some code to every page you want to track (the codes loads up very quickly and validates for w3c standards) and you are ready. Although 103bees is very usefull, it cannot replace completely Google Analytics, as Analytics offer the geo map overlay, marketing information about your site and various other statistics.