6.01.2010

Menggambar pada Frame

Berikut ini adalah source kode untuk menggambar import javax.swing.*;
import java.awt.*;

public class DrawingColor{
public static void main(String[] args) {
DrawingColor d = new DrawingColor();
}

public DrawingColor(){
JFrame frame = new JFrame("Drawing colorfull shapes");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MyComponent());
frame.setSize(400,400);
frame.setVisible(true);
}

public class MyComponent extends JComponent{
public void paint(Graphics g){
int height = 200;
int width = 120;
g.setColor(Color.red);
g.drawRect(10,10,height,width);
g.setColor(Color.gray);
g.fillRect(11,11,height,width);
g.setColor(Color.red);
g.drawOval(250,20, height,width);
g.setColor(Color.magenta);
g.fillOval(249,19,height,width);
}
}
}

Baca Selengkapnya......

1.23.2009

Animation

Membuat sedikit animasi mugkin akan menambah indah hasil program yang dihasulkan kode berikut adalah salah satu contoh yang mungkin bisa jadi gambaran :

import java.util.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class Animation extends MIDlet
{
private Display display; // The display
private AnimationCanvas canvas; // Canvas
private Timer tm; // Timer
private AnimateTimerTask tt; // Task

public Animation()
{
display = Display.getDisplay(this);
canvas = new AnimationCanvas(this);

// Create task that fires off every 1/10 second
tm = new Timer();
tt = new AnimateTimerTask(canvas);
tm.schedule(tt, 0, 100);
}

protected void startApp()
{
display.setCurrent(canvas);
}

protected void pauseApp()
{ }

protected void destroyApp(boolean unconditional)
{ }

public void exitMIDlet()
{
destroyApp(true);
notifyDestroyed();
}
}
class AnimateTimerTask extends TimerTask
{
private AnimationCanvas canvas;

public AnimateTimerTask(AnimationCanvas canvas)
{
this.canvas = canvas;
}

public final void run()
{
// ****************************************************
if ((canvas.x_loc + canvas.radius + canvas.x_dir > canvas.getWidth()) ||
(canvas.x_loc - canvas.radius + canvas.x_dir < 0))
{
canvas.x_dir = -canvas.x_dir;
canvas.changeColor();
canvas.directionChanged++;
}

// **************************************************
if ((canvas.y_loc + canvas.radius + canvas.y_dir > canvas.getHeight()) ||
(canvas.y_loc - canvas.radius + canvas.y_dir < 0))
{
canvas.y_dir = -canvas.y_dir;
canvas.changeColor();
canvas.directionChanged++;
}

//*********************************
canvas.x_loc += canvas.x_dir;
canvas.y_loc += canvas.y_dir;

canvas.repaint();
}
}

class AnimationCanvas extends Canvas implements CommandListener
{
private Animation midlet; // Main midlet
private Command cmExit; // Exit midlet
private int keyFire, // Reset ball
keyRight, // Increase ball radius
keyLeft; // Decrease ball radius
private boolean clearBackground = false; // Clear background
private Random random; // Random number
int x_loc, // Current x & y locations
y_loc,
radius, // Ball radius
red, // rgb colors
green,
blue,
x_dir, // Next x & y positions of ball
y_dir,
start_x, // Where ball starts
start_y,
directionChanged = 0; // How many times we've hit a wall
private static final int MAX_CHANGES = 50;

/*--------------------------------------------------
* Constructor
*-------------------------------------------------*/
public AnimationCanvas(Animation midlet)
{
// ****************************
this.midlet = midlet;

random = new java.util.Random();

// Determine starting location and direction of ball
init();
radius = 7;

// ******************************************
cmExit = new Command("Exit", Command.EXIT, 1);

keyFire = getKeyCode(FIRE);
keyRight = getKeyCode(RIGHT);
keyLeft = getKeyCode(LEFT);

addCommand(cmExit);
setCommandListener(this);
}


protected void paint(Graphics g)
{
// ********************************
if (directionChanged > MAX_CHANGES)
init();

// the background
if (clearBackground)
{
g.setColor(255, 255, 255);
g.fillRect(0, 0, getWidth(), getHeight());
clearBackground = !clearBackground;
}

// Set warna dan gambar
g.setColor(red, green, blue);
g.fillArc( x_loc, y_loc, radius, radius, 0, 360);
}

/*--------------------------------------------------
* Ini Lokasi ball
*-------------------------------------------------*/
private void init()
{
// Start close to the middle
x_loc = getWidth() / 2;
y_loc = getHeight() / 2;

// The direction the ball is heading
x_dir = (random.nextInt() % 10);
if (x_dir == 0) x_dir = 1;

y_dir = (random.nextInt() % 10);
if (y_dir == 0) y_dir = 1;

directionChanged = 0;
clearBackground = true;
changeColor();
}


protected void changeColor()
{
// The shift is to remove any sign (negative) bit
red = (random.nextInt() >>> 1) % 256;
green = (random.nextInt() >>> 1) % 256;
blue = (random.nextInt() >>> 1) % 256;
}

/*--------------------------------------------------
* Event handling
*-------------------------------------------------*/
public void commandAction(Command c, Displayable d)
{
if (c == cmExit)
midlet.exitMIDlet();
}


protected void keyPressed(int keyCode)
{
// Restart
if (keyCode == keyFire)
init();
// Decrease ball size
else if (keyCode == keyLeft)
radius = Math.max(1, --radius);
else if (keyCode == keyRight)
// Increase ball size
radius = Math.min(getWidth() / 4, ++radius);
}
}

