Friday, 22 April 2011

jmenu+separator+submenu on java

package menutest;

import javax.swing.JApplet;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenu;
import javax.swing.JMenuBar;

public class NewJApplet extends JApplet {

    public void init()
    {
    JMenuBar mb = new JMenuBar();
    JMenu filemenu = new JMenu("Display");
    JMenu pullrightmenu = new JMenu("pull right");

    filemenu.add("Welcome");
    filemenu.addSeparator();
    filemenu.add(pullrightmenu); //add submenu
    filemenu.add("Exit");

    pullrightmenu.add(new JCheckBoxMenuItem("Good Morning!"));
    pullrightmenu.add(new JCheckBoxMenuItem("Good Afternoon!"));
    pullrightmenu.add(new JCheckBoxMenuItem("Good night!"));

    mb.add(filemenu);
    setJMenuBar(mb);
    }



}

menu bar on java


package menubar;

import javax.swing.JApplet;
import javax.swing.JMenuBar;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenu;



public class NewJApplet extends JApplet
{


    public void init()
    {
JMenuBar mb= new JMenuBar();
JMenu file= new JMenu("File");
JMenu view= new JMenu("view");
JMenu editor= new JMenu("editor");
JMenu imp= new JMenu("import object");
file.add("New project");
file.addSeparator();
file.add(imp);
file.add("New File");
view.add(editor);
view.add("Browser");
editor.add(new JCheckBoxMenuItem("Source"));
imp.add(new JCheckBoxMenuItem("eclipse"));
mb.add(file);
mb.add(view);
setJMenuBar(mb);


    }



}

tool tip text on java

JAVA MAIN FILE
--------------------------

package apples;

import javax.swing.JFrame;

public class Main
{
    public static void main(String[] args)
    {
    tuna obj = new tuna();
    obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    obj.setSize(275, 180);
    obj.setVisible(true);
    }
}

JAVA FILE
----------------

package apples;

import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class tuna extends JFrame
{
    private JLabel item1;

    public tuna()
    {
    super("The Title Bar");
    setLayout(new FlowLayout());

    item1 = new JLabel("This is a sentnce");
    item1.setToolTipText("You have hovred over it");
    add(item1);
    }
}

radio button on java

JAVA MAIN FILE
-----------------

package radio;

import javax.swing.JFrame;

public class Main
{
    public static void main(String[] args)
    {
        boss obj = new boss();
        obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        obj.setSize(300, 300);
        obj.setVisible(true);
    }
}

JAVA CLASS FILE
-------------------

package radio;

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

public class boss extends JFrame
{
    private JTextField tf;
    private Font pf;
    private Font bf;
    private Font itf;
    private Font bif;
    private JRadioButton pb;
    private JRadioButton bb;
    private JRadioButton ib;
    private JRadioButton bib;
    private ButtonGroup group;

    public boss()
    {
    super("title");
    setLayout(new FlowLayout());

    tf = new JTextField("Try on me", 25);
    tf.setEditable(false);
    add(tf);

    pb = new JRadioButton("plain", true);
    bb = new JRadioButton("bold", false);
    ib = new JRadioButton("italic", false);
    bib = new JRadioButton("bold and italic", false);
    add(pb);
    add(bb);
    add(ib);
    add(bib);

    group = new ButtonGroup();
    group.add(pb);
    group.add(bb);
    group.add(ib);
    group.add(bib);

    pf = new Font("Serif", Font.PLAIN, 14);
    bf = new Font("Serif", Font.BOLD, 14);
    itf = new Font("Serif", Font.ITALIC, 14);
    bif = new Font("Serif", Font.BOLD + Font.ITALIC, 14);

    tf.setFont(pf);

    pb.addItemListener(new HandlerClass(pf));
    bb.addItemListener(new HandlerClass(bf));
    ib.addItemListener(new HandlerClass(itf));
    bib.addItemListener(new HandlerClass(bif));
    }

    private class HandlerClass implements ItemListener
    {
        public Font font;

        //set font object get variable font
        public HandlerClass(Font f)
        {
            font = f;
        }

        //sets the font to the font object that was passed in
        public void itemStateChanged(ItemEvent ie)
        {
            tf.setFont(font);
        }
    }
}

imgage icon on java

package menuitems;

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

public class NewJApplet extends JApplet
{
    public void init()
    {
    Container contentpane = getContentPane();
    Icon newicon = new ImageIcon("new1.gif", "New Document");
    Icon openicon = new ImageIcon("two.jpg", "Open an existing Document");
   
    JMenuBar mb = new JMenuBar();
    JMenu filemenu = new JMenu("File");
   
    JMenuItem newitem = new JMenuItem("New", newicon);
    JMenuItem openitem = new JMenuItem("Open", openicon);
   
    JMenuItem saveitem = new JMenuItem("Save");
    JMenuItem saveasitem = new JMenuItem("Save as..");
    JMenuItem exititem = new JMenuItem("Exit", 'x');

    filemenu.add(newitem);
    filemenu.add(openitem);
    filemenu.add(saveitem);
    filemenu.add(saveasitem);
    filemenu.addSeparator();
    filemenu.add(exititem);

    mb.add(filemenu);
    setJMenuBar(mb);
    }
}

roll over imeges on java

JAVA MAIN FILE
-----------------

package jbutton;

import javax.swing.JFrame;

public class Main
{
    public static void main(String[] args)
    {
    button obj = new button();
    obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    obj.setSize(400, 400);
    obj.setVisible(true);
    }

}

JAVA CLASS FILE
-------------------

package jbutton;

import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

public class button extends JFrame
{
    private JButton reg;
    private JButton custom;

    public button()
    {
    super("the title");
    setLayout(new FlowLayout());

    reg = new JButton("reg button");
    add(reg);

    //Icon b = new ImageIcon(getClass.getResource("a.png"));
    //Icon x = new ImageIcon(getClass.getResource("b.png"));

    //custom = new JButton("Custom", b);
    custom = new JButton("Custom");
    //custom.setRolloverIcon(x);
    add(custom);
   
    HandlerClass handler = new HandlerClass();
    reg.addActionListener(handler);
    custom.addActionListener(handler);
    }

    private class HandlerClass implements ActionListener
    {
        public void actionPerformed(ActionEvent ae)
        {
        JOptionPane.showMessageDialog(null, String.format("%s", ae.getActionCommand()), "Is my title title", JOptionPane.PLAIN_MESSAGE);
        }
    }
}

create file on java

package free;

import java.util.*;

public class Main
{
    public static void main(String[] args)
    {
        final Formatter x;

        try
        {
            x = new Formatter("Custom.docx");
            System.out.println("You created a file.");
        }
        catch(Exception e)
        {
             System.out.println("You get an error");
        }
    }
}

check file on java

package check;

import java.io.File;

public class Main {

    public static void main(String[] args)
    {
        File obj = new File("E:\\go\\hideandseek.txt");

        if(obj.exists())
        {
            System.out.println(obj.getName() + " File exists.");
        }
        else
        {
            System.out.println(obj.getName() + " File DOES NOT exist.");
        }
    }
}

