How to delay between drawings in a Java Applet - java

I'm writing a program to input a number and draw that number of circles of random color and location on an applet. I've been up all night trying to figure out how to add a delay between each of the circles appearing. Right now if I have a for-each statement with a delay in it, and say I input 20 circles and have a delay of 1000, it won't do anything for 20 seconds, then all the circles will appear at once, because the screen doesn't get refreshed until the end of the paint() method.
The only other alternative I could think of was to have a for-each statement in the start() method that would add a color and coordinate to an array, and have the paint() method draw all the circles in this array. I could be wrong, but I would imagine that this would use up way too much memory.
Another possibility would be to just add a circle on to the existing frame without clearing it, but I couldn't find a way to do this.

Use a javax.swing.Timer to add a new Circle object to an expandable list such as an ArrayList. Call repaint() after each addition. In paintComponent(Graphics) draw every Circle in the list.
Update
Unfortunately I cannot add comments at the moment (see External JS failed to load for the gory details). For that reason, I'm adding this as an edit.
#mKorbel: No I sure have not tried it on 1.6.0_26! If I'd tried it at all, I'd have posted the code. ;)
#Tycho: I did not notice you added the awt tag and presumed you were working with Swing.
Are you really using AWT? (If so.) Why?
#Tycho: "The only thing I could tell by quickly searching was that Swing is used more for user interfaces, which is not what I'm going for here."
Umm.. both AWT and Swing (using Applet/JApplet or Frame/JFrame) are used for developing Graphical User Interfaces. Or to put that another way, whether using AWT or Swing, or developing an applet or free-floating frame, you are developing a (G)UI.
Either the applet extends java.applet.Applet (AWT) or javax.swing.JApplet (Swing).
If your applet extends Applet, change it to a Swing JApplet. Few GUI developers can even remember AWT well enough to give good advice on it. My advice was all related to JApplet/Swing. It would not work using AWT.

Use a timer. For example, when you start drawing your circles, set a value:
time_press = System.currentTimeMillis();
circles_to_draw = 20;
Then somewhere in your draw method, do the following:
while(circles_to_draw > 0 && System.currentTimeMillis() < time_press + 1000)
{
time_press += 1000;
circles_to_draw --;
//Draw your circle
}

Related

Issue with flickering in Java 2D Video Game

I am writing a Java 2D video game. I am using only the Java 2D api, and all updates are driven off a single update timer. I perform all the drawing in a JPanel utilizing paintComponent(), and I use Volatile Images for all of the graphics images from what I have read should be a performance increase.
In spite of all this, at times my video game starts flickering like crazy. The whole screen starts flashing. The game is written in Java 6, and I am running on Mac OS X 10.10.1.
Any ideas on how to fix this?
Thanks.
According this post you shouldn't call paintComponent() directly. Try calling paint() instead.
Edit: Sorry, I confused paintComponent() and paintComponents(). Maybe you could show some code?
Call setDoubleBuffered(true) on your main window/frame/panel. Or draw to another component and switch when ready.
The flickering occurs because you quickly redraw on the same component. Redrawing in the background, and then quickly switch to the now newly drawn picture gets rid of this. This is called double buffering. Read more here.

How to add another circle in java coding

so today I'm was making a program and as i'm still a beginner I'm still learning but i'd like to know how to add another circle, for instance I have two units, Red and Blue, I have added the randomize which randomly selects the x and y position, but when I click start it only shows one circle which is red, the blue one is not even there, I know i have not done some coding, but here's my program, please help thanks :)
so yh :) thanks in advance.
A few things to change here:
Drop all AWT components (Canvas, Panel, etc...) and replace them with their equivalent Swing one (JPanel, JTextField...). This will avoid rendering issues and bring double buffering (without any code to perform).
Don't ever use c.getGraphics().
Override paintComponent(Graphics g) and use the Graphics g parameter provided there (see also this link for some example)
To perform "animation" use a javax.swing.Timer. All updates to the UI must be done on the EDT (Event Dispatching Thread). Read also about concurrency in Swing
When using JOptionPane.showMessageDialog (or any other dialog), provide a valid parent component and not null. This will allow proper parenting of windows (avoiding dialogs to be hidden by other frames).

Java: Holding the cursor in an area

