Drawing a line on transparent frame - graphics

I would like to build a simple highlighter program. The idea is to set an image to change the cursor so that it will look like a highlighter. And then, when we move the cursor, it will trace a line along with our movement. The requirement here is to be able to draw the line on a transparent background (not fully transparent though, just about 55%).
My progress so far is being able to draw the line, with transparent background. However, the line is also transparent. Here's my code : left click to begin drawing, right click to stop, and press space to change color.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
public class FreehandExample extends JFrame implements MouseListener, MouseMotionListener, KeyListener {
private int counter = 0;
private int draw = 0;
private int red[] = {58,71,231,243,255};
private int green[] = {54,224,235,109,40};
private int blue[] = {241,95,61,52,40};
private Point start, end;
private Graphics gd;
public FreehandExample()
{
setUndecorated(true);
setBackground(new Color(255,0,0));
setSize(new Dimension(300,200));
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addKeyListener(this);
addMouseListener(this);
addMouseMotionListener(this);
setOpacity(0.55f);
setVisible(true);
}
public void mousePressed(MouseEvent e) {
start = new Point(e.getX(), e.getY());
}
public void mouseClicked(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON1) draw = 1;
if(e.getButton() == MouseEvent.BUTTON3) draw = 0;
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseDragged(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {
gd = this.getGraphics();
if(draw==1){
end = new Point(e.getX(), e.getY());
gd.setColor(new Color( red[counter],green[counter],blue[counter]));
gd.drawLine(start.x, start.y, end.x, end.y);
start = end;
}
}
public static void main(String []args){
new FreehandExample();
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_SPACE) {
counter++;
if(counter>4) counter=0;
}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
}
I have tried the concept of per-pixel transparency... but the line drawing is not being drawn immediately... there is a delay before the line is drawn. However, it indeed produced the correct result e.g the line is not transparent while the frame is transparent.
Could someone please help me modify this code to meet the requirement...?
Thanks.

I've managed to solve this problem using per-pixel transparency, thanks to someone from emunewz forum :) The trick is to call paintComponent() using repaint() all the time after drawing, but the fillRect() method only need to be called just once so that our lines won't disappear.
Here is my code :
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.Paint;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GradientTranslucentWindow extends JFrame implements KeyListener, MouseListener, MouseMotionListener {
private int counter = 0;
private int draw = -1;
private int red[] = {58,71,231,243,255};
private int green[] = {54,224,235,109,40};
private int blue[] = {241,95,61,52,40};
private int R = 240;
private int G = 240;
private int B = 200;
private Point start, end;
private Graphics gd;
private JPanel panel;
public GradientTranslucentWindow() {
setBackground(new Color(0,0,0,0));
setSize(new Dimension(500,500));
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
if (g instanceof Graphics2D) {
Paint p = new GradientPaint(0.0f, 0.0f, new Color(R, G, B, 0), 0.0f, getHeight(), new Color(R, G, B, 150), true);
Graphics2D g2d = (Graphics2D)g;
g2d.setPaint(p);
if(draw==-1) g2d.fillRect(0, 0, getWidth(), getHeight());
}
}
};
setContentPane(panel);
addKeyListener(this);
addMouseListener(this);
addMouseMotionListener(this);
}
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
new GradientTranslucentWindow().setVisible(true);
}
public void mousePressed(MouseEvent e) { start = new Point(e.getX(), e.getY()); }
public void mouseClicked(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON1) draw = 1;
if(e.getButton() == MouseEvent.BUTTON3) draw = 0;
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseDragged(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {
gd = this.getGraphics();
if(draw==1){
end = new Point(e.getX(), e.getY());
gd.setColor(new Color( red[counter],green[counter],blue[counter]));
gd.drawLine(start.x, start.y, end.x, end.y);
start = end;
panel.repaint();
System.out.println(start.x + " - " + start.y);
}
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_SPACE) {
counter++;
if ( counter > 4 ) counter = 0;
}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
}

Related

Could some one help me with my Runnable. I have tried 3 different ways to handle this but I still can not seem to figure it out