Friday, 15 April 2011

25 Android Apps For Web-Workers And Designers

The Android platform is growing in popularity every day, and for good reasons. Obviously being an open-source project and having Google behind it makes it a great choice for developers. Unfortunately the Android Market can’t really compete against the Apple App Store (in my opinion).
So I’ve chosen 25 Android apps that I think can be very useful to designers, developers and web-workers. You’ll find editors, reference guides, blogging tools, image editing tools and more. If you have your Android device handy you can scan the QR Codes next to each item in the list using the Barcode Scanner application.

Magic Color Picker

Magic Color Picker is an powerful color selection tool suitable for designers, artists and programmers for selecting colors using different color models.

Color Dictionary

Color Dictionary makes it very easy for you to reference any traditional colors all over the world. Includes global colors, traditional color of US, UK, France, etc. It provides RGB/HEX/CMYK/Lab values and detailed color analysis.

Cheat Sheet Repository

Over 400 cheat sheets aimed at software developers. Topics including Ruby, Ruby on Rails, HTML, CSS, Regular Expression, jQuery, Prototype, Objective-C, testing, IDE shortcuts and much more. 100% Offline and searchable!

AndFTP Pro

AndFTP Pro is a FTP, FTPS, SCP and SFTP client. It provides commands to rename, delete, set permissions on remote files and folders. It can upload or download files and folders recursively. It supports RSA and DSA keys for SSH. Intents for applications are available.

Mobile GA for Android

Mobile GA for Android is a secure, fast and lightweight application for accessing your Google Analytics data. The app is intended to help you keep an eye on your key summary statistics while you’re on the move.

WordPress
Write new posts, edit content, and manage comments on your WordPress blog. WordPress for Android is an Open Source app that empowers you to write new posts, edit content, view stats, and manage comments with built-in notifications.

ColorViewSource

Source code viewer with syntax highlighting. It can view webpages source, open local files, or even be integrated into the “Share” menu of other apps.

View Web Source

With this application you will be able to view the source of any website. You will also be able to select text, search for text as well as copy and paste the HTML.

Fontroid

Fontroid is the world’s first social font service with which you can share your own handwritten fonts with everyone.

SilverEdit

SilverEdit is the ultimate web designer tool for Android devices. With SilverEdit you can Create, Edit, Preview your pages offline or online. Manage, upload and download files through the FTP as well as managing your local files and folders.


Adobe Photoshop Express
With Photoshop Express you can edit and share photos virtually anywhere. Touch to crop, rotate, adjust color, and add artistic effects. Access all your photos and videos directly from your Photoshop.com account.

Dropbox

Dropbox syncs your files online and across computers and your mobile device for access anywhere. You can now browse the files in your Dropbox folder from your Android phone!

Thinking Space Pro

ThinkingSpace is a mind-mapping app for the Android platform that let’s you create visual thought maps that help organize and plan your activities and ideas.

Fontest

Fontest is a developer and typography tool that helps you quickly preview how your favorite fonts are rendered on Android.

Astrid Task/Todo List

Astrid is a great todo list/task manager app designed to help you get stuff done. It features reminders, tags, sync, a widget and more.

Opera Mini web browser

Get a faster, more cost-efficient mobile web browser thanks to Opera Mini. This browser uses powerful servers to compress data by up to 90% before sending it to your phone, so page loads are lightning fast in the browser.

Mozilla Firefox Web Browser

You can now synchronize your Firefox history, bookmarks, tabs and passwords between your desktop and mobile. Discover and install add-ons right from your phone to customize Firefox exactly the way you like.

Dolphin Browser™ Mini

Dolphin Browser Mini aims at providing a friendly user experience. It features tab browsing, RSS detection, gestures, and of course it supports Flash.

Pixle

Pixle is a browser app for Dribbble. It lists the popular, everyone, and debut shots. It includes personal details, links, list of player’s shots, liked shots, and following, follower, and draftee players.

SketchBook Mobile

Autodesk SketchBook Mobile is a professional-grade paint and drawing application offering a full set of sketching tools and a streamlined and intuitive user interface.

PayPal

Send money, transfer money between PayPal and your bank account, and lots more. You can even use it to manage your PayPal account. You can also use the “Bump” feature to send money.

ASTRO File Manager

Astro will help you copy, move, delete and rename files and manage the files on your SD card. With Astro you can also manage running applications as well as back up apps.

Google Chrome to Phone

Google Chrome to Phone lets you easily share links, maps, and currently selected phone numbers and text between your computer running Chrome and your phone. You also need to install the Chrome browser extension on your computer.

Share to Browser

Share to Browser is the opposite of the Chrome to Phone app and works with any browser without special plugins. Found a great article while browsing the web but would like to read at home on your computer instead? Share to Browser to the rescue.

WiFi Keyboard

The WiFi Keyboard provides a way to use your computer to type something on your Android device. You can type in your browser and all the key presses will appear in your android device.

Standard JDK Tools

Basic Tools
Tool Name
Brief Description
javac  This is the core of java, the compiler for the Java programming language.
java  It is used to launch the Java applications. The same launcher is employed
for deployment and development pupose.
javadoc  It is used for producing API documentation.
apt   This tool is used for annotation processing.
appletviewer   The applet viewer is used to run applet , also used for debugging applets
without the help of browser.
jar This is used to produce and handle jar files.
javah  C header and stub generator. Used to write native methods. This is employed
to produce stub and C header. Also used for writing native methods.
javap  This tool is used to dissembler Class file.
extcheck This is used to find the conflicts between jars.

Security Tools
These security tools help you set security policies on your system and create apps that can work within the scope of security policies set at remote sites.

Tool Name  Brief Description 
keytool Manage keystores and certificates.
jarsigner Generate and verify JAR signatures.
policytool This GUI tool is used to handle policy files.

These security tools help you obtain, list, and manage Kerberos tickets.

Tool Name  Brief Description
kinit  For getting  Kerberos v5 tickets, we use this tool.
klist This tool is a command line tool for listing entries in  credential cache and key tab.
ktab  This Tool is a command line tool for managing entries in the key table. This is done by user. 

Internationalization Tool
 The native2ascii tool is used to convert text to Unicode Latin-1.

Remote Method Invocation (RMI) Tools
Given below tools are used to develop applications that can be used for communication over the network or web.


Tool Name Brief Description 
rmic Generate stubs and skeletons for remote objects.
rmiregistry Remote object registry service.
rmid RMI activation system daemon.
serialver Return class serialVersionUID.

Java IDL and RMI-IIOP Tools
These tools are used when creating applications that use OMG-standard IDL and CORBA/IIOP.

Tool Name  Brief Description 
tnameserv  This tool is used to supply access to the naming service.
idlj This tool produces .java files that map an OMG IDL interface and provide
the ability to java application to use CORBA functionality.
orbd In CORBA environment , it gives support for clients to transparently locate and invoke
persistent objects on servers.
servertool This tool is used to provide ability to application programmers to register,
unregister, startup, and shutdown a server.

