Question by James: How to open Java applet in browser instead of new window on Macbook?
Hey

Sometimes when I use Java things online, instead of the java running in the browser window, it opens a new window called ‘Java Applet’. This has happened in both safari and google chrome. I was wondering how I could run it in the window. Java is enabled.

Best answer:

Answer by Alice
yes.

What do you think? Answer below!

Question by Steven: In Java: How can I make a Timer based repaint, instead repaint as fast as the processor can handle?
I have a Timer, which repaints every 30 milliseconds. It runs a simulation, and I want it to run the simulation as fast as possible. I know I can make the timer refresh at a quicker rate, however Java cuts off functions that did not complete in time. So i would simply like to run it at capacity.

Best answer:

Answer by Jared
repaint means you’re doing an animation, you should run an animation without some sort of a timer.

I would suggest using Threads. Here’s a basic animation thread

public class MyPanel extends JPanel implements Runnable{

//the only method you need for runnable
public void run(){
while(true){
repaint();
try{
Thread.sleep(sleepTime);
}
}
}

}

So you define sleepTime in milliseconds. So if you want 30 frames per second, then you do:

1000 / 30 ~ 33 milliseconds

If you don’t want ANY sleep time (which is what you described), then just take out the sleep, i.e. just have a loop that calls repaint() without waiting on anything.

If you’re running some sort of simulation (like say gravity or something), then you should separate the panel from the simulation.

Basically, you should have another class for .the simulation (which also implements runnable and looks like an animation). The class should hold the position and shape (if applicable) of all of its members.

Then pass this simulation object into the animation panel, then during repaint (paintComponent(Graphics g) really), just paint the objects based on where they are now.

So you should have 2 threads, one running the animation and one running the simulation, this will, theoretically, run concurrently. Then you can make the simulation faster by either lowering the sleep time or eliminating it altogether, but your animation should never be more than around 60 frames per second.

What do you think? Answer below!