Creating a second applet(window) in processing - java

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 ;)

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.

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();
}
}

Related

How to use the repaint method in Java Swing

I am very new to the Graphics portion of Java. I have created a frame and on it I have added a panel whose color has been set to Green. Now on clicking that panel I want to draw a circle using a test class's object called Mypanel. But it does not happen. Please guide !
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
class Mypanel extends JPanel
{
#Override
public void paintComponent(Graphics g)
{
g.drawOval(15, 15, 5, 5);
}
}
public class algo extends javax.swing.JFrame {
public algo() {
initComponents();
jPanel1.setBackground(Color.GREEN);
}
Mypanel p = new Mypanel() ;
private void jPanel1MouseClicked(java.awt.event.MouseEvent evt) {
p.repaint();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new algo().setVisible(true);
}
});
}
}
If I were to guess I would say that I am not supposed to use the repaint method, but I was told that this was to be used.
That code as supplied would not compile. For better help sooner, post a Minimal, Complete, and Verifiable example or Short, Self Contained, Correct Example.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Mypanel extends JPanel {
boolean clicked = false;
Mypanel() {
setBackground(Color.GREEN);
MouseListener mouseListener = new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
clicked = true;
repaint();
}
};
this.addMouseListener(mouseListener);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 100);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (clicked) {
g.drawOval(15, 15, 50, 50);
}
}
}
public class algo extends JFrame {
public algo() {
initComponents();
pack();
//jPanel1.setBackground(Color.GREEN); ?!?
}
protected final void initComponents() {
add(new Mypanel());
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new algo().setVisible(true);
}
});
}
}
There are a few things to correct in your example...
When you create the frame (i.e. in the constructor) you'll want to call super(). This is the first thing the constructor has to do. Then, you'll probably want to set an initial width/height, and set the background color of the frame green.
You need to add a mouse listener so that the mouseClicked method is actually called. Then have it add the 'MyPanel' object to the frame, and call repaint.
I think that's roughly what you're going for.

How to open multiple windows with Processing?

I'm trying to create two windows with Processing. Before you mark this as a duplicate, as there are other questions similar to this, I have a specific error and I can't find a solution. When I try to add(s) I get the error The method add(Component) in the type Container is not applicable for the arguments (evolution_simulator.SecondApplet)
I'm not sure how to fix this, and any help would be appreciated. Here is the code:
import javax.swing.*;
PFrame f;
void setup() {
size(320, 240);
f = new PFrame();
}
void draw() {
}
public class PFrame extends JFrame {
SecondApplet s;
public PFrame() {
setBounds(100,100,400,300);
s = new SecondApplet();
add(s); // error occurs here
s.init();
show();
}
}
public class SecondApplet extends PApplet {
public void setup() {
size(400, 300);
noLoop();
}
public void draw() {
}
}
The reason for the error message is because the add() function is expecting a Component, and PApplet is not a Component. This is because PApplet no longer extends Applet as of Processing 3, so old code that uses it as a Component will no longer work.
Instead, you can create a class that extends PApplet for your second window, and then call PApplet.runSketch() using that second PApplet as a parameter:
void setup() {
size(100, 100);
String[] args = {"TwoFrameTest"};
SecondApplet sa = new SecondApplet();
PApplet.runSketch(args, sa);
}
void draw() {
background(0);
ellipse(50, 50, 10, 10);
}
public class SecondApplet extends PApplet {
public void settings() {
size(200, 100);
}
public void draw() {
background(255);
fill(0);
ellipse(100, 50, 10, 10);
}
}

How to create Form with background color in j2me [duplicate]