Java Deployment Tools
These tools are used with deployment of java applications and applets.

Tool Name  Brief Description 
pack200 Using pack200 tool, you can compress the jar file into pack200 file using gzip compressor
unpack200 This tool coverts the pack200 file into jar files.

Java Plug-in Tools
These tool are used with Java Plug-in. The default tool come with this is htmlconverter , for Java Plug-in, it converts HTML containing applet to the OBJECT / EMBED tag format

Java Web Start Tools
These Tools are used with Java Web Start. The javaws  is a Java Web Start Tool which is a command line tool for establishing Java Web Start and setting various options

Creating Uncrackable Passwords, part 2

Currently users are forced to remember hundreds of passwords to websites and various other authentication systems which require passwords. Due to the wide variety of systems many end users to manage the large numbers of passwords which is complicated to keep straight when you are using a strong password which expires on a rotating schedule. In the original article it was suggested to create an uncrackable password was to put characters from all 5 of these rows in your passwords to increase the time it takes to get cracked and when possible use ALT-Chars which makes passwords uncrackable.
0123456789
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
~!@#$%^&*()_+{}:"<>?|
`-=[];',./\
Mnemonic Passwords are passwords that are derived from simple passwords which the user will remember with ease but they use mnemonic substitutions to give the password a more complex quality.  Leet-speaking a password is a simple example of this technique. For example, converting the passwords ``password'' and ``combobulate'' into leet-speak would result in the passwords ``p@ssw0rd'' and ``c0mb0bul@t3''.
The issue of managing multiple passwords has given rise to insecurities related to selection and reuse of the same passwords.  Users tend to pick one good password and reuse it on several different systems.  Problems arise if one of the systems is compromised all the systems with the same password are put at risk.

Mnemonic Password Formulas

A Mnemonic Password Formula(MPF)is a memory technique utilizing a predefined, memorized formula to construct a password on the fly from various elements of the website or system that you are generating a password from.
A well designed formula should result in a password with the following properties:
1.  A seemingly random string of characters
2.  Long and very complex, therefore difficult to crack via brute force
3.  Easy to reconstruct by a user with knowledge of only the formula, themselves, and the target   authentication system
4.  Unique for each user, class of access, and authenticating system
Step1:
Start out with a strong password: P@ssW0rd11!!
Step2:
Decide on a formula to use mine will substitute 1st, 3rd and 7th letters of my password with the characters from whatever domain I happen to use the password on.
PasswordFormula
The above formula would yield such passwords as:
  • "I@gsW0rm11!!" for digg.com
  • "M@lsW0rm11!!" for gmail.com
  • "E@osW0rs11!!" for del.icio.us
  • "O@esW0rm11!!" for youtube.com
This simple method will create a fairly long, easy to remember, passwords that contain a special characters, numbers, and letters which would make using the same password reusable among several different systems.  If your password were to be compromised on one system it would not expose the others.  More information can be found on making MPF’s at  http://uninformed.org/index.cgi?v=7&a=3

Creating Uncrackable Passwords

Interesting article I found via digg today about Password Cracking and Recovery. It suggests that you put characters from all 5 of these rows in your passwords to increase the time it takes to get cracked.
0123456789
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
@#$%^&*()-_+=
~`[]{}|\:;'<>,.?/
While this is good advise, I personally use alt-characters in my passwords this almost makes it impossible to crack with todays current password cracking tools, here is a table that lists them all:

Monday, 11 April 2011

RGB mixser on JAVA

import java.applet.*;
import java.awt.*;
import java.net.*;

class Slider
{
public boolean over, drag, down;
private Rectangle r=new Rectangle();
private Graphics g;
public Color color;
public int x, y, y1, y2, pos, pos_old, height, value;

public Slider(int x, int y, Color color)
{
height=104;
this.x=x;
this.y=y;
pos=y+height/2;
this.color=color;
r.x=x-10;
r.y=pos-5;
r.width=22;
r.height=10;
}

public void reportMouseMove(int x, int y)
{
if(r.inside(x,y))
over=true;
else
over=false;
}

public void reportMouseDown(int x, int y)
{
if(r.inside(x,y))
{
down=true;
y1=y;
pos_old=pos;
}
}

public void reportMouseUp(int x, int y)
{
down=false;
}

public void reportMouseDrag(int x, int y)
{
if(down)
{
drag=true;
y2=y-y1;

pos=y2+pos_old;

if(pos<this.y+2)pos=this.y+2;
if(pos>this.y+height)pos=this.y+height;
r.move(r.x,pos-5);
}
else
drag=false;
}

private void drawSlider()
{
//the slot
g.setColor(Color.darkGray);
g.drawLine(x,y,x,y+height);
g.setColor(Color.gray);
g.drawLine(x-1,y,x-1,y+height);
g.setColor(Color.lightGray.brighter());
g.drawLine(x+1,y,x+1,y+height);

//draw the scale
g.setColor(Color.gray);
for(int i=y+1; i<y+104; i++)
{
if(i%2==0)
{
g.drawLine(x-10,i,x-5,i);
g.drawLine(x+10,i,x+5,i);
}
}

//the slider knob
g.setColor(Color.lightGray);
g.fill3DRect(x-10,pos-6,22,12,true);
g.fill3DRect(x-9,pos-5,20,10,true);

g.setColor(color);
g.fillRect(x-8,pos-1,18,2);

//the value
value=255-(((pos-y-2)/2)*5);
String valuestring=""+value;

//measure the size of the string to center it
Font font=new Font("Helvetica", Font.PLAIN, 12);
FontMetrics fm = g.getFontMetrics(font);
int stringWidth=fm.stringWidth(valuestring);

g.setFont(font);
g.setColor(Color.black);
g.drawString(valuestring, x-stringWidth/2, y-10);
}

public void paint(Graphics gr)
{
g=gr;
drawSlider();
}

public int getVal()
{
return value;
}
}

