Clearing graphics
Hi everyone !
I'm using the Java Graphics2D API to create a Game Engine, I know how to draw sprites etc but I have a problem.
To refresh the screen, I'm using graphic buffers ( BufferedImage's ) and I have to clear them before redrawing the screen.
The engine is composed of 5 layers ( drawn one above an other ), so when I clear them I want to keep the alpha property of each one.
The method I wrote is here :
protected final void clear(Graphics2D g)
Composite c = g.getComposite();
g.clearRect(0, 0, Tests.WIDTH, Tests.HEIGHT);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_IN, 1f));
g.setColor(new Color(0, 0, 0, 0));
g.fillRect(0, 0, Tests.WIDTH, Tests.HEIGHT);
g.setComposite(c);
}This is the only way I have found, but it is very slowly for a game engine.
Do you have a better idea to resolve this problem ?
Thanks in advance.
>
Are you using compatible images? If not, using them will probably lead to a nice performance boost, especially if you're blitting lots of BufferedImages to the screen per frame.
BufferedImage img = canvas.getGraphicsConfiguration().createCompatibleImage(int width, int height, int transparency) ;Besides that little bit of advice, I'm still a little confused as to what you're trying to do, so an SSCCE would probably be best.
>
No I wasn't and I'm not using the Canvas class.
Nevertheless I have tried to create an image with the 'getGraphicsConfiguration' method of the JPanel I use to render the game, but a NullPointerException was thrown.
I so wrote a method with GraphicsEnvironement and GraphicsDevice class to get a GraphicsConfiguration and finally create a compatible image but the result
was not very conclusive.
The thing I'm trying to do is just to clear a BufferedImage without losing its alpha property. In fact, my engine ( a tile engine ) wroks with layers.
So if a layer background becomes opaque, the things that are under this layer ( another layer ) would not be visible.
But this method :
>
I'm pretty sure that the code you posted is equivalent to
Composite orig = g.getComposite();
g.setComposite(AlphaComposite.Clear);
g.fillRect(0, 0, Tests.WIDTH, Tests.HEIGHT);
g.setComposite(orig);
This wouldn't require the clearRect(). In fact the code you currently have doesn't require the clearRect(). Also, the CLEAR rule doesn't require any calculations like the SRC_IN rule.
>
made my engine take twice less time to execute for each frame. ( 47ms instead of 94 before )
Thank you
Similar Messages
-
Clearing Graphics and Sprites problem
Thanks to Andrei1 for his help previously. Another problem in the same application. Just having problem clearing sprites and graphics. Commented out the clear statements below. Ends up showing nothing. Do I need to create a separate function for initial and then updated values?? Thanks in advance for any help. Hope the code is not to long.
I think you need to listen to CHANGE event on user input items. Events may be different though:
ComboBox - CHANGE,
InputText - has CHANGE or TextEvent.TEXT_INPUT - depending on your needs
CheckBox and RadioButton dispatch CHANGE event
So the code can be as following:
import flash.display.Sprite;
import flash.geom.Point;
stop();
//Set up global variables
//Set initial selectable Values
rbMonth.selected = true;
rbRisk1.selected = true;
rbYears10.selected = true;
// declare color of graph
var graphColor:uint = 0xCC6600;
//Set variable Group Names
var timeValue:Object = rbMonth.group;
var riskValue:Object = rbRisk1.group;
var yearsValue:Object = rbYears10.group;
var answerCurr:Array = new Array();
// it may array of points
var points:Array = new Array();
var gr:Graphics = this.graphics;
gr.lineStyle(1, graphColor, 0.5);
var i:int = 0;
// no need for enter frame event listeners
//addEventListener(Event.ENTER_FRAME, initSum);
//addEventListener(Event.ENTER_FRAME, drawPoints);
// add change or other corresponding events to UI
num2.addEventListener(Event.CHANGE, drawPoints);
num1.addEventListener(Event.CHANGE, drawPoints);
timeValue.addEventListener(Event.CHANGE, drawPoints);
riskValue.addEventListener(Event.CHANGE, drawPoints);
yearsValue.addEventListener(Event.CHANGE, drawPoints);
// initial settings
initSum();
//Calculate initial set values
function initSum(event:Event = null):void {
var Dinit:Number = num2.value;
var Pinit:Number = num1.value;
var Cinit:Number = (timeValue.selectedData) * Dinit;
var Rinit:Number = riskValue.selectedData;
var Yinit:Number = yearsValue.selectedData;
//Compound Interest P = Starting principal, C = contributions/year, R = interest rate as decimal.
//P(1+R)Y + C[((1+R)Y+1 - (1+R))/R]
//Formula converted intoActionscript = P*(Math.pow((1+R), Y)) + C*(((Math.pow((1+R),Y+1)) - (1+R))/R); break formula into separate parts
var firstPartInit = Pinit * (Math.pow((1 + Rinit), Yinit));
var secondPartInit = Math.pow((1 + Rinit), Yinit + 1).toFixed(2);
var thirdPartInit = 1 + Rinit;
var answerInit = firstPartInit +Cinit * ((secondPartInit - thirdPartInit) / Rinit);
var answerInitFinal = answerInit.toFixed(0);
commaCoderInit(answerInitFinal);
// first call to draw points
drawPoints();
//Format initial end result with commas
function commaCoderInit(yourNum):String {
var numtoString1:String = new String();
for (i = 0; i < yourNum.length; i++) {
if ((yourNum.length-i)%3 == 0 && i != 0) {
numtoString1 += ",";
numtoString1 += yourNum.charAt(i);
return result1_txt.text = numtoString1 + " €";
//Draw Current points on graph
function drawPoints(event:Event = null):void {
var Dcurr:Number = num2.value;
var Pcurr:Number = num1.value;
var Ccurr:Number = (timeValue.selectedData) * Dcurr;
var Rcurr:Number = riskValue.selectedData;
var year:Number = yearsValue.selectedData;
var firstPartCurr:Number;
var secondPartCurr:Number;
var thirdPartCurr:Number;
//Calculate Max value and ratio
var firstPartMax:Number;
var secondPartMax:Number;
var thirdPartMax:Number;
var answerMax:Number;
var ratio:Number;
var firstPartMax:Number;
var secondPartMax:Number;
var thirdPartMax:Number;
var answerMax:Number;
var ratio:Number;
// point sprite
var point:Point;
//Create value loop array
for (i = 0; i <= yearsValue.selectedData; i++) {
firstPartCurr = Pcurr * (Math.pow((1 + Rcurr), i));
secondPartCurr = Math.pow((1 + Rcurr), i + 1).toFixed(2);
thirdPartCurr = 1 + Rcurr;
answerCurr[i] = firstPartCurr + Ccurr * ((secondPartCurr - thirdPartCurr) / Rcurr);
//Calculate Max value and ratio
firstPartMax = Pcurr * (Math.pow((1 + Rcurr), year));
secondPartMax = Math.pow((1 + Rcurr), year + 1).toFixed(2);
thirdPartMax = 1 + Rcurr;
answerMax = firstPartMax + Ccurr * ((secondPartMax - thirdPartMax) / Rcurr);
ratio = (answerMax).toFixed(0) / 250;
// now it is Point - not Sprite
point = new Point(25 + i * (550 / yearsValue.selectedData), 675 - (answerCurr[i] / ratio));
points.push(point);
drawLines();
//Draw initial lines on graph
function drawLines():void {
gr.clear();
gr.moveTo(points[0].x, points[0].y);
for (i = 0; i < points.length; i++) {
gr.beginFill(graphColor);
gr.drawCircle(points[i].x, points[i].y, 3);
gr.endFill();
gr.lineTo(points[i].x, points[i].y); -
I am a beginner on using SWING. I have drawn some graphics(lines,rectangles,etc) in a panel,but I want to clear them,how to achieve?The repaint always paint new graphics...:( Can you help me? Thanks.
Hi!
You can use a global boolean variable (like boolean clear) in the JPanel class where you draw the graphics. Initially this var. is false. In your paintComponent(Graphics g)-method, start with super.paintComponent(g), and then
if (!clear) {
// Do the painting
Then make a method (say clear(boolean clear)), and set this.clear = clear;
repaint();
When you call clear(true), the graphics you've painted, will disappear! -
Graphics returning null in one place, but not another.
If you want to compile and run my program.... you can get all the files here:
http://s94182144.onlinehome.us/randomstuff/files.zip
(The main classes you'll need to look at are DrawingCanvas, Trig and GraphEngine)
Here's a visual just in case:
http://s94182144.onlinehome.us/randomstuff/graph.jpg
When I click the "Graph It" button, I'm sending all those variables in the window to another class. Except the method I need to call is passed Graphics g... and thus, I needed to create a graphics variable. But it's returning null.
Here is my code in GraphEngine, which runs when a button is clicked. You'll notice for Graph It... I created a Graphics variable... this returns null. Except you'll also notice I do the same thing for "Clear"... but this works.
NOTE: I was getting mad so I named some methods not so nicely :p .... you may notice they are different in my files.
public void actionPerformed(ActionEvent e)
userDisplay=e.getActionCommand();
if(userDisplay.equals("Draw"))
String progChoice=grapher.graphType.getSelectedItem();
System.out.println(progChoice);
if(progChoice.equals("Lines"))
grapher.allButtons[0].enable();
draw();
else if(progChoice.equals("Scatter Plot"))
lineOfBestFit();
else if(userDisplay.equals("Graph It"))
Trig.graphThisStuff();
Graphics g = canvas.getGraphics();
canvas.trig(g);
else if(userDisplay.equals("Clear"))
Graphics g = canvas.getGraphics();
System.out.println(g);
canvas.clear(g);
else if(userDisplay.equals("Reset"))
Trig.restartThis();
else if(userDisplay.equals("Credits"))
showInstructionsFrame();
else if(userDisplay.equals("Help"))
showHelpFrame();
else if(userDisplay.equals("Create Sinusodial Graph"))
showTrigFrame();1. Do you expect forum members to download and unzip your code? Good luck...
2. Inside almost every "big" problem is a small one trying to get out. Write a minimal program
demonstrating your problem (say <50 lines) and post that. The shorter code and the easier it
is to copy, paste and run, the more forum members will actually give it a go.
That being said, you problem is that you are using Component's getGraphics at all. Don't use it.
It doesn't work very well -- they rendering you do is temporary, if you iconify and restore your
window your changes will disappear (sometimes even moving another window past yours will do this!).
What should you do instead? Put all your rendering code in paintComponent (or subroutines
it calls). Changes in state of your app should trigger a call to repaint (or you will call it directly).
Repainting will eventually cause your paintComponent to be called. -
When I import an image, whether it's an illustrator,
photoshop, jpg, or gif file, the quality of the image is poor. The
text can't be read. How do I get a clear graphic image imported
into Flash without losing the quality of the text in the image? If
I make the image larger, the text looks good. But if make the image
smaller (which is what I need to do for this project) the text
becomes unreadable.
Any thoughts?Yes, I believe I am importing a file into the flash
aurthoring environment although I am not entirely sure as I am new
to flash. I am working with a previously created flash file and the
graphics that where used in it needed corrections. When I import
the corrected graphic/image (image/graphic was created in
Illustrator) I lose the quality of the text that was used in that
graphic/image especially when it is scaled to a smaller size. I
have tried bringing the image into photoshop and resizing, also, I
have tried to bring in the image in as a .gif and a .jpeg files and
still the quality of the text is poor. I am uncertian if I am doing
something wrong with I resize the image. I have tried resizing it
in Illustrator, and Photoshop. If I don't resize the image and
bring it in as it's actual image size, the quality of the text does
not get lost and is readable. -
MONITOR MADNESS - Is it Leopard ? My graphics card perhaps ? HELP
Friends,
I am going nuts ( no don't answer that one ! ).
Recently ( possibly after the 10.5.2 graphics update - I can't exactly recall ) my LG flat screen monitor has started to look like a grainy 60's acid art house experiment !!
It is subtle but most disconcerting as I use my beloved G5 every day with Logic P8.
I have tried changing settings - calibration the lot... but still it looks strangely weird - like a TV that is not quite tuned in.
Gradients and shaded areas have weird lines instead of fine tones and artifacts appear around type and lines where was once beautiful and clear graphics.
When I first bought the LG 204WT 20" monitor 5 months ago it was fine !.
I have been using the recommended DVI output and tried different cables and the alternative input - the effect is still there but not quite as bad when using connector to RGB input.
The shaded areas in finder and Logic are almost transparent and grainy with a light blue / pink halo like effect around windows and graphic boxes - *I don't know how to explain it really but I do hope someone out there may have some answers or at least have an inkling of what I'm trying to describe..*
As if I couldn't make matters worse I did an archive and install to roll back to 10.5.1 early hours of this morning - this didn;'t cure the problem and I lost the use of some music plug -ins and authorizations in the bargain.. Maybe it is time to call it a day and take a long break.
Really I should get a pen and paper and sit with my guitar an a darkened room for a few days.
I called the Mac shop where it was purchased then LG but with no help, advice or offers to replace it.
I guess the monitor basically works but this strange behaviour is arguably quite subtle and may not be considered 'serious' by most people !
*In the meantime if any of you lovely people could take my situation seriously and offer any practical advise I would be most appreciative.*
Many thanks - not quite lost it yet - PaulHello,
Perhaps my problem is related?
Today, I installed Leopard 10.5.2 on a LaCie Quadra FW disk with my G5 2x2.3, 4.5 GB RAM, GeForce 6600 graphics card with one Samsung 18" and one LaCie 20" monitor. This combination (less the FW disk) has worked (and works) perfectly with Tiger.
Also, directly after installing, both monitors showed what's expected.
However, after restarting (also restaring after updating from 10.5.0 to 10.5.2) the image on both monitors is scrambled in vertical bands!
After learning how to get hold of the Monitors settings panel, just by a fluke I decided to checkmark 'Screen Doubling' (equivalent; sorry, running a Swedish System), which made the scrambled stripes go away. Then, when unchecking Screen Doubling again, everything was back to normal.
After restarting again, the problem was back, and had to be dealt with as above...
I'd really appreciate some feedback from anyone with a similar experience.
Switching back to trusty old Tiger, everything is normal as ususal, so there's apparently no hardware problem involved.
Best regards,
Joey -
Uploading an image dynamically into Flash
I'd upload an image choosen by the client, but I want to wrap it in a movieclip in order to manipulate its size and color with color transform. How can I do it? (AS3 in Flash 10)
My code:
import flash.display.SimpleButton;
import flash.net.FileReference;
import flash.net.FileFilter;
import flash.events.IOErrorEvent;
import flash.events.Event;
import flash.utils.ByteArray;
import flash.display.*;
import flash.geom.*;
var loadFileRef:FileReference;
const FILE_TYPES:Array = [new FileFilter("Image Files", "*.jpg;*.jpeg;*.gif;*.png;*.JPG;*.JPEG;*.GIF;*.PNG")];
function loadFile(event:MouseEvent):void {
loadFileRef = new FileReference();
loadFileRef.addEventListener(Event.SELECT, onFileSelect);
loadFileRef.browse();
function onFileSelect(e:Event):void {
loadFileRef.addEventListener(Event.COMPLETE, onFileLoadComplete);
loadFileRef.load();
function onFileLoadComplete(e:Event):void {
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onDataLoadComplete);
loader.loadBytes(loadFileRef.data);
loadFileRef = null;
function onDataLoadComplete(e:Event):void {
var bitmapData:BitmapData = Bitmap(e.target.content).bitmapData;
if((bitmapData.height)<=(bitmapData.width))
var r:Number = bitmapData.height/bitmapData.width;
var ra:Number = 500*r;
var matrix:Matrix = new Matrix();
matrix.scale(500/bitmapData.width, ra/bitmapData.height);
graphics.clear();
graphics.lineStyle(1, 0x000000);
graphics.beginBitmapFill(bitmapData, matrix, false);
graphics.drawRect(0, 0, 500, ra);
graphics.endFill();
} else {
var d:Number = bitmapData.width/bitmapData.height;
var da:Number = 500*d;
var matrix2:Matrix = new Matrix();
matrix2.scale(500/bitmapData.width, da/bitmapData.height);
graphics.clear();
graphics.lineStyle(1, 0x000000);
graphics.beginBitmapFill(bitmapData, matrix2, false);
graphics.drawRect(0,50, 500, da);
graphics.endFill();
boton.addEventListener(MouseEvent.CLICK, loadFile);
Any help will be very appreciated. Madrid.If you see the code, I draw a rectangle in order to enclose the bitmapData as a fill. I made it in flex adding the rectangle to a canvas with ID, and then applied the transformations and zooming to the canvas itself successfully. But my client wants some other issues that only can be made in Flash, and I have to transfer the whole code to Flash, For instance, look at both codes and you will grasp what I'm trying to say:
1) Flex:
imageView.graphics.clear(); // "imageView" is the canvas id.imageView.graphics.beginBitmapFill(bitmapData, matrix,false);imageView.graphics.drawRect(0, 0, 500, ra);
imageView.graphics.endFill();
2) Flash:
graphics.clear(); // you see? There is NOT an instance name. How can I manipulate THIS?
graphics.lineStyle(1, 0x000000);
graphics.beginBitmapFill(bitmapData, matrix, false);
graphics.drawRect(0, 0, 500, ra);
graphics.endFill();
Thanks a lot for your patience. Madrid. -
After upgrading to Lion 10.7.2, some web-pages stopped loading
Hi folks!
Maybe someone knows what is wrong with my Mac or with this Lion 10.7.2..
To connect to internet, I need to go through university autorisation (browser redirects me to authorization page automaticaly).
It worked without any problems on Mac OS Lion 10.7.1, but after upgrading to 10.7.2 browsers refuse to redirecte me to autorization page.
So, there is some kind of connection and I am able to surf within university web-site, but in order to surf Internet, I need fill out my username and password on autorization page, but I can't get there.
After downgrading to Mac OS Lion 10.7.1, everything returns working again..
I have Mac Book Pro, I7...
Does someone know what problem is? (I'd want to use 10.7.2 and all the benefits of iCloud...)
Thank you.olegz,
First, thanks for the clear graphics.
Authorization seems to be the hangup here. But instead of dealing with the complications of conflicts in authorization, which might take several weeks to months to iron out - site by site - I urge you to follow a different path.
It looks like you're using Chrome. For this site alone, use either Safari or Firefox, both of which are more likely to have plugins to deal with authorizing your site. Safari is already on your computer, but v.3 of Firefox is stable, too. Frankly, I can't tell you what specifically might be the problem here; but switching browsers will solve the immediate problem.
Sound good? Not so good? Post in this thread so that I or others can solve your problem once and for all! -
How do I add custom style to custom AS3 component via .css file?
Hi all,
I have created a flex application which displays a custom component I created in actionscript. My custom component is just an extended canvas component which displays a gradient background. When I add the component to my flex app, see code below, the component works great.
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:ns1="http://localhost/mycomps">
<ns1:GradientCanvas fillColors="[#ffffff, #000000]" />
</mx:Application>
However, I also want to support css styles to add the gradient colors to my component, like so
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:ns1="http://localhost/mycomps">
<mx:Style source="test.css" />
<ns1:GradientCanvas styleName="gradientCanvas" />
</mx:Application>
test.css
.gradientCanvas {
fill-colors: #ffffff, #000000;
When I try this my component doesn't display a gradient. I have followed the tutorials online that I could find but it seems to be the same example from Adobe repeated on multiple site and it doesn't work.
My component code is added below, if anyone could show me how to get this to work it would be much appreciated.
Thanks in advance,
Xander
GradientCanvas.as
package mycomps {
import flash.display.GradientType;
import flash.geom.Matrix;
import mx.containers.Canvas;
import mx.styles.CSSStyleDeclaration;
import mx.styles.StyleManager;
public class GradientCanvas extends Canvas {
private static var classConstructed:Boolean = constructStyle();
public function GradientCanvas() {
super();
this.width = 100;
this.height = 20;
private static function constructStyle():Boolean {
var style:CSSStyleDeclaration = StyleManager.getStyleDeclaration("GradientCanvas");
if (style) {
if (style.getStyle("fill-colors") == undefined) {
style.setStyle("fill-colors", [0xffffff, 0x000000]);
} else {
style = new CSSStyleDeclaration();
style.defaultFactory = function():void {
this._fillColours = [0xffffff, 0x000000];
StyleManager.setStyleDeclaration("GradientCanvas", style, true);
return true;
override public function styleChanged(styleProp:String):void {
super.styleChanged(styleProp);
if (styleProp == "fill-colors") {
this._fillColours = getStyle("fill-colors");
this._fillColoursChanged = true;
this.invalidateDisplayList();
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
super.updateDisplayList(unscaledWidth, unscaledHeight);
if (this._fillColoursChanged == true) {
var direction:Number = 90 * (Math.PI / 180);
var matrix:Matrix = new Matrix();
matrix.createGradientBox(unscaledWidth, unscaledHeight, direction, 0, 0);
graphics.clear();
graphics.beginGradientFill(GradientType.LINEAR, this._fillColours, [1,1], [0, 255], matrix, "pad", "rgb", -1);
graphics.drawRect(0, 0, unscaledWidth, unscaledHeight);
graphics.endFill();
this._fillColoursChanged = false;
[Inspectable(category="Gradient", type="Array", format="Color", name="Fill Colours")]
private var _fillColours:Array;
private var _fillColoursChanged:Boolean = false;
public function get fillColours():Array {
return this._fillColours;
public function set fillColours(value:Array):void {
this._fillColours = value;
this._fillColoursChanged = true;
this.invalidateProperties();
this.invalidateDisplayList();Never mind, I've discovered how to do it for myself.
Thanks... -
Hello :) My friend is doing his thesis & he's stuck with this program. Unfortunately I don't have Java installed on this comp (in work) so I'm not much use but I was hoping someone here could point him in the right direction. Here goes...
Description: Basic paddle ball type game.
This example midlet demonstrates how to use threads and the Canvas class. It implements
a simple paddle ball type game. It demonstrates how to use a clipping region to implement
graphics more effeciently.
It should animate at a constant speed on all phones, although it may appear
jerky on devices with very restricted processing resources.
@created den 21 mars 2002
COPYRIGHT All rights reserved Sony Ericsson Mobile Communications AB 2003.
The software is the copyrighted work of Sony Ericsson Mobile Communications AB.
The use of the software is subject to the terms of the end-user license
agreement which accompanies or is included with the software. The software is
provided "as is" and Sony Ericsson specifically disclaim any warranty or
condition whatsoever regarding merchantability or fitness for a specific
purpose, title or non-infringement. No warranty of any kind is made in
relation to the condition, suitability, availability, accuracy, reliability,
merchantability and/or non-infringement of the software provided herein.
package midp.demo;
import java.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
* Basic Ball and Paddle game. Use arrow keys to move paddle.
* Demonstrates multi-threading, animation, event handling.
* @see MIDlet
public class PaddleBall extends MIDlet implements CommandListener {
* Constant for white color
private static final int COLOR_WHITE = 0xFFFFFF;
* Constant for black color
private static final int COLOR_BLACK = 0x000000;
* The game speed (in milliseconds)
private final int GAME_SPEED = 5;
* The main game screen
private GameFrame mainFrame;
* The title screen
private Form titleScreen;
* The results screen
private Form statsScreen;
* The number of milliseconds the user has been playing this game
private long elapsedTime;
* The ball object for this game
private Ball myBall;
* The paddle object for this game
private Paddle myPaddle;
* True if game has not started or player lost
private boolean gameOver = true;
* How many games have been played
private int numGames;
* Reference to Display
private Display myDisplay;
public PaddleBall() {
myDisplay = Display.getDisplay(this);
* Create main game screen
mainFrame = new GameFrame();
* Create title screen
titleScreen = new Form("Paddle Ball");
titleScreen.append(new StringItem(null,
"The classic arcade game, now on your mobile device!"));
titleScreen.setCommandListener(this);
titleScreen.addCommand(new Command("START", Command.OK, 1));
* Create results screen
statsScreen = new Form("Results");
statsScreen.setCommandListener(PaddleBall.this);
statsScreen.addCommand(new Command("AGAIN?", Command.OK, 1));
* Begin the application, show its frame
protected void startApp() {
myDisplay.setCurrent(titleScreen);
* Application is being terminated, kill threads
protected void pauseApp() {
gameOver = true;
myBall = null;
myPaddle = null;
* Clean up application
protected void destroyApp(boolean unconditional) {
gameOver = true;
* Start the game
public void commandAction(Command c, Displayable d) {
* Create ball and paddle threads
myBall = new Ball();
myPaddle = new Paddle();
* Get the starting time
elapsedTime = System.currentTimeMillis();
* Set the initial ball and paddle positions
myBall.setUp();
myPaddle.setUp();
* Set the screen
myDisplay.setCurrent(mainFrame);
* Start the thread
gameOver = false;
myBall.start();
myPaddle.start();
* The main Screen for this game
class GameFrame extends Canvas {
* Canvas receives all key events
public void keyPressed(int keyCode) {
int gameAction = 0;
try {
gameAction = getGameAction(keyCode);
} catch (Exception e) {
if (gameAction == LEFT) {
myPaddle.move(-2 * GAME_SPEED);
} else if (gameAction == RIGHT) {
myPaddle.move(2 * GAME_SPEED);
return;
* Clear the game screen
private void clear(Graphics g) {
g.setColor(0xFFFFFF);
g.fillRect(0, 0, getWidth(), getHeight());
* Paint the game screen
public void paint(Graphics g) {
synchronized (g) {
* Clear the screen
clear(g);
g.setColor(0x000000);
* Paint the ball and paddle
g.fillRect(myPaddle.x, myPaddle.y, myPaddle.WIDTH,
myPaddle.HEIGHT);
g.fillArc(myBall.x, myBall.y, myBall.SIZE,
myBall.SIZE, 0, 360);
* The ball thread
class Ball extends Thread {
* The ball diameter
public final int SIZE = mainFrame.getHeight() / 15;
* The sign of the x component of the velocity
private int xDir = 1;
* The sign of the y component of the velocity
private int yDir = 1;
* X position of ball
int x;
* Y position of ball
int y;
* Create a ball
public Ball() {
setUp();
* Set starting position
void setUp() {
x = mainFrame.getWidth() / 2;
y = mainFrame.getHeight() / 10;
* Loop to run thread, loops until game over
public void run() {
while (!gameOver) {
* Sleep for animation delay
try {
Thread.sleep(150 - 10 * GAME_SPEED);
} catch (Exception e) {
return;
int oldX = x;
int oldY = y;
* Recalculate x position
int xPos = x + xDir * GAME_SPEED;
if (((xPos+SIZE) <= mainFrame.getWidth())
&& (xPos >= 0)) {
x = xPos;
} else {
xDir *= -1;
AlertType.WARNING.playSound(myDisplay);
* Recalculate y position
int yPos = y + yDir * GAME_SPEED;
if ((yPos >= 0) &&
((yPos + SIZE) <=
(mainFrame.getHeight() - myPaddle.HEIGHT))) {
y = yPos;
} else if ((yPos + SIZE) >
(mainFrame.getHeight() - myPaddle.HEIGHT)) {
* Bounce off paddle
if ((xPos <= (myPaddle.x + myPaddle.WIDTH))
&& ((xPos + SIZE) >= myPaddle.x)) {
yDir *= -1;
AlertType.INFO.playSound(myDisplay);
* Player loses
} else {
gameOver = true;
* Get statistic information
elapsedTime = System.currentTimeMillis()
- elapsedTime;
numGames++;
statsScreen.append(new StringItem("Game " +
numGames + " over", "Time: " +
(elapsedTime/1000) + " seconds"));
* Show the statistics screen
myDisplay.setCurrent(statsScreen);
return;
} else if (yPos < 0) {
yDir *= -1;
AlertType.WARNING.playSound(myDisplay);
mainFrame.repaint(Math.min(oldX, x), Math.min(oldY, y),
Math.abs(x-oldX) + SIZE,
Math.abs(y-oldY) + SIZE);
* The game paddle thread
class Paddle extends Thread {
* Paddle width
public final int WIDTH = mainFrame.getWidth() / 6;
* Paddle height
public final int HEIGHT = mainFrame.getHeight() / 15;
* X position
int x;
* Y position
int y;
* Create a new paddle
public Paddle() {
setUp();
* Initialize starting position
void setUp() {
x = mainFrame.getWidth() / 2 - WIDTH / 2;
y = mainFrame.getHeight() - HEIGHT;
* Loop to run paddlethread, loops until game over
public void run() {
while (!gameOver) {
try {
Thread.sleep(10);
} catch (Exception e) {
return;
* Move paddle right/left
void move(int delta) {
int oldX = x;
int xPos = x + delta;
if (((xPos + WIDTH) <= mainFrame.getWidth())
&& (xPos >= 0)) {
x = xPos;
mainFrame.repaint(Math.min(oldX, x), y,
Math.abs(x-oldX) + WIDTH, HEIGHT);
}Let me do you a favor. With this, even you don't have JDK installed, you can help your friend.
PaddleBall.java:4: package javax.microedition.lcdui does not exist
import javax.microedition.lcdui.*;
^
PaddleBall.java:5: package javax.microedition.midlet does not exist
import javax.microedition.midlet.*;
^
PaddleBall.java:13: cannot resolve symbol
symbol : class MIDlet
location: class midp.demo.PaddleBall
public class PaddleBall extends MIDlet implements CommandListener {
^
PaddleBall.java:13: cannot resolve symbol
symbol : class CommandListener
location: class midp.demo.PaddleBall
public class PaddleBall extends MIDlet implements CommandListener {
^
PaddleBall.java:165: cannot resolve symbol
symbol : class Canvas
location: class midp.demo.PaddleBall.GameFrame
class GameFrame extends Canvas {
^
PaddleBall.java:191: cannot resolve symbol
symbol : class Graphics
location: class midp.demo.PaddleBall.GameFrame
private void clear(Graphics g) {
^
PaddleBall.java:200: cannot resolve symbol
symbol : class Graphics
location: class midp.demo.PaddleBall.GameFrame
public void paint(Graphics g) {
^
PaddleBall.java:38: cannot resolve symbol
symbol : class Form
location: class midp.demo.PaddleBall
private Form titleScreen;
^
PaddleBall.java:43: cannot resolve symbol
symbol : class Form
location: class midp.demo.PaddleBall
private Form statsScreen;
^
PaddleBall.java:73: cannot resolve symbol
symbol : class Display
location: class midp.demo.PaddleBall
private Display myDisplay;
^
PaddleBall.java:130: cannot resolve symbol
symbol : class Command
location: class midp.demo.PaddleBall
public void commandAction(Command c, Displayable d) {
^
PaddleBall.java:130: cannot resolve symbol
symbol : class Displayable
location: class midp.demo.PaddleBall
public void commandAction(Command c, Displayable d) {
^
PaddleBall.java:77: cannot resolve symbol
symbol : variable Display
location: class midp.demo.PaddleBall
myDisplay = Display.getDisplay(this);
^
PaddleBall.java:87: cannot resolve symbol
symbol : class Form
location: class midp.demo.PaddleBall
titleScreen = new Form("Paddle Ball");
^
PaddleBall.java:88: cannot resolve symbol
symbol : class StringItem
location: class midp.demo.PaddleBall
titleScreen.append(new StringItem(null,
^
PaddleBall.java:91: cannot resolve symbol
symbol : class Command
location: class midp.demo.PaddleBall
titleScreen.addCommand(new Command("START", Command.OK, 1));
^
PaddleBall.java:91: cannot resolve symbol
symbol : variable Command
location: class midp.demo.PaddleBall
titleScreen.addCommand(new Command("START", Command.OK, 1));
^
PaddleBall.java:96: cannot resolve symbol
symbol : class Form
location: class midp.demo.PaddleBall
statsScreen = new Form("Results");
^
PaddleBall.java:98: cannot resolve symbol
symbol : class Command
location: class midp.demo.PaddleBall
statsScreen.addCommand(new Command("AGAIN?", Command.OK, 1));
^
PaddleBall.java:98: cannot resolve symbol
symbol : variable Command
location: class midp.demo.PaddleBall
statsScreen.addCommand(new Command("AGAIN?", Command.OK, 1));
^
PaddleBall.java:175: cannot resolve symbol
symbol : method getGameAction (int)
location: class midp.demo.PaddleBall.GameFrame
gameAction = getGameAction(keyCode);
^
PaddleBall.java:179: cannot resolve symbol
symbol : variable LEFT
location: class midp.demo.PaddleBall.GameFrame
if (gameAction == LEFT) {
^
PaddleBall.java:182: cannot resolve symbol
symbol : variable RIGHT
location: class midp.demo.PaddleBall.GameFrame
} else if (gameAction == RIGHT) {
^
PaddleBall.java:194: cannot resolve symbol
symbol : method getWidth ()
location: class midp.demo.PaddleBall.GameFrame
g.fillRect(0, 0, getWidth(), getHeight());
^
PaddleBall.java:194: cannot resolve symbol
symbol : method getHeight ()
location: class midp.demo.PaddleBall.GameFrame
g.fillRect(0, 0, getWidth(), getHeight());
^
PaddleBall.java:362: cannot resolve symbol
symbol : method getWidth ()
location: class midp.demo.PaddleBall.GameFrame
public final int WIDTH = mainFrame.getWidth() / 6;
^
PaddleBall.java:367: cannot resolve symbol
symbol : method getHeight ()
location: class midp.demo.PaddleBall.GameFrame
public final int HEIGHT = mainFrame.getHeight() / 15;
^
PaddleBall.java:229: cannot resolve symbol
symbol : method getHeight ()
location: class midp.demo.PaddleBall.GameFrame
public final int SIZE = mainFrame.getHeight() / 15;
^
PaddleBall.java:264: cannot resolve symbol
symbol : method getWidth ()
location: class midp.demo.PaddleBall.GameFrame
x = mainFrame.getWidth() / 2;
^
PaddleBall.java:265: cannot resolve symbol
symbol : method getHeight ()
location: class midp.demo.PaddleBall.GameFrame
y = mainFrame.getHeight() / 10;
^
PaddleBall.java:291: cannot resolve symbol
symbol : method getWidth ()
location: class midp.demo.PaddleBall.GameFrame
if (((xPos+SIZE) <= mainFrame.getWidth())
^
PaddleBall.java:297: package AlertType does not exist
AlertType.WARNING.playSound(myDisplay);
^
PaddleBall.java:306: cannot resolve symbol
symbol : method getHeight ()
location: class midp.demo.PaddleBall.GameFrame
(mainFrame.getHeight() - myPaddle.HEIGHT))) {
^
PaddleBall.java:310: cannot resolve symbol
symbol : method getHeight ()
location: class midp.demo.PaddleBall.GameFrame
(mainFrame.getHeight() - myPaddle.HEIGHT)) {
^
PaddleBall.java:318: package AlertType does not exist
AlertType.INFO.playSound(myDisplay);
^
PaddleBall.java:332: cannot resolve symbol
symbol : class StringItem
location: class midp.demo.PaddleBall.Ball
statsScreen.append(new StringItem("Game " +
^
PaddleBall.java:345: package AlertType does not exist
AlertType.WARNING.playSound(myDisplay);
^
PaddleBall.java:347: cannot resolve symbol
symbol : method repaint (int,int,int,int)
location: class midp.demo.PaddleBall.GameFrame
mainFrame.repaint(Math.min(oldX, x), Math.min(oldY, y),
^
PaddleBall.java:391: cannot resolve symbol
symbol : method getWidth ()
location: class midp.demo.PaddleBall.GameFrame
x = mainFrame.getWidth() / 2 - WIDTH / 2;
^
PaddleBall.java:392: cannot resolve symbol
symbol : method getHeight ()
location: class midp.demo.PaddleBall.GameFrame
y = mainFrame.getHeight() - HEIGHT;
^
PaddleBall.java:417: cannot resolve symbol
symbol : method getWidth ()
location: class midp.demo.PaddleBall.GameFrame
if (((xPos + WIDTH) <= mainFrame.getWidth())
^
PaddleBall.java:421: cannot resolve symbol
symbol : method repaint (int,int,int,int)
location: class midp.demo.PaddleBall.GameFrame
mainFrame.repaint(Math.min(oldX, x), y,
^
42 errors -
Please take a look? (Pong)
Hello :) My friend is doing his thesis & he's stuck with this program. Apparently it's not compiling. Unfortunately I don't have Java installed on this comp (in work) so I'm not much use but I was hoping someone here could point him in the right direction. Here goes...
Description: Basic paddle ball type game.
This example midlet demonstrates how to use threads and the Canvas class. It implements
a simple paddle ball type game. It demonstrates how to use a clipping region to implement
graphics more effeciently.
It should animate at a constant speed on all phones, although it may appear
jerky on devices with very restricted processing resources.
@created den 21 mars 2002
COPYRIGHT All rights reserved Sony Ericsson Mobile Communications AB 2003.
The software is the copyrighted work of Sony Ericsson Mobile Communications AB.
The use of the software is subject to the terms of the end-user license
agreement which accompanies or is included with the software. The software is
provided "as is" and Sony Ericsson specifically disclaim any warranty or
condition whatsoever regarding merchantability or fitness for a specific
purpose, title or non-infringement. No warranty of any kind is made in
relation to the condition, suitability, availability, accuracy, reliability,
merchantability and/or non-infringement of the software provided herein.
package midp.demo;
import java.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
* Basic Ball and Paddle game. Use arrow keys to move paddle.
* Demonstrates multi-threading, animation, event handling.
* @see MIDlet
public class PaddleBall extends MIDlet implements CommandListener {
* Constant for white color
private static final int COLOR_WHITE = 0xFFFFFF;
* Constant for black color
private static final int COLOR_BLACK = 0x000000;
* The game speed (in milliseconds)
private final int GAME_SPEED = 5;
* The main game screen
private GameFrame mainFrame;
* The title screen
private Form titleScreen;
* The results screen
private Form statsScreen;
* The number of milliseconds the user has been playing this game
private long elapsedTime;
* The ball object for this game
private Ball myBall;
* The paddle object for this game
private Paddle myPaddle;
* True if game has not started or player lost
private boolean gameOver = true;
* How many games have been played
private int numGames;
* Reference to Display
private Display myDisplay;
public PaddleBall() {
myDisplay = Display.getDisplay(this);
* Create main game screen
mainFrame = new GameFrame();
* Create title screen
titleScreen = new Form("Paddle Ball");
titleScreen.append(new StringItem(null,
"The classic arcade game, now on your mobile device!"));
titleScreen.setCommandListener(this);
titleScreen.addCommand(new Command("START", Command.OK, 1));
* Create results screen
statsScreen = new Form("Results");
statsScreen.setCommandListener(PaddleBall.this);
statsScreen.addCommand(new Command("AGAIN?", Command.OK, 1));
* Begin the application, show its frame
protected void startApp() {
myDisplay.setCurrent(titleScreen);
* Application is being terminated, kill threads
protected void pauseApp() {
gameOver = true;
myBall = null;
myPaddle = null;
* Clean up application
protected void destroyApp(boolean unconditional) {
gameOver = true;
* Start the game
public void commandAction(Command c, Displayable d) {
* Create ball and paddle threads
myBall = new Ball();
myPaddle = new Paddle();
* Get the starting time
elapsedTime = System.currentTimeMillis();
* Set the initial ball and paddle positions
myBall.setUp();
myPaddle.setUp();
* Set the screen
myDisplay.setCurrent(mainFrame);
* Start the thread
gameOver = false;
myBall.start();
myPaddle.start();
* The main Screen for this game
class GameFrame extends Canvas {
* Canvas receives all key events
public void keyPressed(int keyCode) {
int gameAction = 0;
try {
gameAction = getGameAction(keyCode);
} catch (Exception e) {
if (gameAction == LEFT) {
myPaddle.move(-2 * GAME_SPEED);
} else if (gameAction == RIGHT) {
myPaddle.move(2 * GAME_SPEED);
return;
* Clear the game screen
private void clear(Graphics g) {
g.setColor(0xFFFFFF);
g.fillRect(0, 0, getWidth(), getHeight());
* Paint the game screen
public void paint(Graphics g) {
synchronized (g) {
* Clear the screen
clear(g);
g.setColor(0x000000);
* Paint the ball and paddle
g.fillRect(myPaddle.x, myPaddle.y, myPaddle.WIDTH,
myPaddle.HEIGHT);
g.fillArc(myBall.x, myBall.y, myBall.SIZE,
myBall.SIZE, 0, 360);
* The ball thread
class Ball extends Thread {
* The ball diameter
public final int SIZE = mainFrame.getHeight() / 15;
* The sign of the x component of the velocity
private int xDir = 1;
* The sign of the y component of the velocity
private int yDir = 1;
* X position of ball
int x;
* Y position of ball
int y;
* Create a ball
public Ball() {
setUp();
* Set starting position
void setUp() {
x = mainFrame.getWidth() / 2;
y = mainFrame.getHeight() / 10;
* Loop to run thread, loops until game over
public void run() {
while (!gameOver) {
* Sleep for animation delay
try {
Thread.sleep(150 - 10 * GAME_SPEED);
} catch (Exception e) {
return;
int oldX = x;
int oldY = y;
* Recalculate x position
int xPos = x + xDir * GAME_SPEED;
if (((xPos+SIZE) <= mainFrame.getWidth())
&& (xPos >= 0)) {
x = xPos;
} else {
xDir *= -1;
AlertType.WARNING.playSound(myDisplay);
* Recalculate y position
int yPos = y + yDir * GAME_SPEED;
if ((yPos >= 0) &&
((yPos + SIZE) <=
(mainFrame.getHeight() - myPaddle.HEIGHT))) {
y = yPos;
} else if ((yPos + SIZE) >
(mainFrame.getHeight() - myPaddle.HEIGHT)) {
* Bounce off paddle
if ((xPos <= (myPaddle.x + myPaddle.WIDTH))
&& ((xPos + SIZE) >= myPaddle.x)) {
yDir *= -1;
AlertType.INFO.playSound(myDisplay);
* Player loses
} else {
gameOver = true;
* Get statistic information
elapsedTime = System.currentTimeMillis()
- elapsedTime;
numGames++;
statsScreen.append(new StringItem("Game " +
numGames + " over", "Time: " +
(elapsedTime/1000) + " seconds"));
* Show the statistics screen
myDisplay.setCurrent(statsScreen);
return;
} else if (yPos < 0) {
yDir *= -1;
AlertType.WARNING.playSound(myDisplay);
mainFrame.repaint(Math.min(oldX, x), Math.min(oldY, y),
Math.abs(x-oldX) + SIZE,
Math.abs(y-oldY) + SIZE);
* The game paddle thread
class Paddle extends Thread {
* Paddle width
public final int WIDTH = mainFrame.getWidth() / 6;
* Paddle height
public final int HEIGHT = mainFrame.getHeight() / 15;
* X position
int x;
* Y position
int y;
* Create a new paddle
public Paddle() {
setUp();
* Initialize starting position
void setUp() {
x = mainFrame.getWidth() / 2 - WIDTH / 2;
y = mainFrame.getHeight() - HEIGHT;
* Loop to run paddlethread, loops until game over
public void run() {
while (!gameOver) {
try {
Thread.sleep(10);
} catch (Exception e) {
return;
* Move paddle right/left
void move(int delta) {
int oldX = x;
int xPos = x + delta;
if (((xPos + WIDTH) <= mainFrame.getWidth())
&& (xPos >= 0)) {
x = xPos;
mainFrame.repaint(Math.min(oldX, x), y,
Math.abs(x-oldX) + WIDTH, HEIGHT);
}Cross-post
http://forum.java.sun.com/thread.jspa?threadID=5160243&tstart=0 -
MONITOR SCREEN PROBLEMS - has anyone else had this ? HELP ..
Friends,
I am going nuts ( no don't answer that one ! ).
Recently ( possibly after the 10.5.2 graphics update - I can't exactly recall ) my LG flat screen monitor has started to look like a grainy 60's acid art house experiment !!
It is subtle but most disconcerting as I use my beloved G5 every day with Logic P8.
I have tried changing settings - calibration the lot... but still it looks strangely weird - like a TV that is not quite tuned in.
Gradients and shaded areas have weird lines instead of fine tones and artifacts appear around type and lines where was once beautiful and clear graphics.
When I first bought the LG 204WT 20" monitor 5 months ago it was fine !.
I have been using the recommended DVI output and tried different cables and the alternative input - the effect is still there but not quite as bad when using connector to RGB input.
The shaded areas in finder and Logic are almost transparent and grainy with a light blue / pink halo like effect around windows and graphic boxes.
I *don't know how to explain it really but I do hope someone out there may have some answers or at least have an inkling of what I'm trying to describe..*
As if I couldn't make matters worse I did an archive and install to roll back to 10.5.1 early hours of this morning - this didn;'t cure the problem and I lost the use of some music plug -ins and authorizations in the bargain.. Maybe it is time to call it a day and take a long break.
Really I should get a pen and paper and sit with my guitar an a darkened room for a few days.
I called the Mac shop where it was purchased then LG but with no help, advice or offers to replace it.
I guess the monitor basically works but this strange behaviour is arguably quite subtle and may not be considered 'serious' by most people !
*In the meantime if any of you lovely people could take my situation seriously and offer any practical advise I would be most appreciative.*
Many thanks - not quite lost it yet - PaulHi Pancenter,
Many thanks for taking time to message.
The resoloution is set as it should be and millions of colours is selected etc.
The screen has had several contrast / brightness adjustments and a factory reset with no improvement.
Also someone suggested the screen zoom might be on but this is all set as normal.
I have an imac which works fine and the difference is quite noticable - on the G5 w/ LG screen there are light blue and pink 'halo's ' around gray areas, graphics have strange patchy dots like a screen print and as I am looking and typing into this forum the gradient shaded area that says 'Apple Discussions' has very poor quality shading with horizontal blue lines !
I've also tested the cables and made sure there are no interferences - this is really weird...
I will try another monitor when I get chance - thanks again.
Paul -
Fit the image to window width, window height and the window size
hi all
here we wrote the code for "fit the image to window width, window height and the window size". we are facing some problems in it. and all these operations have to perform even after zooming operations are done.if the below code doesnt satisfy kindly provide appropriate code .
thanks .
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.io.File;
import javax.swing.filechooser.FileFilter;
import java.awt.geom.*;
public class DP extends JFrame implements ActionListener,
MouseListener,
MouseMotionListener {
private final int PEN_OP = 1;
private final int CLEAR_OP = 2;
private int radius;
private int radius1;
private int mousex = 0;
private int mousey = 0;
private int prevx = 0;
private int prevy = 0;
private boolean initialFreeHand = true;
private boolean initialLine = true;
private boolean initialEraser = true;
private int Orx = 0;
private int Ory = 0;
private int OrWidth = 0;
private int OrHeight = 0;
private int drawX = 0;
private int drawY = 0;
private int polyX = 0;
private int polyY = 0;
private int eraserLength = 5;
private int udefRedValue = 255;
private int udefGreenValue = 255;
private int udefBlueValue = 255;
private int opStatus = PEN_OP;
private int colorStatus = 1;
private double zoomPercentage=10;
private Color mainColor = new Color(0, 0, 0);
private Color xorColor = new Color(255, 255, 255);
private Color userDefinedColor =
new Color(udefRedValue, udefGreenValue,udefBlueValue);
private JButton openButton = new JButton("open");
private JButton closeButton = new JButton("close");
private JButton zoominButton = new JButton("ZoomIn");
private JButton zoomoutButton = new JButton("ZoomOut");
private JButton zoomto100Button = new JButton("ZoomTo100");
private JButton fwwButton = new JButton("Fit window width");
private JButton fwhButton = new JButton("Fit window height");
private JButton fwButton = new JButton("Fit the window");
private JButton clearButton = new JButton("Clear");
private JTextField colorStatusBar = new JTextField(20);
private JTextField opStatusBar = new JTextField(20);
private JTextField mouseStatusBar = new JTextField(10);
private JPanel controlPanel = new JPanel(new GridLayout(18, 1, 0, 0));
JToolBar jToolbar = new JToolBar();
private Container container;
private JScrollBar horizantalSlide=new JScrollBar();
public BufferedImage image;
BufferedImage bgImage;
// public ImageIcon icon=null;
JFileChooser fileChooser;
DrawPanel drawPanel = new DrawPanel(bgImage,zoomPercentage);
public DP() {
super("WhiteBoard");
fileChooser = new JFileChooser(".");
container = getContentPane();
container.setBackground(Color.white);
container.setLayout(new BorderLayout());
container.add(jToolbar,BorderLayout.NORTH);
container.add(horizantalSlide);
jToolbar.add(openButton);
jToolbar.add(closeButton);
jToolbar.add(zoominButton);
jToolbar.add(zoomoutButton);
jToolbar.add(zoomto100Button);
jToolbar.add(fwwButton);
jToolbar.add(fwhButton);
jToolbar.add(fwButton);
jToolbar.add(clearButton);
colorStatusBar.setEditable(false);
opStatusBar.setEditable(false);
mouseStatusBar.setEditable(false);
controlPanel.setBackground(Color.white);
drawPanel.setBackground(Color.white);
container.add(controlPanel, "West");
container.add(drawPanel, "Center");
openButton.addActionListener(this);
closeButton.addActionListener(this);
zoominButton.addActionListener(this);
zoomoutButton.addActionListener(this);
zoomto100Button.addActionListener(this);
fwwButton.addActionListener(this);
fwhButton.addActionListener(this);
fwButton.addActionListener(this);
clearButton.addActionListener(this);
drawPanel.addMouseMotionListener(this);
drawPanel.addMouseListener(this);
addMouseListener(this);
addMouseMotionListener(this);
opStatusBar.setText("FreeHand");
colorStatusBar.setText("Black");
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("open"))
showDialog();
if(e.getActionCommand().equals("close"))
closeDialog();
if(e.getActionCommand().equals("ZoomIn"))
drawPanel.zoom(1);
if(e.getActionCommand().equals("ZoomOut"))
drawPanel.zoom(-1);
if(e.getActionCommand().equals("ZoomTo100"))
drawPanel.zoom(+10);
if(e.getActionCommand().equals("Fit window width"))
drawPanel.fitwindowwidth();
if(e.getActionCommand().equals("Fit window height"))
drawPanel.fitwindowheight();
if(e.getActionCommand().equals("Fit the window"))
drawPanel.fitthewindow();
if (e.getActionCommand() == "Clear")
opStatus = CLEAR_OP;
switch (opStatus) {
case CLEAR_OP:
clearPanel();
private void showDialog() {
if(fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
bgImage = ImageIO.read(file);
} catch(IOException e) {
System.out.println("IO error: " + e.getMessage());
clearPanel();
private void closeDialog() {
drawPanel.setVisible(false);
drawPanel.repaint();
public void clearPanel() {
opStatusBar.setText("Clear");
Graphics g = image.getGraphics();
g.setColor(drawPanel.getBackground());
g.fillRect(0, 0, drawPanel.getBounds().width, drawPanel.getBounds().height);
if(bgImage != null)
g.drawImage(bgImage, 0, 0, this);
g.dispose();
drawPanel.repaint();
public boolean mouseHasMoved(MouseEvent e) {
return (mousex != e.getX() || mousey != e.getY());
public void setActualBoundry() {
if (mousex < Orx || mousey < Ory) {
if (mousex < Orx) {
OrWidth = Orx - mousex;
drawX = Orx - OrWidth;
} else {
drawX = Orx;
OrWidth = mousex - Orx;
if (mousey < Ory) {
OrHeight = Ory - mousey;
drawY = Ory - OrHeight;
} else {
drawY = Ory;
OrHeight = mousey - Ory;
} else {
drawX = Orx;
drawY = Ory;
OrWidth = mousex - Orx;
OrHeight = mousey - Ory;
public void setGraphicalDefaults(MouseEvent e) {
mousex = e.getX();
mousey = e.getY();
prevx = e.getX();
prevy = e.getY();
Orx = e.getX();
Ory = e.getY();
drawX = e.getX();
drawY = e.getY();
OrWidth = 0;
OrHeight = 0;
public void mouseDragged(MouseEvent e) {
updateMouseCoordinates(e);
switch (opStatus) {}
public void mouseReleased(MouseEvent e) {
updateMouseCoordinates(e);
switch (opStatus) {}
public void mouseEntered(MouseEvent e) {
updateMouseCoordinates(e);
public void updateMouseCoordinates(MouseEvent e) {
String xCoor = "";
String yCoor = "";
if (e.getX() < 0)
xCoor = "0";
else {
xCoor = String.valueOf(e.getX());
if (e.getY() < 0)
xCoor = "0";
else {
yCoor = String.valueOf(e.getY());
mouseStatusBar.setText("x:" + xCoor + " y:" + yCoor);
public void mouseClicked(MouseEvent e) { updateMouseCoordinates(e); }
public void mouseExited(MouseEvent e) { updateMouseCoordinates(e); }
public void mouseMoved(MouseEvent e) { updateMouseCoordinates(e); }
public void mousePressed(MouseEvent e) { updateMouseCoordinates(e); }
public static void main(String[] args) {
DP wb = new DP();
wb.setDefaultCloseOperation(EXIT_ON_CLOSE);
wb.setSize(1024,740);
wb.setVisible(true);
private class DrawPanel extends JPanel {
private double m_zoom = 1.0;
private double m_zoomPercentage;
private BufferedImage m_image;
double theta = 0;
double thetaInc = Math.PI/2;
public DrawPanel(BufferedImage imageb,double zoomPercentage) {
m_image = imageb;
m_zoomPercentage = zoomPercentage / 100;
protected void paintComponent(Graphics g) {
Graphics2D g2d=(Graphics2D)g;
if(image == null)
initImage();
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
double x = (1.0 - m_zoom)*getWidth()/2.0;
double y = (1.0 - m_zoom)*getHeight()/2.0;
AffineTransform at = AffineTransform.getTranslateInstance(x, y);
at.rotate(theta,m_zoom*getWidth()/2,m_zoom*getHeight()/2);
at.scale(m_zoom, m_zoom);
g2d.drawRenderedImage(image, at);
public void zoom(int inc) {
m_zoom += inc * m_zoomPercentage;
repaint();
public void fitwindowwidth()
int w1=drawPanel.getWidth();
int h1=drawPanel.getHeight();
BufferedImage image2=image.getScaledInstance(w1,h1,Image.SCALE_DEFAULT);
drawPanel.setPreferredSize(new java.awt.Dimension(100,image2.getImage().getHeight(null)));
drawPanel.repaint();
public void fitwindowheight()
BufferedImage image2=image.getScaledInstance(500,680,1);
drawPanel.setImage(iicon);
drawPanel.setPreferredSize(new java.awt.Dimension(100,image2.getImage().getHeight(null)));
drawPanel.repaint();
public void fitthewindow()
BufferedImage image2=image.getScaledInstance(1000,680,1);
drawPanel.setPreferredSize(new java.awt.Dimension(100,image2.getImage().getHeight(null)));
drawPanel.repaint();
private void initImage() {
int w = getWidth();
int h = getHeight();
image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = image.createGraphics();
g2.setPaint(getBackground());
g2.fillRect(0,0,w,h);
g2.dispose();
}thank you for giving reply.
your code is very helpful to us.but i couldn't integrate it in my code.here's my code.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.io.File;
import javax.swing.filechooser.FileFilter;
import java.awt.geom.*;
public class IS extends JFrame implements ActionListener,
MouseListener,
MouseMotionListener {
private final int PEN_OP = 1;
private final int CLEAR_OP = 2;
private final int DISTORT = 3;
private final int SCALE = 4;
private final int FIT = 5;
private final int FILL = 6;
int scaleMode = SCALE;
private int radius;
private int radius1;
private int mousex = 0;
private int mousey = 0;
private int prevx = 0;
private int prevy = 0;
private boolean initialFreeHand = true;
private boolean initialLine = true;
private boolean initialEraser = true;
private int Orx = 0;
private int Ory = 0;
private int OrWidth = 0;
private int OrHeight = 0;
private int drawX = 0;
private int drawY = 0;
private int polyX = 0;
private int polyY = 0;
private int eraserLength = 5;
private int udefRedValue = 255;
private int udefGreenValue = 255;
private int udefBlueValue = 255;
private int opStatus = PEN_OP;
private int colorStatus = 1;
private double zoomPercentage=10;
private Color mainColor = new Color(0, 0, 0);
private Color xorColor = new Color(255, 255, 255);
private Color userDefinedColor =
new Color(udefRedValue, udefGreenValue,udefBlueValue);
private JButton openButton = new JButton("open");
private JButton closeButton = new JButton("close");
private JButton zoominButton = new JButton("ZoomIn");
private JButton zoomoutButton = new JButton("ZoomOut");
private JButton zoomto100Button = new JButton("ZoomTo100");
private JButton fwwButton = new JButton("Fit window width");
private JButton fwhButton = new JButton("Fit window height");
private JButton fwButton = new JButton("Fit the window");
private JButton clearButton = new JButton("Clear");
private JTextField colorStatusBar = new JTextField(20);
private JTextField opStatusBar = new JTextField(20);
private JTextField mouseStatusBar = new JTextField(10);
private JPanel controlPanel = new JPanel(new GridLayout(18, 1, 0, 0));
JToolBar jToolbar = new JToolBar();
private Container container;
private JScrollBar horizantalSlide=new JScrollBar();
public BufferedImage image;
BufferedImage bgImage;
// public ImageIcon icon=null;
JFileChooser fileChooser;
DrawPanel drawPanel = new DrawPanel(bgImage,zoomPercentage);
public IS() {
super("WhiteBoard");
fileChooser = new JFileChooser(".");
container = getContentPane();
container.setBackground(Color.white);
container.setLayout(new BorderLayout());
container.add(jToolbar,BorderLayout.NORTH);
container.add(horizantalSlide);
jToolbar.add(openButton);
jToolbar.add(closeButton);
jToolbar.add(zoominButton);
jToolbar.add(zoomoutButton);
jToolbar.add(zoomto100Button);
jToolbar.add(fwwButton);
jToolbar.add(fwhButton);
jToolbar.add(fwButton);
jToolbar.add(clearButton);
colorStatusBar.setEditable(false);
opStatusBar.setEditable(false);
mouseStatusBar.setEditable(false);
controlPanel.setBackground(Color.white);
drawPanel.setBackground(Color.white);
container.add(controlPanel, "West");
container.add(drawPanel, "Center");
openButton.addActionListener(this);
closeButton.addActionListener(this);
zoominButton.addActionListener(this);
zoomoutButton.addActionListener(this);
zoomto100Button.addActionListener(this);
fwwButton.addActionListener(this);
fwhButton.addActionListener(this);
fwButton.addActionListener(this);
clearButton.addActionListener(this);
drawPanel.addMouseMotionListener(this);
drawPanel.addMouseListener(this);
addMouseListener(this);
addMouseMotionListener(this);
opStatusBar.setText("FreeHand");
colorStatusBar.setText("Black");
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("open"))
showDialog();
if(e.getActionCommand().equals("close"))
closeDialog();
if(e.getActionCommand().equals("ZoomIn"))
drawPanel.zoom(1);
if(e.getActionCommand().equals("ZoomOut"))
drawPanel.zoom(-1);
if(e.getActionCommand().equals("ZoomTo100"))
drawPanel.zoom(+10);
if(e.getActionCommand().equals("Fit window width"))
//drawPanel.fitwindowwidth();
drawPanel.scaleImage(0,0,0,0);
if(e.getActionCommand().equals("Fit window height"))
drawPanel.scaleImage(0,0,0,0);
if(e.getActionCommand().equals("Fit the window"))
drawPanel.scaleImage(0,0,0,0);
if (e.getActionCommand() == "Clear")
opStatus = CLEAR_OP;
switch (opStatus) {
case CLEAR_OP:
clearPanel();
private void showDialog() {
if(fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
bgImage = ImageIO.read(file);
} catch(IOException e) {
System.out.println("IO error: " + e.getMessage());
clearPanel();
private void closeDialog() {
drawPanel.setVisible(false);
drawPanel.repaint();
public void clearPanel() {
opStatusBar.setText("Clear");
int w = image.getWidth();
int h = image.getHeight();
Graphics g = image.getGraphics();
g.setColor(drawPanel.getBackground());
g.fillRect(0, 0, w, h);
if(bgImage != null) {
int x = (w - bgImage.getWidth())/2;
int y = (h - bgImage.getHeight())/2;
g.drawImage(bgImage, x, y, this);
g.dispose();
drawPanel.repaint();
public boolean mouseHasMoved(MouseEvent e) {
return (mousex != e.getX() || mousey != e.getY());
public void setActualBoundry() {
if (mousex < Orx || mousey < Ory) {
if (mousex < Orx) {
OrWidth = Orx - mousex;
drawX = Orx - OrWidth;
} else {
drawX = Orx;
OrWidth = mousex - Orx;
if (mousey < Ory) {
OrHeight = Ory - mousey;
drawY = Ory - OrHeight;
} else {
drawY = Ory;
OrHeight = mousey - Ory;
} else {
drawX = Orx;
drawY = Ory;
OrWidth = mousex - Orx;
OrHeight = mousey - Ory;
public void setGraphicalDefaults(MouseEvent e) {
mousex = e.getX();
mousey = e.getY();
prevx = e.getX();
prevy = e.getY();
Orx = e.getX();
Ory = e.getY();
drawX = e.getX();
drawY = e.getY();
OrWidth = 0;
OrHeight = 0;
public void mouseDragged(MouseEvent e) {
updateMouseCoordinates(e);
switch (opStatus) {
public void mouseReleased(MouseEvent e) {
updateMouseCoordinates(e);
switch (opStatus) {}
public void mouseEntered(MouseEvent e) {
updateMouseCoordinates(e);
public void updateMouseCoordinates(MouseEvent e) {
String xCoor = "";
String yCoor = "";
if (e.getX() < 0)
xCoor = "0";
else {
xCoor = String.valueOf(e.getX());
if (e.getY() < 0)
xCoor = "0";
else {
yCoor = String.valueOf(e.getY());
mouseStatusBar.setText("x:" + xCoor + " y:" + yCoor);
public void mouseClicked(MouseEvent e) { updateMouseCoordinates(e); }
public void mouseExited(MouseEvent e) { updateMouseCoordinates(e); }
public void mouseMoved(MouseEvent e) { updateMouseCoordinates(e); }
public void mousePressed(MouseEvent e) { updateMouseCoordinates(e); }
public static void main(String[] args) {
IS wb = new IS();
wb.setDefaultCloseOperation(EXIT_ON_CLOSE);
wb.setSize(1024,740);
wb.setVisible(true);
private class DrawPanel extends JPanel {
private double m_zoom = 1.0;
private double m_zoomPercentage;
private BufferedImage m_image;
double theta = 0;
double thetaInc = Math.PI/2;
public DrawPanel(BufferedImage imageb,double zoomPercentage) {
m_image = imageb;
m_zoomPercentage = zoomPercentage / 100;
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d=(Graphics2D)g;
if(image == null)
initImage();
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
int w = getWidth();
int h = getHeight();
int iw = image.getWidth();
int ih = image.getHeight();
if(scaleMode == SCALE) {
double x = (w - m_zoom*iw)/2;
double y = (h - m_zoom*ih)/2;
AffineTransform at = AffineTransform.getTranslateInstance(x, y);
at.rotate(theta,m_zoom*getWidth()/2,m_zoom*getHeight()/2);
at.scale(m_zoom, m_zoom);
g2d.drawRenderedImage(image, at);
else {
scaleImage(w, h, iw, ih);
private void scaleImage( int w, int h, int iw, int ih) {
Graphics2D g2d = image.createGraphics();
double xScale = (double)w/iw;
double yScale = (double)h/ih;
AffineTransform at = new AffineTransform();
if(scaleMode == DISTORT) {
double x = (w - xScale*iw)/2;
double y = (h - yScale*ih)/2;
at.setToTranslation(x, y);
at.scale(xScale, yScale);
} else {
double scale = (scaleMode == FIT) ? Math.min(xScale, yScale)
: Math.max(xScale, yScale);
double x = (w - scale*iw)/2;
double y = (h - scale*ih)/2;
at.setToTranslation(x, y);
at.scale(scale, scale);
g2d.drawRenderedImage(image, at);
public void zoom(int inc) {
m_zoom += inc * m_zoomPercentage;
repaint();
private void initImage() {
int w = getWidth();
int h = getHeight();
image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = image.createGraphics();
g2.setPaint(getBackground());
g2.fillRect(0,0,w,h);
g2.dispose();
} -
Am I alone - having lots of problems with 10.7.1. iPhoto is slow and when I export photos it exists iphoto then I restart and sometimes it will works. Safari is slower also. Sometimes it justs hangs and I have to force quit. iTunes is also slower to open. Almost everytime it goes to a checking library for a long time.
Should I go back to previous version? Will I lose my purchase. I do not have disks for the upgrade. I do not want to go back - I have a lot of data and always fear of losing it.
Think Apple knows about the problems or am I the only one and have some other problem?olegz,
First, thanks for the clear graphics.
Authorization seems to be the hangup here. But instead of dealing with the complications of conflicts in authorization, which might take several weeks to months to iron out - site by site - I urge you to follow a different path.
It looks like you're using Chrome. For this site alone, use either Safari or Firefox, both of which are more likely to have plugins to deal with authorizing your site. Safari is already on your computer, but v.3 of Firefox is stable, too. Frankly, I can't tell you what specifically might be the problem here; but switching browsers will solve the immediate problem.
Sound good? Not so good? Post in this thread so that I or others can solve your problem once and for all! -
Flattened circles in drawing api
Hi Guys
When I use the drawing api to create circles, sometimes they
appear flattened, as if the edges had been sliced off. Below is the
code. Can anyone tell me how to fix this?
// extends UIComponent
public function CircleThing ()
super();
mouseChildren = false;
buttonMode = true;
//resetCircle();
base = new Sprite();
baseOver = new Sprite();
label = new TextField()
label.autoSize = TextFieldAutoSize.LEFT;
label.multiline = true;
label.wordWrap = true;
label.width = 108;
label.x = -52;
addChild(base);
addChild(baseOver);
addChild(label);
addEventListeners();
//label.border = true;
//label.borderColor = 0xff0000;
//addChild(label);
//resetCircle();
//addListeners();
// This function creates the blue circle
public function drawCircle(_name:String=null):void
trace ('NavCircle drawCircle');
var myFilters:Array = [new
DropShadowFilter(5,135,0x000000,0.15,5,5)];
//base.name = _name;
base.graphics.clear();
base.graphics.beginFill(_color, .9);
base.graphics.drawCircle(0, 0, defaultDiameter/2);
base.graphics.endFill();
base.filters = myFilters;
// added djg draw overCircle
baseOver.graphics.clear();
baseOver.graphics.beginFill(_overColor, 1);
baseOver.graphics.drawCircle(0, 0, defaultDiameter/2);
baseOver.graphics.endFill();
baseOver.visible = false;
}I'm not sure about tutorials, but read up on the
flash.display.Graphics class. Your Canvas has a graphics property
and that's where you draw. Here's how to draw a red circle 50
pixels in diameter:
graphics.clear();
graphics.beginFill( 0xff0000 );
graphics.drawCircle( 100, 100, 25 );
graphics.endFill();
You should do most of your drawing in the updateDisplayList
function - just override it (in a Script block if using
MXML).
Maybe you are looking for
-
When installing itunes on my windows XP I get an error message "Service Apple Mobile Device"
When installing iTunes on my Windows XP I get an error message "Service Apple Mobile Device (Apple Mobile Device) failed to start. Verify that you have sufficient privileges to start system services". I don't know what this means and I do not know
-
How to read OLE objects from Access ??
Hi, I have an field of type OLE in my Access Database table. This field has some files stored in it in the form of attachment. The file types of the OLE objects can be different (xls,txt,doc). Now, I want to query the database and find the extension
-
URGENT issue with testing movie / publishing
hello, i am creating a presentation for my coworker in flash. let me start by saying i am in no way familiar with this program. i am planning on learning more, but for now my task is specific to this assisgnment. basically i have one large timelin
-
Hi, When i've created a purchase order i fix (inconsciously) the exchange rate and currency. so the purchase order currency and the exchange rate cannot be changed during posting an invoice in MIRO. Please i want to post an invoice in MIRO with a dif
-
Ipad2 sd movie cannot open content not authorized
Downloaded SD movie onto ipad2 and it will not open to play. Get the message Cannot Open: Content not authorized. Using current version of OS, other SD movies in library play fine.