my problem is in the onClick method. I just can't seem to figure out the how to properly construct a running Runnable/Thread/Handler.
package sed.jeff.conversion;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends Activity
{
private static final String TAG = "MainActivity";
Button btConvert;
EditText etInitialValue;
TextView tvAnswer;
Spinner spInitialType, spFinalType;
int mInitialValue, mInitialType, mFinalValue, mFinalType, mRegion = 0;
Distance D1;
Handler handler;
Runnable r;
//initialization
#Override
protected void onCreate(Bundle savedInstanceState)
{
Log.i(TAG, "entered onCreate()");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btConvert = (Button)findViewById(R.id.btnConvert);
etInitialValue = (EditText)findViewById(R.id.etInitialValue);
spInitialType = (Spinner)findViewById(R.id.spInitialType);
spFinalType = (Spinner)findViewById(R.id.spFinalType);
D1 = new Distance();
}
//implementation
protected void onStart()
{
Log.i(TAG, "entered onStart()");
super.onStart();
spInitialType.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
// TODO Auto-generated method stub
Log.i(TAG, "Initial Type position 1: " + position);
mInitialType = position;
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
// TODO Auto-generated method stub
}
});
spFinalType.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
// TODO Auto-generated method stub
Log.i(TAG, "Initial Type position 2: " + position);
mFinalType = position;
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
// TODO Auto-generated method stub
}
});
btConvert.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Log.i(TAG, "entered onClick()");
handler = new Handler();
r = new Runnable()
{
#Override
public void run()
{
tvAnswer.setText(D1.getAnswer(mRegion, mInitialType, mFinalType, Double.parseDouble(etInitialValue.getText().toString())));
handler.post(this);
}
};
handler.post(r);
}
});
}
}
This is the class I am using to do the conversion. The only important methods here as of right now are the constructor with no inputs and the String getAnswer() method.
package sed.jeff.conversion;
public class Distance
{
double league, mile, yard, feet, inch, line, thou;
double decameter, hectometer, kilometer, megameter, meter, decimeter, centermeter, micrometer;
double fathom, nauticalMile;
double chain, rod;
double furlong, horseLength;
double hubbleLength, parsec, lightYear, astronomicalUnit;
/*(
private static double[] THOU = {1, 83.333333, 1000, 12000, 36000, 63360000, 190080000};
private static double[] LINE = {.012, 1, 12, 144, 432, 760320, 2280960};
private static double[] INCH = {.001, .083333, 1, 12, 36, 63360, 190080};
private static double[] FOOT = {.000083, .006944, .083333, 1, 3, 5280, 15840};
private static double[] YARD = {.000028, .002315, .027778, .333333, 1, 1760, 5280};
private static double[] MILE = {.00000001578, .000001315, .0000157828, .00018939, .0005681818, 1, 3};
private static double[] LEAGUE = {.00000000526, .00000043841, .00000526094, .00006313131, .0001893939, .33333333, 1};
*/
private static double[][] CONVERSION_USA = {{1, 83.333333, 1000, 12000, 36000, 63360000, 190080000},
{.012, 1, 12, 144, 432, 760320, 2280960},
{.001, .083333, 1, 12, 36, 63360, 190080},
{.000083, .006944, .083333, 1, 3, 5280, 15840},
{.000028, .002315, .027778, .333333, 1, 1760, 5280},
{.00000001578, .000001315, .0000157828, .00018939, .0005681818, 1, 3},
{.00000000526, .00000043841, .00000526094, .00006313131, .0001893939, .33333333, 1}
};
public double[] answer;
public Distance()
{
answer = new double[7];
}
public Distance(int type, int initialMeasurement, double value)
{
answer = new double[7];
switch(type)
{
case 0:
uSMeasurments(initialMeasurement, value);
break;
}
}
private void uSMeasurments(int initialType, double value)
{
for(int i = 0; i < 7; i++ )
{
answer[i] = CONVERSION_USA[initialType][i] * value;
}
}
public String getAnswer(int region, int initialType, int finalType, double value)
{
String answer = null;
switch(region)
{
case 0:
answer = Double.toString(CONVERSION_USA[initialType][finalType] * value);
break;
}
return answer;
}
public String toString()
{
String finalAnswer = "";
for(int i = 0; i < 7; i++ )
{
finalAnswer += answer[i] + " ";
}
return finalAnswer;
}
}
In this case i do not think that you need to use a handler.
Otherwise a proper way would be to do something on these lines:
Runnable r=new Runnable() {
#Override
public void run() {
tvAnswer.setText(D1.getAnswer(mRegion, mInitialType, mFinalType, Double.parseDouble(etInitialValue.getText().toString())));
}
};
handler.post(r);