public class RGBMixer extends Applet
{
Image Buffer;
Graphics gBuffer;
URL url;
int h=35;
Slider sl1=new Slider(180,h,Color.red);
Slider sl2=new Slider(210,h,Color.green);
Slider sl3=new Slider(240,h,Color.blue);
//the hotlink
Rectangle r=new Rectangle(165,150,87,10);
boolean overLink;

public void update(Graphics g)
{
paint(g);
}

public void init()
{
Buffer=createImage(size().width,size().height);
gBuffer=Buffer.getGraphics();

try{url=new URL("http://www.programming.de/");}
catch(MalformedURLException mal){}
}

public void drawStuff() {

gBuffer.setColor(Color.lightGray);
gBuffer.fillRect(0,0,size().width,size().height);

gBuffer.draw3DRect(0,0,size().width-1,size().height-1,true);
gBuffer.draw3DRect(4,4,size().width-9,size().height-9,false);
gBuffer.draw3DRect(5,5,size().width-11,size().height-11,true);

gBuffer.draw3DRect(18,38,133,98,false);

sl1.paint(gBuffer);
sl2.paint(gBuffer);
sl3.paint(gBuffer);

Color mixColor=
new Color(sl1.getVal(),sl2.getVal(),sl3.getVal());

gBuffer.setColor(mixColor);
gBuffer.fillRect(20,40,130,95);

String red,green,blue;

red=sl1.getVal()<20?"0"+Integer.toHexString(sl1.getVal()):Integer.toHexString(sl1.getVal());
green=sl2.getVal()<20?"0"+Integer.toHexString(sl2.getVal()):Integer.toHexString(sl2.getVal());
blue=sl3.getVal()<20?"0"+Integer.toHexString(sl3.getVal()):Integer.toHexString(sl3.getVal());

String hex="color=\"#"+red+green+blue+"\"";

Font font=new Font("Helvetica", Font.PLAIN, 12);
gBuffer.setFont(font);
gBuffer.setColor(Color.black);
gBuffer.drawString(hex,45,25);

Font smallFont=new Font("Helvetica", Font.PLAIN, 9);
gBuffer.setFont(smallFont);
gBuffer.setColor(Color.gray);
gBuffer.drawString("©2001 by Johannes Wallroth",20,157);
gBuffer.setColor(Color.blue);
gBuffer.drawString("www.programming.de",165,157);
gBuffer.drawLine(165,158,251,158);
}

public boolean mouseMove(Event evt,int x,int y)
{
sl1.reportMouseMove(x, y);
sl2.reportMouseMove(x, y);
sl3.reportMouseMove(x, y);

if(r.inside(x,y))
overLink=true;
else
overLink=false;

Component ParentComponent = getParent();
while ( ParentComponent != null &&
!(ParentComponent instanceof Frame))
ParentComponent = ParentComponent.getParent();
Frame BrowserFrame = (Frame) ParentComponent;

if(overLink)
BrowserFrame.setCursor(Frame.HAND_CURSOR);
else
BrowserFrame.setCursor(Frame.DEFAULT_CURSOR);

repaint();
return true;
}

public boolean mouseDrag(Event evt,int x,int y)
{
sl1.reportMouseDrag(x, y);
sl2.reportMouseDrag(x, y);
sl3.reportMouseDrag(x, y);
repaint();
return true;
}

public boolean mouseDown(Event evt,int x,int y)
{
sl1.reportMouseDown(x, y);
sl2.reportMouseDown(x, y);
sl3.reportMouseDown(x, y);

if(overLink)
getAppletContext().showDocument(url,"_blank");

repaint();
return true;
}

public boolean mouseUp(Event evt,int x,int y)
{
sl1.reportMouseUp(x, y);
sl2.reportMouseUp(x, y);
sl3.reportMouseUp(x, y);
repaint();
return true;
}

public void paint(Graphics g)
{
drawStuff();
g.drawImage (Buffer,0,0, this);
}
}
Back to JAVA-RGB-Mixer

createting calculator on JAVA using awt classes

import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics;
import ETextField;