Baca Selengkapnya......

Contoh Text-Box Midlet

Lansung pada pokoknya hehe.. kita akan buat contoh program text Box Midlet... ketikan aja kode dibawah ini ya....!

import java.io.*;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;

import javax.microedition.lcdui.*;

import javax.microedition.midlet.MIDlet;

public class TextBoxMIDlet extends TextBoxMIDlet implements CommandListener {

// Exit command
private static final Command EXIT_COMMAND =
new Command("Exit", Command.EXIT, 0);

// OK command
private static final Command OK_COMMAND =
new Command("OK", Command.OK, 0);

// Clear text box content
private static final Command CLEAR_COMMAND =
new Command("Clear", Command.SCREEN, 1);

// Reverse the content of the text box
private static final Command REVERSE_COMMAND =
new Command("Reverse", Command.SCREEN, 1);

protected void startApp() {
boolean firstTime = !started;
super.startApp();

// If this is the first execution
// of startApp, install commands
if (firstTime) {
textBox.addCommand(OK_COMMAND);
textBox.addCommand(EXIT_COMMAND);
textBox.addCommand(CLEAR_COMMAND);
textBox.addCommand(REVERSE_COMMAND);
textBox.setCommandListener(this);
}
}

// Command implementations.
public void commandAction(Command c, Displayable d) {
if (c == EXIT_COMMAND) {
destroyApp(true);
notifyDestroyed();
} else if (c == OK_COMMAND) {
System.out.println("OK pressed");
} else if (c == CLEAR_COMMAND) {
textBox.setString(null);
} else if (c == REVERSE_COMMAND) {
String str = textBox.getString();
if (str != null) {
StringBuffer sb = new StringBuffer(str);
textBox.setString(sb.reverse().toString());
}
}
}
}

class TextBoxMIDlet extends MIDlet {

// Maximum size of the text in the TextBox
private static final int MAX_TEXT_SIZE = 64;

// The TextBox
protected TextBox textBox;

// The MIDlet's Display object
protected Display display;

// Flag indicating first call of startApp
protected boolean started;

protected void startApp() {
if (!started) {
// First time through - initialize
// Get the text to be displayed
String str = null;
try {
InputStream is = getClass().getResourceAsStream("test.txt");
InputStreamReader r = new InputStreamReader(is);
char[] buffer = new char[32];
StringBuffer sb = new StringBuffer();
int count;
while ((count = r.read(buffer, 0, buffer.length)) > -1) {
sb.append(buffer, 0, count);
}
str = sb.toString();
} catch (IOException ex) {
str = "Failed to load text";
}

// Create the TextBox
textBox = new TextBox("TextBox Example", str,
MAX_TEXT_SIZE, TextField.ANY);

// Create a ticker and install it
Ticker ticker = new Ticker("This is a ticker...");
textBox.setTicker(ticker);

// Install the TextBox as the current screen
display = Display.getDisplay(this);
display.setCurrent(textBox);

started = true;
}
}

protected void pauseApp() {
}

protected void destroyApp(boolean unconditional) {
}
}

Baca Selengkapnya......

WindowClosingExample

Kala Kita membuat program di dekstop kadang tanda silang yang berada pada jendela hasil eksekusi program tidak bisa ditutup, mungkin karena ada beberapa komponen yang belum dimasukan, sebagai contoh program mungkin kode dibawah ini bisa jadi rujukan buat pembaca sekalian.


package org.kodejava.example.swing;

import java.awt.Button;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;

public class WindowClosingExample extends JFrame {
public static void main(String[] args) {
WindowClosingExample frame = new WindowClosingExample();
frame.setSize(new Dimension(200, 200));
frame.add(new Button("Hello World"));

//
// Add window listener by implementing WindowAdapter class to the
// frame instance. To handle the close event we just need to implement
// the windowClosing() method.
//
frame.addWindowListener(new WindowAdapter() {

@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});

//
// Show the frame
//
frame.setVisible(true);
}
}

Baca Selengkapnya......

Tool Tips dengan Swing

Kalau kita menggerakan mouse melewati suatu objek di dekstop, kadang kita akan melihat
tulisan muncul dengan tiba-tibaatau dengan kata lain adalah Tool Tips yang berfungsi untuk memberikan keterangan tentang funsi suatu objek yang terlewati oleh mouse, pada contoh kali ini kita akan membuat tool tips dengan mengunakan java swing.