How can I do a sprite to jump with moveYModifier when I touch the screen

I'm still new with programming android. I have a problem with my game project. The problem is I have a problem with moveYModifier for sprite to jump when I touch the screen. Other problem is I got an error when I try to make a touch event method. Can somebody help me, so I can understand how to write correctly the method. I do not use engine extension because I think it's enough by using moveYModifier. I already search the answer but I still confuse about it. Thanks.
here my code :
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.modifier.MoveYModifier;
import org.anddev.andengine.entity.modifier.SequenceEntityModifier;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.scene.background.AutoParallaxBackground;
import org.anddev.andengine.entity.scene.background.ParallaxBackground.ParallaxEntity;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
import org.anddev.andengine.ui.activity.BaseGameActivity;
public class KetigaMainActivity extends BaseGameActivity implements IOnSceneTouchListener{
private int CAMERA_WIDTH = 800;
private int CAMERA_HEIGHT = 480;
private BitmapTextureAtlas bitmapTextureAtlas;
private TiledTextureRegion playerTextureRegion;
private BitmapTextureAtlas autoParallaxBackgroundTexture;
private TextureRegion parallaxLayerBack;
private TextureRegion parallaxLayerMid;
private TextureRegion parallaxLayerFront;
private TextureRegion parallaxLayerBackMid;
private int jumpHeight = 100;
private int jumpDuration = 2;
private int playerX = CAMERA_WIDTH/2;
private int playerY = CAMERA_HEIGHT - playerTextureRegion.getTileHeight() - (parallaxLayerFront.getHeight()/3);
#Override
public Engine onLoadEngine() {
final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera));
}
#Override
public void onLoadResources(){
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.bitmapTextureAtlas = new BitmapTextureAtlas(512, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
this.playerTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.bitmapTextureAtlas, this, "ulat10.png",0,0,4,2);
this.autoParallaxBackgroundTexture = new BitmapTextureAtlas(1024, 1024, TextureOptions.DEFAULT);
this.parallaxLayerFront = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.autoParallaxBackgroundTexture, this, "tanah6.png",0,810);
this.parallaxLayerBack = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.autoParallaxBackgroundTexture, this, "background1.png",0,0);
this.parallaxLayerBackMid = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.autoParallaxBackgroundTexture, this, "gunung3.png",0,490);
this.parallaxLayerMid = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.autoParallaxBackgroundTexture, this, "awan5.png",0,700);
this.mEngine.getTextureManager().loadTextures(this.bitmapTextureAtlas, this.autoParallaxBackgroundTexture);
}
#Override
public Scene onLoadScene(){
new Scene();
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene();
final AutoParallaxBackground autoParallaxBackground = new AutoParallaxBackground(0, 0, 0, 5);
autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(0.0f, new Sprite(0, CAMERA_HEIGHT - this.parallaxLayerBack.getHeight(), this.parallaxLayerBack)));
autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(-1/4.0f, new Sprite(0, CAMERA_HEIGHT - this.parallaxLayerBackMid.getHeight() - (parallaxLayerFront.getHeight()/6), this.parallaxLayerBackMid)));
autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(-1/2.0f, new Sprite(0, 0,this.parallaxLayerMid)));
autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(-3.0f, new Sprite(0, CAMERA_HEIGHT - this.parallaxLayerFront.getHeight(), this.parallaxLayerFront)));
scene.setBackground(autoParallaxBackground);
AnimatedSprite player = new AnimatedSprite(playerX, playerY, this.playerTextureRegion);
player.setScaleCenterY(this.playerTextureRegion.getTileHeight());
player.animate(new long[]{100, 100, 100},0 ,2, true);
scene.setOnSceneTouchListener(this);
scene.attachChild(player);
return scene;
}
#Override
public void onLoadComplete(){
}
#Override
public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
if (pSceneTouchEvent.isActionDown()) {
jump(); // this where I got an error
}
return false;
}
public boolean jump(AnimatedSprite player){
final MoveYModifier moveUpModifier = new MoveYModifier(jumpDuration /2, playerY, playerY + jumpHeight);
final MoveYModifier moveDownModivier = new MoveYModifier(jumpDuration /2, playerY + jumpHeight, playerY );
final SequenceEntityModifier modifier = new SequenceEntityModifier(moveUpModifier, moveDownModivier);
player.registerEntityModifier(new SequenceEntityModifier (modifier));
return true;
}
}
#Override
public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent)
{
if (pSceneTouchEvent.isActionDown())
{
jump(player);
}
return false;
}
You can use the JumpModifier instead
public boolean jump(AnimatedSprite player){
//your innitial y-position
final float innitialYPosition = 120;
//-140 means jump upward, positive move downward
JumpModifier jumpModifier = new JumpModifier(1, fromX, toX, fromY, toY, -140, new IEntityModifier.IEntityModifierListener() {
#Override
public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) {
animatedSprite.stopAnimation(0);
}
#Override
public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) {
animatedSprite.animate(50);
animatedSprite.setY(innitialYPosition);
}
});
animatedSprite.registerEntityModifier(jumpModifier);
}