public class AwtCalc extends java.applet.Applet implements ActionListener
{

private Button[] buttons = new Button[19];
private String[] buttonText = { " 1 ", " 2 ", " 3 ", " + ", " - ",
" 4 ", " 5 ", " 6 ", " x ", " / ",
" 7 ", " 8 ", " 9 ", "^ ", "sqrt",
" C ", " 0 ", " . ", " = "};

private ETextField result; // Calculator display screen
private String input = ""; // stores user input
private Label label;
private Color forecolor, // Calculator foreground color
backcolor, // Calculator background color
fieldcolor; // the display screen's color
private Font font,
buttonfont;
private int oper = 0, // stores the integer constants representing
oldoper = 0, // the operators
newoper = 0;
private double answer,
num1 = 0.0,
num2 = 0.0,
num3 = 0.0;
private final int ADD=1, // integer constants representing operators
SUB = 2,
MULT = 3,
DIVI = 4,
POW = 5,
SQRT = 6;
private boolean firstpress = true, //determines first button press
morenums = false, //"" if more numbers are being pressed
equals = false, //"" if equal button has been pressed
clearscreen = false, //clears screen
decnumber = false, //"" if a user entered a float
doubleclick = false; //"" if mouse was doubleclicked

public void init() {

font = new Font( "Courier", Font.ITALIC, 10 );
buttonfont = new Font( "Courier", Font.PLAIN, 12 );
setBackground( Color.lightGray );

//initialize colors

result = new ETextField( 125, 18 );
label = new Label( "AWT Calculator" );
setLayout( new FlowLayout() );

add( result );
add( label );

//initialize and add buttons
for ( int i = 0; i < 19; i++ ) {
buttons[i] = new Button( buttonText[i] );
buttons[i].setFont( buttonfont );
buttons[i].addActionListener( this );

if ( i <= 2 )
add( buttons[i] );
else if ( i >= 3 && i <= 7)
add( buttons[i] );
else if ( i >=8 && i <= 12 )
add( buttons[i] );
else if ( i >= 13 && i <= 17 )
add( buttons[i] );
else
add( buttons[i] );

if ( i == 2 )
add( new Label( " " ) );
else if ( i == 7 )
add( new Label( " " ) );
else if ( i == 12 )
add( new Label( " " ) );
else if ( i == 17 )
add( new Label( " " ) );

}
buttons[15].setForeground( Color.red );
result.setBackground( Color.white );
label.setFont( font );


}

//==============================================================================
// Interface method that determines which button was pressed then determines
// the appropriate action.
//==============================================================================
public void actionPerformed( ActionEvent e )
{

// "if" block is not entered if the button is an operator
if ( e.getSource() != buttons[3] && e.getSource() != buttons[4]
&& e.getSource() != buttons[8] && e.getSource() != buttons[9]
&& e.getSource() != buttons[13] && e.getSource() != buttons[14]
&& e.getSource() != buttons[15] && e.getSource() != buttons[18] ) {

if ( clearscreen ) { // clears screen if user enters number before an
clearScreen(); // operator after pressing equals
clearscreen = false;
}

if ( e.getSource() == buttons[0] ) {
input += "1"; // concoctenate "1" to input
result.setText( input );
showAnswer( input );
} // end else if

else if ( e.getSource() == buttons[1] ) {
input += "2"; // concoctenate "2" to input
showAnswer( input );
} // end else if

else if ( e.getSource() == buttons[2] ) {
input += "3"; // concoctenate "3" to input
showAnswer( input );
} // end else if

else if ( e.getSource() == buttons[5] ) {
input += "4"; // concoctenate "4" to input
showAnswer( input );
} // end else if

else if ( e.getSource() == buttons[6] ) {
input += "5"; // concoctenate "5" to input
showAnswer( input );
} // end if

else if ( e.getSource() == buttons[7] ) {
input += "6"; // concoctenate "6" to input
showAnswer( input );
} // end else if

else if ( e.getSource() == buttons[10] ) {
input += "7"; // concoctenate "7" to input
showAnswer( input );
} // end else if

else if ( e.getSource() == buttons[11] ) {
input += "8"; // concoctenate "8" to input
showAnswer( input );
} // end else if

else if ( e.getSource() == buttons[12] ) {
input += "9"; // concoctenate "9" to input
showAnswer( input );
} // end else if

else if ( e.getSource() == buttons[16] ) {
input += "0"; // concoctenate "0" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[17] ) {
if ( decnumber == false ) {
decnumber = true;
input += ".0"; // concoctenate "." to input
showAnswer( input );
}
}
} // end if

// check if user entered the addition operator
if ( e.getSource() == buttons[3] ) {
clearscreen = false;
decnumber = false;
oper = ADD; // oper is set to addition
clickCheck( input ); // checks if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} // end if

// check if user entered the subtraction operator
else if (e.getSource() == buttons[4] ) {
clearscreen = false;
decnumber = false;
oper = SUB; // oper is set to subtraction
clickCheck( input ); // check if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} // end else if

// check if user entered the multiplication operator
else if (e.getSource() == buttons[8] ) {
clearscreen = false;
decnumber = false;
oper = MULT; // oper is set to multiplication
clickCheck( input ); // check if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} //end else if

// check if user entered the divide operator
else if (e.getSource() == buttons[9] ) {
clearscreen = false;
decnumber = false;
oper = DIVI; // oper is set to divide
clickCheck( input ); // check if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} // end else if

// check if user entered the exponential operator
else if ( e.getSource() == buttons[13] ) {
clearscreen = false;
decnumber = false;
oper = POW; // oper is set to exponential
clickCheck( input ); // check if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} // end else if

// check if user entered the square root operator
else if ( e.getSource() == buttons[14] ) {
clearscreen = false;
oper = SQRT; // oper is set to square root
clickCheck( input ); // check if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} // end else if

// check if user entered the clear operator
if (e.getSource() == buttons[15] ) {
clearScreen();
} // end if

// check if user entered the equal operator
if (e.getSource() == buttons[18] ) {
equals = true;
clearscreen = true;
clickCheck( input ); //check if user double-clicked
if ( doubleclick == false )
processNumbers(); //continue to process numbers if
input = Double.toString( answer ); //if no double-click
} // end if

} // end actionPerformed()

//==============================================================================
//Method processNumbers is where processes the numbers inputed by the user
//==============================================================================
public void processNumbers() {

// the program enters this "if" block when an operator is pressed for the
// first time
if ( firstpress ) {

if ( equals ) {
num1 = answer; //answer is stored in num1 if user enters equal operator
equals = false; // equals is set to false to allow additional input
} // end if
else
num1 = Double.valueOf( input ).doubleValue(); // converts a string number to double

oldoper = oper; // store current operator to oldoper

// if operator is square root, calculation and output is done immediately
if ( oper == SQRT ) {
answer = calculate( oldoper, num1, 0.0 );
showAnswer( Double.toString( answer ) );
morenums = true;
}
firstpress = false; // no longer the first operator
} // end if

// "if" block is entered if now more than two numbers are being entered to
// be calculated
else if ( !morenums ) {

num2 = Double.valueOf( input ).doubleValue(); //converts second num to double
answer = calculate( oldoper, num1, num2 ); //calculate num1 and num2 with
showAnswer( Double.toString( answer) ); //the past operator
newoper = oper; //store current operator to
//new oper
if ( !equals )
morenums = true; //tells program that more than two numbers have
else { //entered
morenums = false; //if equal operator is pressed, firstpress
firstpress = true; //returns to true
} // end else
} // end if

// if more than two numbers are being inputted to calculate, this "if" block
// is accessed
else if (morenums) {

if ( equals ) {

newoper = oper;
morenums = false;
firstpress = true; // if equals is pressed set firstpress to false
} // end if

num3 = Double.valueOf( input ).doubleValue();
answer = calculate( newoper, answer, num3 );
showAnswer( Double.toString(answer) );

newoper = oper;
} // end else if
} // end processNumbers()

//==============================================================================
//Method calculate determines which operator was entered and calculates
//two numbers depending on the operator pressed
//==============================================================================
public double calculate( int oper, double number1, double number2 )
{
double answer = 0.0;

switch( oper ) {
case ADD:
answer = number1 + number2;
break;
case SUB:
answer = number1 - number2;
break;
case MULT:
answer = number1 * number2;
break;
case DIVI:
answer = number1 / number2;
break;
case POW:
answer = Math.pow( number1, number2 );
break;
case SQRT:
answer = Math.sqrt( number1 );
break;
} // end switch

return answer;
} // end calculate()

//==============================================================================
//Method showAnswer outputs the results in the calculators displays screen
//==============================================================================
public void showAnswer( String s )
{
double answer;

answer = Double.valueOf(s).doubleValue();
if ( decnumber )
result.setText( Double.toString(answer) );
else
result.setText( s ); //all output are displayed as integers at start

} // end showAnswer

//==============================================================================
//Method clickCheck determines if the user double clicked and returns a boolean
//value. If doubleclick is true, the program ignores the input
//==============================================================================
public boolean clickCheck( String s ) {
if ( s == "" )
doubleclick = true;
else
doubleclick = false;

return doubleclick;
}

//==============================================================================
//Method clearScreen clears calculator display screen and sets variables to
//default.
//==============================================================================
public void clearScreen()
{
oper = 0; // reinitialize variables to default
input = "";
answer = 0;
decnumber = false;
morenums = false;
firstpress = true;
equals = false;
showAnswer( Integer.toString( (int)answer) );
}

public void paint( Graphics g )
{
//draw border
g.drawRect( 0, 0, size().width - 1, size().height - 1 );
g.drawLine( 0, 0, 0, size().height );
}
} // end program

source code for a game JAVA

import java.applet.*;
import java.lang.*;
import java.awt.*;
import java.net.*;

public class AllLights extends Applet {

final int ON = 1;
final int OFF = -1;
final int WIDTH = 200;
protected int light[][];
protected int counterOn = 0;
protected int counterOff = 0;
int end = 0;

public void init() {
end = 0;
light = new int[5][5];
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
light[i][j] = OFF;
}
}
countLight();
}

public void start() {
setBackground(Color.white);
init();
}

public void paint(Graphics g) {
g.setColor(Color.blue);
g.fill3DRect(210, 165, 60, 20, true);
g.setColor(Color.red);
g.drawString("RESTART", 214, 180);
drawBoard(g);
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (light[i][j] != 0) {
drawLight(i, j, g);
}
}
}
drawCountLight(g);
}

public void drawBoard(Graphics g) {
g.setColor(Color.black);
g.drawLine(0,0, 0,WIDTH);
g.drawLine(WIDTH,0, WIDTH,WIDTH);
g.drawLine(0,0, WIDTH,0);
g.drawLine(0,WIDTH, WIDTH,WIDTH);
for (int i = 1; i < 5; i++) {
g.drawLine(WIDTH*i/5,0, WIDTH*i/5,WIDTH);
g.drawLine(0,WIDTH*i/5, WIDTH,WIDTH*i/5);
}
}

public void drawLight(int column, int row, Graphics g) {
if (light[column][row] == ON) {
g.setColor(Color.yellow);
} else if (light[column][row] == OFF) {
g.setColor(Color.gray);
}
g.fillRect(column * WIDTH / 5 + 2, row * WIDTH / 5 + 2,
WIDTH / 5 - 3, WIDTH / 5 - 3);
}

void countLight() {
counterOn = 0;
counterOff = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if(light[i][j] == ON) counterOn++;
if(light[i][j] == OFF) counterOff++;
}
}
if (counterOn == 25) {
endGame(getGraphics());
}
}

public void endGame(Graphics g) {
update(getGraphics());
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
light[i][j] = OFF;
update(getGraphics());
}
}
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
light[i][j] = ON;
update(getGraphics());
}
}
g.setColor(Color.yellow);
g.fillRect(65, 98, 80, 10);
g.setColor(Color.black);
g.drawString("Congratulations!!", 66, 106);
g.setColor(Color.red);
g.drawString("Congratulations!!", 65, 105);
end = 1;
}