For those of you who have played Madness Interactive, one of the most frustrating things is when the cursor leaves the game area, and you accidentally click. This causes the game to defocus and your character dies in a matter of seconds. To fix this, I'd like to make a java application that I can run in the background that will hold the cursor inside the screen until I press a key, like ESC or something.
I see two ways of implementing this, but I don't know if either of them are workable.
Make an AWT frame that matches the size of Madness Interactive's render area, and control the cursor using that.
Use some out-of-context operating system calls to keep the cursor in a given area.
Advantage of approach #1: Much easier to implement resizing of the frame so that user can see the shape and position of the enclosed area.
Potential Problems with approach #1: The AWT Frame would likely need to steal focus from the browser window the game is running in, making the whole solution pointless.
My question is, are either of these approaches viable? If not, is there a viable option?
EDIT: I am willing to use another programming language if necessary.
EDIT2: I might develop a browser plugin for this, but I've never done that kind of development before. I'll research it.
If you're still interested in working in Java, here's a possible solution for you.
First, in order to limit the cursor within an area, you could use the Java Robot class.
mouseMove(int x, int y);
Then, you could use AWT's MouseInfo to get the position of the mouse cursor.
PointerInfo mouseInfo = MouseInfo.getPointerInfo();
Point point = mouseInfo.getLocation();
int x = (int) point.getX();
int y = (int) point.getY();
Then, whenever the x and y value of the mouse cursor go beyond a certain point, move them back using the Java Robot class.
If this is for a browser-based game, consider writing a greasemonkey script, which acts as a browser extension that can be filtered to only run on the game's site.
In the simplest case, assume the clickable regions are (0,0) - (300,400), then you can add the following event handler to the page:
$(document).on('click', function(event) {
if (event.pageX > 300 || event.pageY > 400) {
return false;
}
});
You can further refine your script to do the following:
resize the browser to be the perfect size for playing the game
instead of checking the absolute x,y coords of the click, check if it is inside an element of the page that you don't want to receive the click
add custom key bindings to umm.. help you at the game
write a javascript bot that can play the game itself

Ways to Draw and Redraw / update just the Content (not the background) components of JPanel?

I am creating a graph plotter that plots (draws) datapoints & lines based on periodically updating data points.
I am using a JPanel inside a JFrame as the drawing canvas.
The JPanel contains the line axis & other info (scales etc) as background. It also contains the updating data points as the content.
I would like to update the content of the JFrame periodically, after the new data is fetched.
The data points fetching part is complete & works fine.
This is my code: http://pastebin.com/SAEjNT1R , http://pastebin.com/WvPTyEfR (The panel class).
Main:
Panel object class:
This the the OraclePinger package (not really required, in case u wanna run) : At pastebin Wdmd3q1t (Connector class), MycAgyu3 (Target class)
Originally by Oracle - modified by me : docs.oracle.com/javase/1.4.2/docs/guide/nio/example/Ping.java
I am just confused with the JPanel drawing part. I would like to be able to draw the background once, then periodically refresh/clear & redraw the contents.
---Say if it's not possible to separate the background & content while refreshing.. that we only can clear all Components in the panel. Can I at least make a call to something like panel.clearAllComponents(); panel.draw(TheBackGround+Content) (repeatedly) from the Main
How can I solve this ?
Thanks
I can't look at links due to work related firewall restrictions but regardless, since you're asking volunteers for free advice, you really should be posting pertinent code here so as to make it as easy as possible for us to help you.
That being said, draw the invariant parts of your graph on a BufferedImage that is shown in the JPanel's paintComponent method, and then draw the changing parts in the JPanel's paintComponent method, possibly by looping through an ArrayList of data points.
If you are using JFreeChart, here's a related example that uses a javax.swing.Timer to pace the animation. Note that JFreeChart updates the entire plot on each increment by design.

Working my way arround repaint() in Java