kode ini bisa di jalankan pada semua IDE nya java...
ketikan kode berikut ini :

package org.kodejava.example.swing;

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

public class MultilinesToolTip {
public static void main(String[] args) {
JFrame frame = new JFrame("Tool Tip Demo");
frame.setSize(200, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JLabel label = new JLabel("Tool Tips");

//
// Setting tool tip for our Swing JLabel component using an html
// formatted string so that we can create a multi lines tool tip.
//
label.setToolTipText(
"Coba ToolTips");
frame.getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER));
frame.getContentPane().add(label);

frame.setVisible(true);}}

Baca Selengkapnya......

FormattedTextFieldExample JFrame

Langsung saja deh kali ini kita membuat contoh aplikasi Format TextField di dekstop,
ketikan kode yang ada disini :

package org.kodejava.example.swing;

import javax.swing.*;
import javax.swing.text.MaskFormatter;
import javax.swing.text.DateFormatter;
import java.awt.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;

public class FormattedTextFieldExample extends JFrame {
public FormattedTextFieldExample() {
initComponents();
}

private void initComponents() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(new Dimension(200, 200));
getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));

MaskFormatter mask = null;
try {
//
// Create a MaskFormatter for accepting phone number, the # symbol accept
// only a number. We can also set the empty value with a place holder
// character.
//
mask = new MaskFormatter("(###) ###-####");
mask.setPlaceholderCharacter('_');
} catch (ParseException e) {
e.printStackTrace();
}

//
// Create a formatted text field that accept a valid phone number.
//
JFormattedTextField phoneField = new JFormattedTextField(mask);
phoneField.setPreferredSize(new Dimension(100, 20));

//
// Here we create a formatted text field that accept a date value. We
// create an instance of SimpleDateFormat and use it to create a
// DateFormatter instance which will be passed to the JFormattedTextField.
//
DateFormat format = new SimpleDateFormat("dd-MMMM-yyyy");
DateFormatter df = new DateFormatter(format);
JFormattedTextField dateField = new JFormattedTextField(df);
dateField.setPreferredSize(new Dimension(100, 20));
dateField.setValue(new Date());

getContentPane().add(phoneField);
getContentPane().add(dateField);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new FormattedTextFieldExample().setVisible(true);
}
});
}
}

Baca Selengkapnya......

GameActions


Kali ini kita akan membuat Gambe actions, dengan menggunakan menginport Midletnya sekalian. IDE yang digunakan dalam contoh ini adalah Net-Beans 5.5 dengan mobility-nya...!
lansung saja buat project baru di Net_Beansnya dengan nama file GameAction, lalu ketikan kode dibawah ini :

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class GameActions extends MIDlet
{
private Display display; // The display
private GameActionCanvas canvas; // Canvas

public GameActions()
{
display = Display.getDisplay(this);
canvas = new GameActionCanvas(this);
}

protected void startApp()
{
display.setCurrent( canvas );
}

protected void pauseApp()
{ }

protected void destroyApp( boolean unconditional )
{ }

public void exitMIDlet()
{
destroyApp(true);
notifyDestroyed();
}
}

/*--------------------------------------------------
* GameActionCanvas.java
*
* Game action event handling
*-------------------------------------------------*/
class GameActionCanvas extends Canvas implements CommandListener
{
private Command cmExit; // Exit midlet
private String keyText = null; // Key code text
private GameActions midlet;

/*--------------------------------------------------
* Constructor
*-------------------------------------------------*/
public GameActionCanvas(GameActions midlet)
{
this.midlet = midlet;

// Create exit command & listen for events
cmExit = new Command("Exit", Command.EXIT, 1);
addCommand(cmExit);
setCommandListener(this);
}

/*--------------------------------------------------
* Paint the text representing the key code
*-------------------------------------------------*/
protected void paint(Graphics g)
{
// Clear the background (to white)
g.setColor(255, 255, 255);
g.fillRect(0, 0, getWidth(), getHeight());

// Set color and draw text
if (keyText != null)
{
// Draw with black pen
g.setColor(0, 0, 0);
// Center the text
g.drawString(keyText, getWidth()/2, getHeight()/2, Graphics.TOP | Graphics.HCENTER);
}
}

/*--------------------------------------------------
* Command event handling
*-------------------------------------------------*/
public void commandAction(Command c, Displayable d)
{
if (c == cmExit)
midlet.exitMIDlet();
}

/*--------------------------------------------------
* Game action event handling
* A game action will be converted into a key code
* and handed off to this method
*-------------------------------------------------*/
protected void keyPressed(int keyCode)
{
switch (getGameAction(keyCode))
{
// Place logic of each action inside the case
case FIRE:
case UP:
case DOWN:
case LEFT:
case RIGHT:
case GAME_A:
case GAME_B:
case GAME_C:
case GAME_D:
default:
// Print the text of the game action
keyText = getKeyName(keyCode);
}
repaint();
}
}

Baca Selengkapnya......
Template by : kendhin x-template.blogspot.com