void drawCountLight(Graphics g) {
g.setColor(Color.white);
g.fill3DRect(WIDTH+15, 50, 30,20, false);
g.fill3DRect(WIDTH+15, 110, 30,20, false);
g.setColor(Color.gray);
g.fill3DRect(WIDTH+5, 85, 20,20, true);
g.setColor(Color.yellow);
g.fill3DRect(WIDTH+5, 20, 20,20, true);
g.setColor(Color.black);
g.drawString("LightOn", WIDTH+30, 35);
g.drawString("LightOff", WIDTH+30, 100);
g.drawString(Integer.toString(counterOn), WIDTH+20, 65);
g.drawString(Integer.toString(counterOff), WIDTH+20, 125);
}

public boolean mouseUp(Event event, int x, int y) {
if (end == 1) {
init();
update(getGraphics());
} else {
if (x > 210 && x < 270 && y > 165 && y < 185) {
init();
update(getGraphics());
}
int column = (int)(x / (WIDTH / 5));
int row = (int)(y / (WIDTH / 5));
light[column][row] = -light[column][row];
try {
light[column+1][row] = -light[column+1][row];
} catch(Exception e) {
}
try {
light[column-1][row] = -light[column-1][row];
} catch(Exception e) {
}
try {
light[column][row+1] = -light[column][row+1];
} catch(Exception e) {
}
try {
light[column][row-1] = -light[column][row-1];
} catch(Exception e) {
}
countLight();
if (end == 0) {
update(getGraphics());
}
}
return true;
}
}
//click here for the game and further info

source code for a game absulute JAVA

// Absolute Space

import java.awt.*;
import java.net.*;
import java.applet.Applet;
import java.applet.AudioClip;