Trying to print a string character by character with delay between two character print

I've tried with code below. please guide me where i am wrong??? The desired output is like..
m(delay)e(delay)s(delay)s(delay)a(delay)g(delay)e.
import java.util.*;
import java.applet.*;
import java.awt.*;
/*<applet code="MessageWithDelay" width=400 height=200>
</applet>*/
public class MessageWithDelay extends Applet implements Runnable {
Thread t;
//char msg[] ={"m","e","s","s","a","g","e"};
String str = "message";
Graphics bufferg;
Image buffer;
int counter=0,x=str.length(),i=0;;
public void init() {
//initializa the thread
t = new Thread(this);
t.start();
Dimension d = getSize();
buffer = createImage(d.width,d.height);
}
public void run() {
try {
while(true)
{
//requesting repaint
repaint();
if(counter==x)
{
Thread.sleep(200);
counter=0;
i=0;
}
else
{
Thread.sleep(400);
}
}
}
catch(Exception e) {
}
}
public void update(Graphics g) {
paint(g);
}
public void paint(Graphics g) {
if(bufferg == null) {
Dimension d = getSize();
bufferg.setColor(Color.green);
g.setFont(new Font("Comic Sans MS",Font.BOLD,36));
bufferg.drawString(str.charAt(i)+"",20,20);
counter++;
i+=1;
//update screen
g.drawImage(buffer,0,0,this);
}
}
}
I am working on command prompt and its giving me bunch of different errors. I want to know why the errors occurring if anyone could explain me by trying it. Thanx in advance.
The problems I found include:
Use JApplet instead of Applet.
In the init method, create the buffer before starting the thread.
Update the buffer with the letters in the run method. The paint method just paints. No calculations.
Here's the working code. I formatted the code in Eclipse, an integrated development environment (IDE) for Java development.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JApplet;
/*<applet code="MessageWithDelay" width=400 height=200>
</applet>*/
public class MessageWithDelay extends JApplet implements Runnable {
private static final long serialVersionUID = 1722008447683646619L;
Thread t;
String str = "message";
Image buffer;
#Override
public void init() {
Dimension d = getSize();
buffer = createImage(d.width, d.height);
// Initialize the thread
t = new Thread(this);
t.start();
}
#Override
public void run() {
int x = 40;
int y = 40;
for (int i = 0; i < str.length(); i++) {
Graphics g = buffer.getGraphics();
g.setFont(new Font("Comic Sans MS", Font.BOLD, 36));
g.setColor(Color.GREEN);
g.drawString("" + str.charAt(i), x, y);
g.dispose();
x += 40;
repaint();
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
}
}
}
#Override
public void update(Graphics g) {
paint(g);
}
#Override
public void paint(Graphics g) {
g.drawImage(buffer, 0, 0, this);
}
}

Java Painting issues