I'm planning to write a simple spaceshooter. I have read that the repaint() method is only a request, and it doesn't execute every time it's called. I believe I'm noticing the effects of this, as my spaceship tends to lag ever so slightly when I'm moving it. Currently I'm simply drawing my ship in a a JPanel's paintComponent() method, and keep calling repaint() on regular intervals (my panel's also Runnable). Seeing as repaint() may potentially screw me over, I'm trying to find a way to work arround it, however I've ran out of ideas. The code I have so far:
private void renderGraphics() {
if (MyImage == null) {
MyImage = new BufferedImage(getPreferredSize().width,
getPreferredSize().height, BufferedImage.TYPE_INT_RGB);
}
MyGraphics = MyImage.getGraphics();
MyGraphics.setColor(Color.BLACK);
MyGraphics.fillRect(0, 0, getPreferredSize().width, getPreferredSize().height);
MyGraphics.drawImage(ship.getImage(), ship.getCurrentX(), ship.getCurrentY(), null);
}
The idea was to create my own graphics, and then make the JPanel draw it, and keep calling this instead of repaint() in my run() method, however I have no idea how to do that. I'd appriciate any input on the matter.
There are multiple ways to approach this.
The best is probably to use BufferStrategy and draw to that, of which I have included a code snippet that should work for you.
You can take this one step further and abandon Swing altogether, just using Frame/BufferStrategy. There is a fully working example (from which the code snippet was taken and adapted) in my question here:
AWT custom rendering - capture smooth resizes and eliminate resize flicker
Anyway, here is an implementation BufferStrategy that you should be able to just drop in:
// you should be extending JFrame
public void addNotify() {
super.addNotify();
createBufferStrategy(2);
}
private synchronized void render() {
BufferStrategy strategy = getBufferStrategy();
if (strategy==null) return;
sizeChanged = false;
// Render single frame
do {
// The following loop ensures that the contents of the drawing buffer
// are consistent in case the underlying surface was recreated
do {
MyGraphics draw = strategy.getDrawGraphics();
draw.setColor(Color.BLACK);
draw.fillRect(0, 0, getPreferredSize().width, getPreferredSize().height);
draw.drawImage(ship.getImage(), ship.getCurrentX(), ship.getCurrentY(), null);
draw.dispose();
// Repeat the rendering if the drawing buffer contents
// were restored
} while (strategy.contentsRestored());
// Display the buffer
strategy.show();
// Repeat the rendering if the drawing buffer was lost
} while (strategy.contentsLost());
}
any drawing will still be performed in the Swing Thread, so no matter what you try work around, it wont help.
Make sure you are not doing any lengthy calculations in the swing thread, this may be stopping repaint from being executed as soon as it needs to be executed
Separate all the logic into 2 parts. Static and Dynamic. (e.g. sea and moving ship. Ship changes shape/location on a static image of sea)
Draw static content in an image once and use the image in your paintComponent(). Call dynamic parts painting after the static image.
Use setClip() to restrict repainting areas.
Calling repaint without any arguments means that the whole panel is repainted.
If you need to repaint parts of the screen (the spaceship has moved to a different location) you should make shure that only those parts of the screen are repainted. The areas that stay the same should not be touched.
Repaint takes coordinates of a rectangle that should be repainted. When moving the ship you should know the old coordinates of the ship and the coordinates the ship should move to.
repaint( oldShipCoordinateX, oldShipCoordinateY, shipWidth, shipLength );
repaint( newShipCoordinateX, newShipCoordinateY, shipWidth, shipLength );
This is usually much faster than calling repaint() without arguments. However you have extra effort to remember the last position of the ship and must be able to calculate the new position of the ship.
See also: http://download.oracle.com/javase/tutorial/uiswing/painting/index.html - especially step 3
Just for code that you post here:
1/ if you want to display Image/ImageIcon, then the best and easiest way is to Use Labels
2/ as you mentioned Runnable{...}.start(); Swing is simple threaded and all output to GUI must be done on EDT; you have to look at Concurrency in Swing, result is that all output from BackGround Task(s) must be wrapped into invokeLater(), and if is there problem with perfomancie then into invokeAndWait()
3/ if you be switch (between JComponents)/add/delete/change Layout then you have to call revalidate() + repaint() as last lines in concrete code block
EDIT:
dirty hack would be paintImmediately()
I have read that the repaint() method is only a request, and it doesn't execute every time it's called
It consolidates multiple repaint() requests into one to be more efficient.
I believe I'm noticing the effects of this, as my spaceship tends to lag ever so slightly when I'm moving it.
Then post your SSCCE that demonstrates this problem. I suspect the problem is your code.
Regarding the solution you accepted, take a look at Charles last posting: Swing/JFrame vs AWT/Frame for rendering outside the EDT comparing Swing vs AWT solutions.

Categories