public class Absolute extends Applet implements Runnable
{
Dimension d;
Font largefont = new Font("Helvetica", Font.PLAIN, 24);
Font smallfont = new Font("Helvetica", Font.PLAIN, 14);

FontMetrics fmsmall, fmlarge;
Graphics goff;
Image ii;
Thread thethread;

boolean ingame=false;

int x, y, mousex, mousey, oldx, oldy, dx=0, dy=0, count, shield=0;
boolean showtitle=true;
Image ship;
Image[] fire;
int firecnt=0;

// Bullet variables
Image bullet;
int[] bx;
int[] by;
final int bmy=16, bul_xs=54, bul_ys=8;

// Meteor variables
Image meteor;
int maxmet, metcount, mtotal, mrenew, metmy;
int[] metx;
int[] mety;
int[] metf;
boolean[] metr;
final int sxmet=80, symet=84;

// These are for the star field
public int starsX[];
public int starsY[];
public Color starsC[];
public int numStars = 30;
public int speed = 6, xSize, ySize;

// Variables for big boom
Image[] boom;
int rndbx, rndby, rndcnt=777;
final int sxbom=71, sybom=100, bframes=4;

// Global Variables
int distance=0, maxdist=2000;
int slevel, blevel, difflev, bosslevel;
int smax, bmax;
int scur, bcur, renew, rcnt=0, sstretch, txtalign=100;
long score;

// Sounds
AudioClip blast, crash, kill;

// Bosses here
// Sunbird
boolean sunbird, sbefore, safter;
int sbx, sby, sbmove, maxtribe, tribe;
int[] sbfx, sbfy;

final int maxshield=9;
final int backcol=0x102040;
final int fireframe=2;
final int borderwidth=0;
final int sxsize=90, sysize=39, sxfire=11, syfire=6;
final int movex=10, movey=5;
final int scoreheight=45;
final int screendelay=300;

public String getAppletInfo()
{
return("Absolute Space - by Aleksey Udovydchenko");
}

public void init()
{
Graphics g;
int n;
d = size();
setBackground(Color.black);
g=getGraphics();
g.setFont(smallfont);
fmsmall = g.getFontMetrics();
g.setFont(largefont);
fmlarge = g.getFontMetrics();
ship = getImage(getCodeBase(), "ship.gif");
bullet = getImage(getCodeBase(), "bullet.gif");
fire = new Image[fireframe];
for (n=0; n<fireframe; n++) {
fire[n] = getImage(getCodeBase(), "fire"+n+".gif");
}
boom = new Image[bframes+1];
for (n=0; n<=bframes; n++) {
boom[n] = getImage(getCodeBase(), "boom"+n+".gif");
}

xSize = d.width - borderwidth*2;
ySize = d.height - borderwidth*2 - scoreheight;

x = (xSize - sxsize) / 2;
y = ySize - sysize - scoreheight - borderwidth;
mousex = -1;

// will be override by command line parameters
blevel = 3;
slevel = 3;

bx = new int[blevel*10];
by = new int[blevel*10];

for (n=0; n<blevel*10; n++) {
bx[n] = -1;
}

// Meteor initiliaze
meteor = getImage(getCodeBase(), "meteor.gif");
maxmet = d.height / symet + 1;
maxmet = maxmet * 10;
metx = new int[maxmet];
mety = new int[maxmet];
metf = new int[maxmet];
metr = new boolean[maxmet];

// Audio
try {
blast = getAudioClip(new URL(getDocumentBase(), "blast.au"));
crash = getAudioClip(new URL(getDocumentBase(), "collisn.au"));
kill = getAudioClip(new URL(getDocumentBase(), "mdestr.au"));
}
catch (MalformedURLException e) {}

blast.play(); blast.stop();
crash.play(); crash.stop();
kill.play(); kill.stop();

initStars();

rndcnt = 777;

// Bosses
// Sunbird
sbfx = new int[11];
sbfy = new int[11];
sbfx[0] = 10;
sbfy[0] = 0;
sbfx[1] = 15;
sbfy[1] = 10;
sbfx[2] = 0;
sbfy[2] = 10;
sbfx[3] = 3;
sbfy[3] = 15;
sbfx[4] = 17;
sbfy[4] = 15;
sbfx[5] = 20;
sbfy[5] = 20;
sbfx[6] = 23;
sbfy[6] = 15;
sbfx[7] = 37;
sbfy[7] = 15;
sbfx[8] = 40;
sbfy[8] = 10;
sbfx[9] = 25;
sbfy[9] = 10;
sbfx[10] = 30;
sbfy[10] = 0;

}

// This creates the starfield in the background
public void initStars () {
starsX = new int[numStars];
starsY = new int[numStars];
starsC = new Color[numStars];
for (int i = 0; i < numStars; i++) {
starsX[i] = (int) ((Math.random() * xSize - 1) + 1);
starsY[i] = (int) ((Math.random() * ySize - 1) + 1);
starsC[i] = NewColor();
}
}

public boolean keyDown(Event e, int key)
{
if (ingame)
{
mousex = -1;
if (key == Event.LEFT)
dx=-1;
if (key == Event.RIGHT)
dx=1;
if (key == Event.UP)
dy=-1;
if (key == Event.DOWN)
dy=1;
if (key == ' ')
if (bcur>0) FireGun();
if (key == Event.ESCAPE)
ingame=false;
}
else
{
if (key == 's' || key == 'S')
{
ingame=true;
GameStart();
}
}
return true;
}

public boolean keyUp(Event e, int key)
{
System.out.println("Key: "+key);
if (key == Event.LEFT || key == Event.RIGHT)
dx=0;
if (key == Event.UP || key == Event.DOWN)
dy=0;
return true;
}

public void paint(Graphics g)
{
String s;
Graphics gg;

if (goff==null && d.width>0 && d.height>0)
{
ii = createImage(d.width, d.height);
goff = ii.getGraphics();
}
if (goff==null || ii==null)
return;

goff.setColor(Color.black);
goff.fillRect(0, 0, d.width, d.height);

if (ingame)
PlayGame();
else
ShowIntroScreen();
g.drawImage(ii, 0, 0, this);
}


public void PlayGame()
{
NewMeteor();
MoveShip();
DrawPlayField();

// Big bosses here
if (sunbird) SunBird();

ShowScore();
distance++;
score+=100;
if (distance % maxdist == 0) {
difflev++;
if (difflev>2 & difflev<10) {
renew-=20;
bmax+=1;
smax+=1;
metmy++;
mrenew--;
}
if (difflev>3 & difflev<11) {
maxtribe++;
sbmove++;
}
if (difflev>3) {
sunbird = true;
tribe = maxtribe;
}
}

// Renew Ship Energy
rcnt++;
if (rcnt % (renew / blevel) == 0) {
bcur++;
if (bcur>bmax) bcur=bmax;
}
if (distance % 500 == 0) {
scur++;
if (scur>smax) scur=smax;
}
if (rcnt>renew) rcnt=0;
}

public void ShowIntroScreen()
{
String s;

DrawPlayField();
goff.setFont(largefont);

if (rndcnt > bframes) {
rndbx = (int) (Math.random() * (xSize - sxbom) + 1);
rndby = (int) (Math.random() * (ySize - sybom) + 1);
rndcnt = 0;
}

goff.drawImage(boom[rndcnt], rndbx, rndby, this);
rndcnt++;
for (int i=0; i<xSize/bul_xs; i++) {
goff.drawImage(bullet, i*bul_xs, 0, this);
goff.drawImage(bullet, i*bul_xs, ySize-bul_ys, this);
}

if (showtitle)
{
goff.setColor(new Color(0xff0000));
s="Absolute Space";
goff.drawString(s,(d.width-fmlarge.stringWidth(s)) / 2, (d.height-scoreheight-borderwidth)/2 - 20);
goff.setColor(new Color(0xff00ff));
s="(c)2000 by Aleksey Udovydchenko";
goff.setFont(smallfont);
goff.drawString(s,(d.width-fmsmall.stringWidth(s))/2,(d.height-scoreheight-borderwidth)/2 + 10);
s="freewebdesign@crosswinds.net";
goff.drawString(s,(d.width-fmsmall.stringWidth(s))/2,(d.height-scoreheight-borderwidth)/2 + 30);
}
else
{
goff.setFont(smallfont);
goff.setColor(new Color(0xffff00));
s="Leftclick to start game";
goff.drawString(s,(d.width-fmsmall.stringWidth(s))/2,(d.height-scoreheight-borderwidth)/2 - 10);
goff.setColor(new Color(0x00ff00));
s="Use cursor keys move, click or press SPACE to fire";
goff.drawString(s,(d.width-fmsmall.stringWidth(s))/2,(d.height-scoreheight-borderwidth)/2 + 20);
goff.setFont(largefont);
goff.setColor(new Color(0xff00ff));
s="LAST SCORE: "+score;
goff.drawString(s,(d.width-fmlarge.stringWidth(s))/2,(d.height-scoreheight-borderwidth)/2 + 120);
}
count--;
if (count<=0)
{ count=screendelay; showtitle=!showtitle; }
}

public void DrawPlayField()
{

// Show stars
moveStars();
for (int a = 0; a < numStars; a++) {
goff.setColor(starsC[a]);
goff.drawRect(starsX[a], starsY[a], 1, 1);
}

ShowMeteors();
KillEmAll();
goff.drawImage(ship, x, y, this); // paint ship
if (firecnt != 0) {
goff.drawImage(fire[firecnt-1], x+( (sxsize-sxfire) / 2 ), y+sysize, this); // engine fire
}
firecnt++;
if (firecnt > 2) firecnt=0;
Collisions();

if (shield>0) {
goff.setColor(new Color(0x00ffff));
goff.drawOval(x-shield, y-shield, sxsize+shield*2, sysize+shield*2);
shield--;
}

}

public void ShowScore()
{
String s;
int my;
sstretch = (xSize-txtalign*2)/Math.max(bmax,smax);
// Laser bar
my = d.height-scoreheight+10;
goff.setColor(new Color(0x00ff96));
goff.drawRect(txtalign, my-10, bmax*sstretch, 10);
goff.setFont(smallfont);
s="laser: "+bcur+"/"+bmax;
goff.fillRect(txtalign, my-10, bcur*sstretch, 10);
goff.drawString(s,10,my);
// Shield bar
my += 15;
goff.setColor(new Color(0x00ffff));
goff.drawRect(txtalign, my-10, smax*sstretch, 10);
goff.setFont(smallfont);
s="shield: "+scur+"/"+smax;
goff.fillRect(txtalign, my-10, scur*sstretch, 10);
goff.drawString(s,10,my);
// Score
my += 20;
goff.setColor(new Color(0xffffff));
goff.setFont(largefont);
s="score: "+score;
goff.drawString(s,10,my);
}

public void MoveShip()
{
int xx, yy;
oldx = x;
oldy = y;

xx = mousex;
if (xx>0) {
yy = mousey;
if (xx<x) dx=-1;
if (xx>x+sxsize) dx=1;
if (yy<y) dy=-1;
if (yy>y+sysize) dy=1;
if (xx>x & xx<x+sxsize & yy>y & yy<y+sysize) {
dx = 0;
dy = 0;
mousex = -1;
}
}

x+=dx*movex;
y+=dy*movey;

if (y<=borderwidth || y>=(d.height-sysize-scoreheight))
{
dy=0;
y=oldy;
}
if (x>=(d.width-borderwidth-sxsize) || x<=borderwidth)
{
dx=0;
x=oldx;
}
}

public void FireGun()
{
int n=0, f=-1;
while (n<blevel*10 && bx[n]>=0) n++;
if (n<blevel*10) f = n;
if (f>=0) {
bx[f] = x+( (sxsize-bul_xs) / 2);
by[f] = y;
bcur--;
blast.play();
}
}

public void KillEmAll()
{
int f;
for (int n=0; n<blevel*10; n++) {
if (bx[n]>0) {
by[n] -= bmy;
if ( by[n] < borderwidth | MetHit(n) | BirdHit(bx[n], by[n]) ) {
bx[n] = -1;
} else {
goff.drawImage(bullet, bx[n], by[n], this); // paint bullet
}
}
}
}

public boolean MetHit(int f)
{
for (int n=0; n<maxmet; n++) {
if (metx[n]>=0) {
if (metr[n] & bx[f]+bul_xs>metx[n] & bx[f]<metx[n]+sxmet & by[f]+bul_ys>mety[n] & by[f]<mety[n]+symet) {
DelMeteor(n);
kill.play();
return true;
}
}
}
return false;
}

public void ShowMeteors()
{
int n;
mtotal = 0;
for (n=0; n<maxmet; n++) {
if (metx[n]>=0) {
mtotal++;
mety[n] += metmy;
if (mety[n] > d.height-borderwidth-scoreheight) {
DelMeteor(n);
} else {
if (metr[n]) {
goff.drawImage(meteor, metx[n], mety[n], this); // paint meteor
} else {
goff.drawImage(boom[bframes-metf[n]], metx[n]+(sxmet-sxbom)/2, mety[n]+(symet-sybom)/2, this); // paint boom
metf[n]--;
if (metf[n]<0) DelMeteor(n);
}
}
}
}
}

public void NewMeteor()
{
int n=0, f=-1;
metcount++;
if (metcount > mrenew/metmy) {
metcount = 0;
while (n<maxmet & metx[n]>=0) n++;
if (n<maxmet) f = n;
if (f>=0) {
metx[f] = (int) (Math.random() * (xSize - sxmet) + 1);
mety[f] = borderwidth-symet;
metr[f] = true;
metf[f] = bframes;
}
}
}

// If a star in the background reaches the bottome then it will go back to the top
public void moveStars () {
for (int i = 0; i < numStars; i++) {
if (starsY[i] + 1 > ySize - (speed * 2 )) {
starsY[i] = 0;
starsX[i] = (int) ((Math.random() * xSize - 1) + 1);
starsC[i] = NewColor();
}
else {
starsY[i] += speed;
}
}
}

public void Collisions()
{

for (int n=0; n<maxmet; n++) {
if (metx[n]>=0) {
if (metr[n] & x+sxsize>metx[n] & x<metx[n]+sxmet & y+sysize>mety[n] & y<mety[n]+symet) {
HitShip();
DelMeteor(n);
}
}
}

}

public void HitShip()
{
crash.play();
shield=maxshield;
scur--;
if (scur<0) GameOver();
}

public void DelMeteor(int n)
{
if (metr[n]) {
metr[n] = false;
metf[n] = bframes;
} else {
metx[n] = -1;
metr[n] = true;
metf[n] = 0;
}
}

public Color NewColor()
{
int[] rgb;
int t;
rgb = new int[3];
for (int i=0; i<3; i++) rgb[i] = 0;
t = (int) (Math.random()*3);
rgb[t] = (int) (Math.random()*128 + 1) + 127;
return new Color(rgb[0], rgb[1], rgb[2]);
}

public void run()
{
long starttime;
Graphics g;

Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
g=getGraphics();

while(true)
{
starttime=System.currentTimeMillis();
try
{
paint(g);
starttime += 30;
Thread.sleep(Math.max(0, starttime-System.currentTimeMillis()));
}
catch (InterruptedException e)
{
break;
}
}
}

public void start()
{
if (thethread == null) {
thethread = new Thread(this);
thethread.start();
}
}

public void stop()
{
if (thethread != null) {
thethread.stop();
thethread = null;
}
}

// This class handles mouse clicking
public boolean mouseDown(Event e,int xx,int yy)
{
if (ingame) {
mousex = xx;
mousey = yy;
keyDown(e, 32);
} else {
keyDown(e, 'S');
}
return true;
}

// Game Start
public void GameStart()
{
// Set Up Ship variables
bmax = blevel*blevel;
bcur = bmax;
smax = slevel*slevel;
scur = smax;
difflev = 3;
distance=0;
score=0;
renew=250;
for (int n=0; n<maxmet; n++) {
metx[n] = -1;
metf[n] = 0;
metr[n] = true;
}
metcount=0;
metmy=2;
mrenew=60;

// Bosses init
// #1 - SunBird;
sbx = -1;
sbmove = 2;
maxtribe = 1;
sunbird=false;
sbefore = true;
safter = false;
}

// Game Over
public void GameOver()
{
ingame=false;
}

// Boss #1 - Sunbird's pack
public void SunBird()
{
int[] xcur, ycur;
xcur = new int[11];
ycur = new int[11];
if (sbx<0) {
sbx = (int) ((Math.random() * xSize - 40) + 1);
sby = -5;
sbefore = true;
safter = false;
}
sby += sbmove;
if (y+sysize/2<sby) safter = true;
goff.setColor(new Color(0xffff00));
if (sbefore & safter) {
// hit ship
goff.fillRect(0, sby+15, xSize, 2);
HitShip();
}
for (int i=0; i<11; i++) {
xcur[i] = sbfx[i] + sbx;
ycur[i] = sbfy[i] + sby;
}
goff.fillPolygon(xcur, ycur, 11);
if (sby>xSize+20) {
sbx=-1;
sbefore = true;
safter = false;
}
sbefore=false;
if (y+sysize/2>sby) sbefore = true;
}

public boolean BirdHit(int blx, int bly) {
if (sunbird) {
if (blx+bul_xs>sbx & blx<sbx+40 & bly+bul_ys>sby & bly<sby+20) {
tribe--;
if (tribe<0) sunbird=false;
sbx=-1;
sbefore = true;
safter = false;
return true;
}
}
return false;
}

}
Back to Absolute