I need help with a "paint" program. I've got the GUI established, but I'm having issues with the actual drawing portion of the program. Everything I draw disappears immediately after I draw it, and I can't figure out why.
Here is what I have so far:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JPaint extends JFrame implements ActionListener, MouseListener, MouseMotionListener {
int x, y, x2, y2;
private int select = 0;
private Graphics g;
private PaintPanel DrawPanel = new PaintPanel(this);
private JPanel ButtonPanel = new JPanel();
private JTextArea Draw = new JTextArea(20,20);
private JButton jbtRed = new JButton("Red");
private JButton jbtGreen = new JButton("Green");
private JButton jbtBlue = new JButton("Blue");
private JButton jbtErase = new JButton("Eraser");
private JButton jbtClear = new JButton("Clear");
PaintPanel l=new PaintPanel(this);
public JPaint(){
super("Java Paint");
setSize(480,320);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//build draw panel
DrawPanel.setBackground(Color.WHITE);
add(DrawPanel, BorderLayout.CENTER);
DrawPanel.setVisible(true);
//build button panel
ButtonPanel.add(jbtRed);
ButtonPanel.add(jbtGreen);
ButtonPanel.add(jbtBlue);
ButtonPanel.add(jbtErase);
ButtonPanel.add(jbtClear);
add(ButtonPanel, BorderLayout.SOUTH);
ButtonPanel.setVisible(true);
jbtRed.addActionListener(this);
jbtGreen.addActionListener(this);
jbtBlue.addActionListener(this);
jbtErase.addActionListener(this);
jbtClear.addActionListener(this);
DrawPanel.addMouseMotionListener(this);
DrawPanel.addMouseListener(this);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == jbtRed){
DrawPanel.setToolTipText("Color set to 'Red'");
select = 1;
}
if(e.getSource() == jbtGreen){
DrawPanel.setToolTipText("Color set to 'Green'");
}
if(e.getSource() == jbtBlue){
DrawPanel.setToolTipText("Color set to 'Blue'");
}
if(e.getSource() == jbtErase){
DrawPanel.setToolTipText("Erase Selected");
}
if(e.getSource() == jbtClear){
DrawPanel.setToolTipText("Drawing cleared");
}
}
#Override
public void mouseDragged(MouseEvent e) {
x = e.getX();
y = e.getY();
DrawPanel.repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
}
#Override
public void mouseReleased(MouseEvent e) {
x2 = e.getX();
y2 = e.getY();
DrawPanel.repaint();
}
}
class PaintPanel extends JPanel
{
JPaint p;
PaintPanel(JPaint in){
p=in;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// clear the screen
g.setColor(Color.white);
g.setColor(Color.RED);
g.drawLine(p.x, p.y, p.x2, p.y2);
p.x2 = p.x;
p.y2 = p.y;
}
}
class Run_JPaint {
public static void main(String[] args){
JPaint P = new JPaint();
P.setVisible(true);
}
}
You would probably want to remove the following line of code:
super.paintComponent(g);
from inside your PaintPanel class. Otherwise with each draw command your GUI resets the screen.
Good Luck!

implementing grid view with in a horizontal scroll(view flipper)

