I have a simple question, I have created an Applet to display some results:
public class Plot2D extends JApplet {
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.red);
Dimension size = getSize();
Insets insets = getInsets();
int w = size.width - insets.left - insets.right;
int h = size.height - insets.top - insets.bottom;
Random r = new Random();
for (int i = 0; i < 1000; i++) {
int x = Math.abs(r.nextInt()) % w;
int y = Math.abs(r.nextInt()) % h;
g2d.drawLine(x, y, x, y);
}
}
public void main(String[] args) {
JFrame frame = new JFrame("Points");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// Timer timer = new Timer(2000, new ActionListener() {
// @Override
// public void actionPerformed(ActionEvent e) {
frame.add(new Plot2D());
frame.setSize(200, 200);
frame.setResizable(false);
frame.setVisible(true);
// }
// });
// timer.setRepeats(true);
// timer.start();
};
}
Which works fine and displays random points. Now If I call that Applet from another class using:
Plot2D plotting = new Plot2D();
plotting.main(null);
it displays the same figure but the applet doesn't last on screen. How can I enable that? I've tried the timer which doesn't seem to work. Any thoughts around this?
Thank you.
Edit. As an answer to questions about how is that Applet called, here is the class:
public class PedestrianSpawnerTest {
// @Before
// public void initialise(){
// frame = new JFrame("Points");
// }
public void test() {
int numberOfPedestrians = 10;
PedestrianSpawner pedestrianSpawner = new PedestrianSpawner();
pedestrianSpawner.SpawnRandomlyStandardPedestrians(numberOfPedestrians);
List<StandardPedestrian> listOfPedestrians = pedestrianSpawner
.getListOfPedestrians();
for (int i = 0; i < listOfPedestrians.size(); i++) {
System.out.println(listOfPedestrians.get(i).getId());
System.out.println(listOfPedestrians.get(i).getPosition());
System.out.println(listOfPedestrians.get(i).getVelocity());
System.out.println(listOfPedestrians.get(i).getTarget());
}
Plot2D plotting = new Plot2D();
plotting.main(null);
}
}
Edit 2: Ok I've found a sort of hacky trick by adding
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
just after the two lines mentioned above. It seems to work.