Reputation: 49
Hello guys i am trying to do a code where i can create a second applet in processing by passing on a sensible area.
the code works fine except for 1 thing.
when it passes over the sensible area it creates in a loop the same frame.
here is the code.
import javax.swing.JFrame;
PFrame f;
secondApplet s;
void setup() {
size(600, 340);
}
void draw() {
background(255, 0, 0);
fill(255);
}
void mousePressed(){
PFrame f = new PFrame();
}
public class secondApplet extends PApplet {
public void setup() {
size(600, 900);
noLoop();
}
public void draw() {
fill(0);
ellipse(400, 60, 20, 20);
}
}
public class PFrame extends JFrame {
public PFrame() {
setBounds(0, 0, 600, 340);
s = new secondApplet();
add(s);
s.init();
println("birh");
show();
}
}
This code creates the second applet by just clicking in any region of the frame, but if you keep clicking it will create more frames of the same applet.
what i want is that once i click it creates only 1 frame and no more.
can you help me please? thanks ;)
Upvotes: 2
Views: 5117
Reputation: 807
import javax.swing.JFrame;
PFrame f = null;
secondApplet s;
void setup() {
size(600, 340);
}
void draw() {
background(255, 0, 0);
fill(255);
}
void mousePressed(){
if(f==null)f = new PFrame();
}
public class secondApplet extends PApplet {
public void setup() {
size(600, 900);
noLoop();
}
public void draw() {
fill(0);
ellipse(400, 60, 20, 20);
}
/*
* TODO: something like on Close set f to null, this is important if you need to
* open more secondapplet when click on button, and none secondapplet is open.
*/
}
public class PFrame extends JFrame {
public PFrame() {
setBounds(0, 0, 600, 340);
s = new secondApplet();
add(s);
s.init();
println("birh");
show();
}
}
Upvotes: 1
Reputation: 367
The code you posted won't compile, as you have no top-level encapsulating class declared, so I'm curious about why you say it works.
Regarding your issue, you have the field PFrame f
declared at the top, but in mousePressed()
you declare another one. This variable f
is different from the first variable. To solve your problem, you probably want your code to look something like:
void mousePressed() {
if (f == null) {
f = new PFrame();
}
}
This will allow you to create the new frame, but only once. I recommend you choose more descriptive variable names, though. Also, it should be SecondApplet
, not secondApplet
.
Upvotes: 1