i want to implement a horizontal slide to my grid view so that one slide displays 9 images and next slide displays the other 9 images and so on. The images here are took from sd card. can any one help out please..!!
after a trying for a long time i got the right code as
package flipper.view;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
public class NewflipperActivity extends Activity implements OnClickListener,OnTouchListener{
ViewFlipper flip;
Animation animFlipInForeward;
Animation animFlipOutForeward;
Animation animFlipInBackward;
Animation animFlipOutBackward;
int filepos=0;
int y;
private GestureDetector gestureDetector;
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
RelativeLayout rl1,rl2;
TextView tv1,tv2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Display dip=getWindowManager().getDefaultDisplay();
int width=dip.getWidth();
int actualheight=dip.getHeight();
System.out.println("width is--->"+width);
System.out.println("height is--->"+actualheight);
int layoutheight=(actualheight)/8;
int flipheight=6*layoutheight;
RelativeLayout.LayoutParams params1=new RelativeLayout.LayoutParams(width,layoutheight-30);
params1.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
tv1=(TextView)findViewById(R.id.textView1);
tv1.setLayoutParams(params1);
RelativeLayout.LayoutParams params2=new RelativeLayout.LayoutParams(width,layoutheight-30);
params2.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
tv2=(TextView)findViewById(R.id.textView2);
tv2.setLayoutParams(params2);
gestureDetector = new GestureDetector(new MyGestureDetector());
flip=(ViewFlipper)findViewById(R.id.viewFlipper1);
flip.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
return false;
}
return true;
}
});
LinearLayout mylay=(LinearLayout)findViewById(R.id.linearlay);
LinearLayout.LayoutParams layparam=new LinearLayout.LayoutParams(width,flipheight);
mylay.setLayoutParams(layparam);
animFlipInForeward = AnimationUtils.loadAnimation(this, R.anim.flipin);
animFlipOutForeward = AnimationUtils.loadAnimation(this, R.anim.flipout);
animFlipInBackward = AnimationUtils.loadAnimation(this, R.anim.flipin_reverse);
animFlipOutBackward = AnimationUtils.loadAnimation(this, R.anim.flipout_reverse);
String folderpath=Environment.getExternalStorageDirectory()+"/New Folder/";
File filepath=new File(folderpath);
File[] mylist=filepath.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
// TODO Auto-generated method stub
return (filename.toLowerCase().endsWith(".jpg")||filename.toLowerCase().endsWith(".png")||filename.toLowerCase().endsWith(".jpeg"));
}
});
Arrays.sort(mylist);
int folderlength=mylist.length;
int mylength=folderlength/9;
if(folderlength%9==0)
{
y=mylength;
}
else
{
y=(mylength)+1;
}
for(int i=0;i<y;i++)
{System.out.println("abc"+i);
TableLayout mtable=new TableLayout(this);
TableLayout.LayoutParams myparams=new TableLayout.LayoutParams(width,flipheight);
mtable.setLayoutParams(myparams);
mtable.setWeightSum(3);
mtable.setOnTouchListener(NewflipperActivity.this);
for(int j=0;j<3;j++)
{
TableRow mrow=new TableRow(this);
mrow.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
mrow.setOnTouchListener(NewflipperActivity.this);
for(int k=0;k<3;k++)
{
if(filepos<folderlength)
{
Log.i("displaying","image at file pos"+mylist[filepos]);
final ImageView imageView = new ImageView(this);
Bitmap imgBitmap,b1;
try
{
if(mylist[filepos].length()>1500){
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inSampleSize = 4;
imgBitmap = BitmapFactory.decodeFile(mylist[filepos] + "",bounds);
b1=Bitmap.createScaledBitmap(imgBitmap, ((int)(width/3))-20, ((int)(flipheight/3))-20, true);
}
else
{
imgBitmap=BitmapFactory.decodeFile(mylist[filepos] + "");
b1=Bitmap.createScaledBitmap(imgBitmap, ((int)(width/3))-20,((int)(flipheight/3))-20, true);
}
imageView.setImageBitmap(b1);
imageView.setAdjustViewBounds(true);
imageView.setPadding(10,10,10,10);
imageView.setTag(mylist[filepos]+"");
imageView.setOnTouchListener(NewflipperActivity.this);
imageView.setOnClickListener(NewflipperActivity.this);
// final String imagename=mylist[filepos].getName();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
mrow.addView(imageView);
filepos++;
}
}
mtable.addView(mrow);
}
flip.addView(mtable);
}
}
private void SwipeRight(){
flip.setInAnimation(animFlipInBackward);
flip.setOutAnimation(animFlipOutBackward);
flip.showPrevious();
}
private void SwipeLeft(){
flip.setInAnimation(animFlipInForeward);
flip.setOutAnimation(animFlipOutForeward);
flip.showNext();
}
class MyGestureDetector extends SimpleOnGestureListener {
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
// right to left swipe
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(NewflipperActivity.this, "Left Swipe", Toast.LENGTH_SHORT).show();
SwipeLeft();
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(NewflipperActivity.this, "Right Swipe", Toast.LENGTH_SHORT).show();
SwipeRight();
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
#Override
public boolean onDown(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ImageView imagename1 = (ImageView)v;
String imgName = (String) imagename1.getTag();
Toast.makeText(NewflipperActivity.this, "clicked on image-->"+imgName, Toast.LENGTH_SHORT).show();
Log.e("displaying","clicked onimage::::::"+imgName);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if (gestureDetector.onTouchEvent(event)) {
return true;
}
return false;
}
}

Resources