Please have a look at the following code
First, Please note I am a 100% newbie to Java Mobile.
In here, I am making the light on and vibrate on when user click the button. However, I really wanted to create a SOS application which turn the whole screen into white, and go to black, like that, in the thread. I guess I didn't achieve that by this app because even the lights are on, the buttons are still there. I tried to turn the "Form" color to "white" but it seems like JME has no "Color" class.
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class Midlet extends MIDlet{
private Form f;
private Display d;
private Command start,stop;
private Thread t;
public Midlet()
{
t = new Thread(new TurnLightOn());
}
public void startApp()
{
f = new Form("Back Light On");
d = Display.getDisplay(this);
d.setCurrent(f);
start = new Command("Turn On",Command.OK,0);
stop = new Command("Turn Off",Command.OK,1);
f.addCommand(start);
f.setCommandListener(new Action());
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional)
{
this.notifyDestroyed();
}
private class Action implements CommandListener
{
public void commandAction(Command c, Displayable dis)
{
f.append("Light is Turnning On");
t.start();
}
}
private class ActionOff implements CommandListener
{
public void commandAction(Command c, Displayable dis)
{
}
}
private class TurnLightOn implements Runnable
{
public void run()
{
f.append("Working");
for(int i=0;i<100;i++)
{
try
{
d.flashBacklight(200);
d.vibrate(200);
Thread.sleep(1000);
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
}
}
}
Use the javax.microedition.lcdui.Canvas instead of Form. This example can get you started
public void startApp()
{
f = new Form("Back Light On");
d = Display.getDisplay(this);
start = new Command("Turn On",Command.OK,0);
stop = new Command("Turn Off",Command.OK,1);
f.addCommand(start);
f.setCommandListener(new Action());
myCanvas = new MyCanvas();
d.setCurrent(myCanvas);
myCanvas.repaint();
}
Now create a canvas and implement paint method like this:
class MyCanvas extends Canvas {
public void paint(Graphics g) {
// create a 20x20 black square in the center
// clear the screen first
g.setColor(0xffffff);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(0xffffff); // make sure it is white color
// draw the square, <b>changed to rely on instance variables</b>
<b>g.fillRect(x, y, getWidth(), getHeight());</b>
}
}

MouseListener mouseClicked() missing first event

public class TesterApplication {
static JPanel CenterPanel;
public static void main(String[] args){
/* get image MapImg */
JFrame frame=new JFrame();
CenterPanel = new JPanel(){
#Override
protected void paintComponent(Graphics g){
g.drawImage(MapImg, 0, 0, null);
}
};
CenterPanel.addMouseListener(new LineBuildListener(new TesterApplication()));
frame.getContentPane().add(BorderLayout.CENTER, CenterPanel);
frame.setSize(x, y);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
}
now inner class
class LineBuildListener implements MouseListener {
TesterApplication TA;
int xFirstClick;
int yFirstClick;
int ClickCounter=0;
int xClick;
int yClick;
LineBuildListener(TesterApplication TA){
this.TA=TA;
}
#Override
public void mouseClicked(MouseEvent e) {
xFirstClick=xClick;
yFirstClick=yClick;
xClick=e.getX();
yClick=e.getY();
TA.CenterPanel.getGraphics().fillOval(xClick, yClick, 10, 10);
if(ClickCounter!=0){
SecondClick();
ClickCounter++;
}else{
ClickCounter++;
}
System.out.println(ClickCounter);
}
public void SecondClick(){
TA.CenterPanel.getGraphics().drawLine(xClick, yClick, xFirstClick,yFirstClick);
}
}
meanwhile I make first click, my GUI blink, Click Counter print that i have made 1 click, but yet i don't get my first circle. If i keep clicking everything work fine, it prints next circle, increase Counter and draw line between them, so i dont get why first circle is missing
Look at this:
xFirstClick=xClick;
yFirstClick=yClick;
xClick=e.getX();
yClick=e.getY();
xClick and yClick are not initialized the first time

Java transparent window

I am trying to create a circle-shaped window that follows the mouse and pass clicks to the underlying windows.
I was doing this with Python and Qt (see Python overlay window) but then I switched to Java and Swing. However I'm not able to make the window transparent. I tried this method but it doesn't work, however I think that my system supports the transparency because if I start Screencast-O-Matic (which is in Java), the rectangle is actually transparent.
How can I achieve something like that? (I'm on Linux KDE4)
Why did the Java tutorial How to Create Translucent and Shaped Windows fail to work? Are you using the latest version of Java 6 or Java 7?
In the May/June issue of Java Magazine, there was a tutorial on shaped and transparent windows requiring java 7. You will probably need to sign up for Java magazine in order to read it. See if you can get this to run on your system:
import java.awt.*; //Graphics2D, LinearGradientPaint, Point, Window, Window.Type;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
/**
* From JavaMagazine May/June 2012
* #author josh
*/
public class ShapedAboutWindowDemo {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//switch to the right thread
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("About box");
//turn of window decorations
frame.setUndecorated(true);
//turn off the background
frame.setBackground(new Color(0,0,0,0));
frame.setContentPane(new AboutComponent());
frame.pack();
//size the window
frame.setSize(500, 200);
frame.setVisible(true);
//center on screen
frame.setLocationRelativeTo(null);
}
}
);
}
private static class AboutComponent extends JComponent {
public void paintComponent(Graphics graphics) {
Graphics2D g = (Graphics2D) graphics;
//create a translucent gradient
Color[] colors = new Color[]{
new Color(0,0,0,0)
,new Color(0.3f,0.3f,0.3f,1f)
,new Color(0.3f,0.3f,0.3f,1f)
,new Color(0,0,0,0)};
float[] stops = new float[]{0,0.2f,0.8f,1f};
LinearGradientPaint paint = new LinearGradientPaint(
new Point(0,0), new Point(500,0),
stops,colors);
//fill a rect then paint with text
g.setPaint(paint);
g.fillRect(0, 0, 500, 200);
g.setPaint(Color.WHITE);
g.drawString("My Killer App", 200, 100);
}
}
}
If you're using Java 6, you need to make use of the private API AWTUtilities. Check out the Java SE 6 Update 10 API for more details
EXAMPLE
This is a bit of quick hack, but it gets the idea across
public class TransparentWindow {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MyFrame frame = new MyFrame();
frame.setUndecorated(true);
String version = System.getProperty("java.version");
if (version.startsWith("1.7")) {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice graphicsDevice = ge.getDefaultScreenDevice();
System.out.println("Transparent from under Java 7");
/* This won't run under Java 6, uncomment if you are using Java 7
System.out.println("isPerPixelAlphaTranslucent = " + graphicsDevice.isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSLUCENT));
System.out.println("isPerPixelAlphaTransparent = " + graphicsDevice.isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSPARENT));
System.out.println("isPerPixelAlphaTranslucent = " + graphicsDevice.isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency.TRANSLUCENT));
*/
frame.setBackground(new Color(0, 0, 0, 0));
} else if (version.startsWith("1.6")) {
System.out.println("Transparent from under Java 6");
System.out.println("isPerPixelAlphaSupported = " + supportsPerAlphaPixel());
setOpaque(frame, false);
}
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class MyFrame extends JFrame {
public MyFrame() throws HeadlessException {
setContentPane(new MyContentPane());
setDefaultCloseOperation(EXIT_ON_CLOSE);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
dispose();
}
}
});
}
}
public static class MyContentPane extends JPanel {
public MyContentPane() {
setLayout(new GridBagLayout());
add(new JLabel("Hello, I'm a transparent frame under Java " + System.getProperty("java.version")));
setOpaque(false);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.BLUE);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
g2d.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 20, 20);
}
}
public static boolean supportsPerAlphaPixel() {
boolean support = false;
try {
Class<?> awtUtilsClass = Class.forName("com.sun.awt.AWTUtilities");
support = true;
} catch (Exception exp) {
}
return support;
}
public static void setOpaque(Window window, boolean opaque) {
try {
Class<?> awtUtilsClass = Class.forName("com.sun.awt.AWTUtilities");
if (awtUtilsClass != null) {
Method method = awtUtilsClass.getMethod("setWindowOpaque", Window.class, boolean.class);
method.invoke(null, window, opaque);
// com.sun.awt.AWTUtilities.setWindowOpaque(this, opaque);
// ((JComponent) window.getContentPane()).setOpaque(opaque);
}
} catch (Exception exp) {
}
}
public static void setOpacity(Window window, float opacity) {
try {
Class<?> awtUtilsClass = Class.forName("com.sun.awt.AWTUtilities");
if (awtUtilsClass != null) {
Method method = awtUtilsClass.getMethod("setWindowOpacity", Window.class, float.class);
method.invoke(null, window, opacity);
}
} catch (Exception exp) {
exp.printStackTrace();
}
}
public static float getOpacity(Window window) {
float opacity = 1f;
try {
Class<?> awtUtilsClass = Class.forName("com.sun.awt.AWTUtilities");
if (awtUtilsClass != null) {
Method method = awtUtilsClass.getMethod("getWindowOpacity", Window.class);
Object value = method.invoke(null, window);
if (value != null && value instanceof Float) {
opacity = ((Float) value).floatValue();
}
}
} catch (Exception exp) {
exp.printStackTrace();
}
return opacity;
}
}
On Windows 7 it produces
Under Java 6
Under Java 7
i guess this will work,i already tried it..to make a JFrame or a window transparent you need to undecorate Undecorated(true) the frame first. Here is sample code :
import javax.swing.*;
import com.sun.awt.AWTUtilities;
import java.awt.Color;
class transFrame {
private JFrame f=new JFrame();
private JLabel msg=new JLabel("Hello I'm a Transparent Window");
transFrame() {
f.setBounds(400,150,500,500);
f.setLayout(null);
f.setUndecorated(true); // Undecorates the Window
f.setBackground(new Color(0,0,0,25)); // fourth index decides the opacity
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
msg.setBounds(150,250,300,25);
f.add(msg);
f.setVisible(true);
}
public static void main(String[] args) {
new transFrame();
}
}
The only problem is you need to add your own code for close and minimize using buttons.
If you want to do it on your own, without using a external lib, you could start a thread that performs :
set the transparent window invisible
make a Screenshot of the desktop
put this screenshot as background image of your window
Or you could use JavaFX
I was also facing the same problem. After hours of searching, I finally found the problem! These are the lines you must write, if you want to make a transparent JFrame:
public void enableTransparentWindow(float opacity) {
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
f.setLocationRelativeTo(null);
f.setBackground(new Color(0, 0, 0));
//If translucent windows aren't supported, exit.
f.setUndecorated(true);
if (!gd.isWindowTranslucencySupported(TRANSLUCENT)) {
System.err.println(
"Translucency is not supported");
System.exit(0);
}
f.setOpacity(opacity);
}
Don't forget to call the setVisible() method after this code.
Happy Coding!

Categories