Showing posts with label java gui. Show all posts
Showing posts with label java gui. Show all posts

13 July 2014

KeyListener example in java

KeyListener Example


/*
*its the first class
*save is as Car.java
/*
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;

public class Car {

static int CARWIDTH = 40;
static int CARLENGTH = 70;
int x = Game.WIDTH/2 - CARWIDTH/2;
int y = Game.HEIGHT - 105;
int dx = 0;
int dy = 0;
private Game game;

public Car(Game game){
this.game = game;
}

public void paint(Graphics2D g2d){
g2d.setColor(Color.blue);
g2d.fillRect(x, y, CARWIDTH, CARLENGTH);
}

public void move(){

if(x+dx > 0 && x+dx < Game.WIDTH-56) x = x+dx;
if(y+dy > 0 && y+dy < Game.HEIGHT-105) y = y+dy;

}

public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_LEFT) dx = -1;
if(e.getKeyCode() == KeyEvent.VK_RIGHT) dx = 1;
if(e.getKeyCode() == KeyEvent.VK_UP) dy = -1;
if(e.getKeyCode() == KeyEvent.VK_DOWN) dy = 1;
}

public void keyReleased(){
dx = 0;
dy = 0;
}

}
//////////////EnD of First Class////////////////

/*
*its the SECOND class
*save is as Game.java
/*


import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class Game extends JPanel{

static int WIDTH = 500;
static int HEIGHT = 700;
Car car = new Car(this);


public Game(){
addKeyListener(new KeyListener() {

@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub

}

@Override
public void keyReleased(KeyEvent e) {
car.keyReleased();

}

@Override
public void keyPressed(KeyEvent e) {
car.keyPressed(e);

}
});
setFocusable(true);
}

private void move(){
car.move();
}

public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
car.paint(g2d);
}



public static void main(String args[]) throws InterruptedException{
Game game = new Game();
JFrame frame = new JFrame("Car Game");
frame.add(game);
frame.getContentPane().setBackground(Color.white);
frame.setSize(WIDTH, HEIGHT);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


while(true){
game.move();
game.repaint();
Thread.sleep(1);
}
}


}
////////////////////EnD of Second Class////////////////////////////

How to paddle in brick breaker

Simple Paddle in Brick Breaker




Code for simple paddle in java brick breaker game

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;

import test1.BallBreaker;



public class Bat extends JPanel{


private int x = 140;

private int y = 240;

int width = 30;

int height = 10;
public Bat(){
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent evt) {
moveIt(evt);
}
});
setFocusable(true);
}

public void paint(Graphics g)
{
/*
*
* As we are extending JPanel,
* we need to paint background with some color first
* Note: if we extend Canvas class than we need not
* paint back ground. we can directly draw peddle
*/
g.setColor(Color.LIGHT_GRAY);//paint background with light gray
g.fillRect(0, 0, 350, 450);//screen dimensions
g.setColor(Color.blue);//change color value from gray to blue
g.drawRect(x, y, width, height);
g.fillRect(x, y, width, height);//fill blue color to paddle

/*
* you can uncomment below two lines to see styles of peddle
*/
// g.fill3DRect(x, y+40, width, height, false);

// g.fill3DRect(x, y+80, width, height, true);
}
protected void moveIt(KeyEvent evt) {////finds which key is pressed eighter left of right
if (x < 3) {
x = 3;
} else if (x > 290) {
x = 290;
}

switch (evt.getKeyCode()) {
case KeyEvent.VK_LEFT:
x -= 5;
break;
case KeyEvent.VK_RIGHT:
x += 5;
break;
}

repaint();
}

//public int getX() {
// return x;
//}
//
//public void setX(int x) {
// this.x = x;
//}
//
//public int getY() {
// return y;
//}
//
//public void setY(int y) {
// this.y = y;
//}

public static void main(String[] args) {
Bat bat = new Bat();
JFrame jf = new JFrame("game");
jf.add(bat);
jf.setSize(350,450);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


}


}

25 April 2014

draw text in canvas using edittext

draw text in canvas using edittext

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="packagename.MainActivity">

<intraction.arrow.app.DrawView
    android:id="@+id/drawView"
    android:layout_width="fill_parent"
    android:layout_height="200dp" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText"
        android:hint="Enter your Text"
        android:focusable="true"
        android:layout_below="@+id/drawView"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save Image"
        android:id="@+id/button"
        android:layout_below="@+id/editText"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />


</RelativeLayout>




MainActivity.java

package packagename;


import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;



public class MainActivity extends ActionBarActivity {

    Communicator communicator;
//ListView listView;
    EditText editText;
    Button saveButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //listView = (ListView) findViewById(R.id.listView);
        //NetworkConfig config = new NetworkConfig("http://arrowgifts.com/mobile/mobile_home");

        //drawView = new DrawView(this);
        //drawView = (DrawView) findViewById(R.id.drawView);
        communicator = (Communicator)findViewById(R.id.drawView);
        //setContentView(drawView);
       // save();
        saveButton = (Button) findViewById(R.id.button);
        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                communicator.saveImage();
            }
        });
        editText = (EditText) findViewById(R.id.editText);
editText.addTextChangedListener( new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
communicator.writeText(editText.getText().toString());
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
});
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
     
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

/**
 * Communicator
 * **/
public interface Communicator{
    public void writeText(String string);
    public void saveImage();
}



}
//...................................\\


DrawView.java

package packagename;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;


import android.util.AttributeSet;

import android.view.View;



/**
 * Created by sravan on 4/22/2014.
 */
public class DrawView extends View implements MainActivity.Communicator {
    Bitmap bitmap;
Bitmap newBitmap;

//        public DrawView(Context context) {
//            this(context,null);
//        bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.templer);
//        newBitmap = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth()-100,bitmap.getHeight()-100);
//
//
//    }

    public DrawView(Context context, AttributeSet attrs) {

        super(context, attrs);
        bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.templer);
        newBitmap = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth()-100,bitmap.getHeight()-100);
    }

//    public DrawView(Context context, AttributeSet attrs, int defStyleAttr) {
//        super(context, attrs, defStyleAttr);
//    }







    @Override
    protected void onDraw(Canvas canvas) {

        super.onDraw(canvas);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.RED);
        paint.setTextSize(50);
        paint.setStyle(Paint.Style.FILL);


        canvas.drawBitmap(newBitmap, 0, 0, null);

        canvas.drawText(textToBeWritten, 10, 50, paint);
        setDrawingCacheEnabled(true);

    }

private String textToBeWritten ="Enter Text" ;
    @Override
    public void writeText(String string) {
        textToBeWritten = string;
        invalidate();
    }

    @Override
    public void saveImage() {
        SaveFile saveFile = new SaveFile();
        saveFile.save(getDrawingCache());
    }
}



SaveFile.java


package packagename;

import android.graphics.Bitmap;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;

/**
 * Created by sravan on 4/23/2014.
 */
public class SaveFile {

    //Bitmap bitmap;// = getDrawingCache();
    public void save(Bitmap bitmap) {


        String root = Environment.getExternalStorageDirectory().toString();
        File myDir = new File(root + "/saved_images");
        myDir.mkdirs();

        String fname = "Image.jpg";
        File file = new File (myDir, fname);
        if (file.exists ()) file.delete ();
        try {
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
            Log.i("Success", root + "/saved_images");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
//..............................//


Tested in Android 4.2.2. API Level 19, and working fine.

Contact Form

Name

Email *

Message *

Smooth Graphics Java

// Arrange Bricks in Game //java brick breaker game code without flickering // added game levels 1,2,3 in the game //java paddle ball ga...