We are about to switch to a new forum software. Until then we have removed the registration on this forum.
It sounds like you want an existing file dialog box function that is built in -- like selectInput() or selectFolder() -- so you don't have to program UI for it. You want this thing to load files over the internet. Is that right?
Have you seen something like this before that you are basing your idea off of -- like a browser plugin, or an FTP application? Is your application scraping a public web page, or is it using a protocol like WebDAV or SFTP, or a feed like RSS / XML?
Web-based file interfaces can be really hard. You probably want a simple workaround.
new version
// Editor
// from https : // forum.processing.org/two/discussion/comment/112902/#Comment_112902
// editor path and file extension
final String pathFolder="texts";
final String fileExtension = ".txt";
// editor content
String str = "Test ";
// states of the program:
// unique constants:
final int normal = 0;
final int save = 1;
final int load = 2;
///current state (must be one of them)
int state=normal;
// blinking cursor:
boolean blinkIsOn=true;
// Paths
String savePath="";
String loadPath="";
// ------------------------------------------------
// Core functions of processing
void setup() {
size(900, 900);
}//func
void draw() {
switch (state) {
case normal:
drawForStateNormal() ;
break;
case save:
// wait for Save Dialog
waitForSaveDialog();
break;
case load:
// wait for Load Dialog
waitForLoadDialog();
break;
default:
//Error
println("Fail");
exit();
break;
//
}//switch
}//func
// ------------------------------------------------
void drawForStateNormal() {
background(0);
textSize(14);
// title
fill(255, 2, 2);
text("My little Editor",
width-123, 20, 100, 422);
// show the text the user entered
fill(255);
text(str+blink(),
20, 20, width-170, height-20);
// ----------------------
// buttons
textSize(11);
fill(128);
if ( overSave() ) {
fill(196);
}
rect(width-40, height-20, 40, 20);
fill(255);
text("Save",
width-40+7, height-9+5);
// ---
fill(128);
if ( overLoad() ) {
fill(196);
}
rect(width-40, height-50, 40, 20);
fill(255);
text("Load",
width-40+7, height-50+9+5);
// ---
fill(128);
if ( overNew() ) {
fill(196);
}
rect(width-40, height-80, 40, 20);
fill(255);
text("New",
width-40+7, height-80+9+5);
}
//----------------------------------------------------------------------------
// functions to register if mouse is over buttons
boolean overSave() {
return( mouseX > width-40 &&
mouseY > height-20 );
}
boolean overLoad() {
return( mouseX > width-40 &&
mouseY > height-50 &&
mouseY < height-50+25 );
}
boolean overNew() {
return( mouseX > width-40 &&
mouseY > height-80 &&
mouseY < height-80+25 );
}
// ---------------------------------------------------------------------------
// Inputs
void keyPressed() {
if (state!=normal)
return;
// for the editor:
if ( keyCode == DELETE || keyCode == BACKSPACE ) {
if ( str.length() > 0 ) {
str = str.substring(0, str.length()-1);
}
} else {
if ( key != CODED ) {
str += key;
}
}
}
void mousePressed() {
if (state!=normal)
return;
// for the buttons
if ( overSave() ) {
initSave();
}
//---
else if ( overLoad() ) {
initLoad();
}
//---
else if ( overNew() ) {
str="";
}
//
}//func
// -------------------------------------------------
// Save and load
void initSave() {
// init save process
// reset
savePath="";
// make date time stamp (the expression nf(n,2) means leading zero: 2 becomes 02)
String dateTimeStamp = year()
+ nf(month(), 2)
+ nf(day(), 2)
+ "-"
+ nf(hour(), 2)
+ nf(minute(), 2)
+ nf(second(), 2);
// prepare fileDescription which occurs in the dialogue
File fileDescription = new File( sketchPath()
+ "//"
+ pathFolder
+ "//"
+ dateTimeStamp
+ fileExtension);
// open the dialog
selectOutput("Select a file to write to", "fileSelectedSave", fileDescription);
// set state to wait
state=save;
}
void initLoad() {
// init load process
// reset
loadPath="";
// prepare fileDescription which occurs in the dialogue
File fileDescription = new File( sketchPath()+"//"+pathFolder+"//"+"*" + fileExtension );
// open the dialog
selectInput("Select a file to load", "fileSelectedLoad", fileDescription);
// set state to wait
state=load;
}
void fileSelectedSave(File selection) {
// the 'callback' function
if (selection == null) {
// println("Window was closed or the user hit cancel.");
// go back
state=normal;
} else {
// println("User selected " + selection.getAbsolutePath());
savePath=selection.getAbsolutePath();
}
}
void fileSelectedLoad(File selection) {
// the 'callback' function
if (selection == null) {
// println("Window was closed or the user hit cancel.");
// go back
state=normal;
} else {
// println("User selected " + selection.getAbsolutePath());
loadPath=selection.getAbsolutePath();
}
}
void waitForSaveDialog() {
if (!savePath.equals("")) {
// waiting is over
saveIt();
// go back
state=normal;
}
}
void waitForLoadDialog() {
if (!loadPath.equals("")) {
// waiting is over
loadIt();
// go back
state=normal;
}
}
void saveIt() {
// save
// split at line break and make array (to save it)
String[] strs = split ( str, "\n" );
// check if file extension (fileExtension, e.g. .txt) is there
int len = savePath.length();
if (len<4 || !savePath.substring( len-4 ).equals(fileExtension)) {
// file Extension is not present, we have to add it
savePath += fileExtension; // add the file Extension
}
// save
println("Saved: " + savePath);
saveStrings( savePath, strs );
}
void loadIt() {
// load
String[] strs = loadStrings( loadPath );
str = join(strs, "\n");
}
// -------------------------------------------------
// Misc
String blink() {
// toggle blinkIsOn
if (frameCount%17 == 0)
blinkIsOn=!blinkIsOn;
// depending from blinkIsOn
if (blinkIsOn)
return "|";
else return "";
}
//
String words = "";
String[] wordOutPut;
boolean blinkIsOn=true;
void setup() {
size(750, 1000);
}
void draw() {
background(255);
//Button rectangle
fill(150);
//SaveButton
rect(450, 850, 100, 50);
//LoadButton
rect(570, 850, 100, 50);
//Button text
fill(0);
textSize(20);
textAlign(CENTER, CENTER);
text("Save", width/1.5, 875);
text("Load", width/1.2, 875);
//Written text by user.
textSize(18);
textAlign(LEFT, TOP);
textLeading(20);
//(If you want to change where the text should be change this section (295, 340, 140, 200) = (X,Y,Height,Width) musch like a rect.
text(words+blink(), 295, 340, 140, 200);
}
//Makes it possible to write into the program
void keyPressed() {
if ( keyCode == DELETE || keyCode == BACKSPACE ) {
if ( words.length() > 0 ) {
words = words.substring(0, words.length()-1);
}
} else {
if ( key != CODED ) {
words += key;
}
}
}
//Start and Load buttons clicable // (Note the SAVE button also clears the text, if you want it to not save just remove the words = ""; from the first if statement)
void mouseClicked() {
if (mouseX > 450 && mouseX < 550 && mouseY > 850 && mouseY < 900) {
String date = "Location" + "-" + day() + "-" + minute() + "-" + second() + ".txt";
saveStrings(date, new String[]{words});
words = "";
}
if (mouseX > 570 && mouseX < 670 && mouseY > 850 && mouseY < 900) {
selectInput("Select a file to load", "fileSelected");
}
}
//Loads the string into the program
void fileSelected(File selection) {
wordOutPut = loadStrings(selection.getAbsolutePath());
loadStrings(selection.getAbsolutePath());
words = join(wordOutPut, "\n");
}
//Blinking line |
String blink() {
// toggle blinkIsOn
if (frameCount%30 == 0)
blinkIsOn=!blinkIsOn;
// depending from blinkIsOn
if (blinkIsOn)
return "|";
else return "";
}
String str = "Test 17";
// state of the program :
//constants, unique:
final int normal = 0;
final int save = 1;
final int load = 2;
///current state
int state=normal;
boolean blinkIsOn=true;
String savePath="";
String loadPath="";
// ------------------------------------------------
// Core functions of processing
void setup() {
size(900, 900);
}//func
void draw() {
switch (state) {
case normal:
drawForStateNormal() ;
break;
case save:
// wait
if (!savePath.equals("")) {
// waiting is over
saveIt();
// go back
state=normal;
}
break;
case load:
// wait
if (!loadPath.equals("")) {
// waiting is over
loadIt();
// go back
state=normal;
}
break;
default:
//Error
println("Fail");
exit();
break;
//
}//switch
}//func
// ------------------------------------------------
void drawForStateNormal() {
background(0);
textSize(14);
// title
fill(255, 2, 2);
text("My little Editor",
width-123, 20, 100, 22);
// the text the user entered
fill(255);
text(str+blink(),
20, 20, 100, height-20);
// ----------------------
// TWO buttons
textSize(11);
fill(128);
if ( overSave() ) {
fill(196);
}
rect(width-40, height-20, 40, 20);
fill(255);
text("Save",
width-40+4, height-9+3);
// ---
fill(128);
if ( overLoad() ) {
fill(196);
}
rect(width-40, height-50, 40, 20);
fill(255);
text("Load",
width-40+4, height-50+9+3);
}
//----------------------------------------------------------------------------
// TWO functions register if mouse is over buttons
boolean overSave() {
return( mouseX > width-40 &&
mouseY > height-20 );
}
boolean overLoad() {
return( mouseX > width-40 &&
mouseY > height-50 &&
mouseY < height-50+25 );
}
// ---------------------------------------------------------------------------
// Inputs
void keyPressed() {
if ( keyCode == DELETE || keyCode == BACKSPACE ) {
if ( str.length() > 0 ) {
str = str.substring(0, str.length()-1);
}
} else {
if ( key != CODED ) {
str += key;
}
}
}
void mousePressed() {
if ( overSave() ) {
savePath="";
selectOutput("Select a file to write to:", "fileSelectedSave");
state=save;
} else if ( overLoad() ) {
loadPath="";
selectInput("Select a file to load:", "fileSelectedLoad");
state=load;
}
}
// -------------------------------------------------
// Save and load
void saveIt() {
//save
// split at line break and make array
String[] strs = split ( str, "\n" );
saveStrings( savePath, strs );
}
void loadIt() {
// load
String[] strs = loadStrings( loadPath );
str=join(strs, "\n");
}
void fileSelectedSave(File selection) {
if (selection == null) {
println("Window was closed or the user hit cancel.");
} else {
println("User selected " + selection.getAbsolutePath());
savePath=selection.getAbsolutePath();
}
}
void fileSelectedLoad(File selection) {
if (selection == null) {
println("Window was closed or the user hit cancel.");
} else {
println("User selected " + selection.getAbsolutePath());
loadPath=selection.getAbsolutePath();
}
}
// -------------------------------------------------
// Misc
String blink() {
// toggle blinkIsOn
if (frameCount%17 == 0)
blinkIsOn=!blinkIsOn;
// depending from blinkIsOn
if (blinkIsOn)
return "|";
else return "";
}
//
See, the idea of the forum is that you ask for help with your code. Like post code and ask something like „in line 30 I need to check the mouse against my nice Load Button but I don’t know how“.
The forum is not here to ask others for complete programs.
These are just some rules here to get used to.
Now you wrote you tried selectInput and I asked to see your attempt and you said it’s above but above there is no selectInput.
So when you want to learn how to program, try to write a code with selectInput and then show attempts and ask and learn.
The trick with selectInput for example is that draw() doesn’t wait for it. Instead you need to check whether its result has arrived and then move on. Use a Boolean variable for example which tells you if the result has arrived (see example of selectInput to understand).
Best regards, Chrisir
I have tried the SelectInput(), but i cant seem to make it work :(
A file dialog to choose a file can be found by checking previous posts as well: https://forum.processing.org/two/search?Search=selectinput
Also check the controlP5 or G4P library to use buttons in your sketch. You can install either library using the library manager in the Processing IDE. Then, go to files>>examples>>Contributed libraries and either ControlP5 or G4P to see the examples.
Kf
Hi all.
I sorted this issue by a bit of working around. The code is as below for a record. It's slightly messy, but it works. I had to detect apple-command key separately. I also added a timer. More lines were required than I imagined. My verdict is that I wouldn't use combination short-cut keys and just use single key for a short cut unless absolutely required.
Please let me know if someone find a better way of doing this. I also don't know why (keyCode == COMMAND_KEY) didn't work alternately. Any idea?
boolean key_command;
boolean key_open;
//int COMMAND_KEY = 157; // apple-command key. not used.
IsKeyPressed ikp; // detect apple-command key separately...
void setup()
{
size(100, 100);
key_command = false;
key_open = false;
ikp= new IsKeyPressed();
ikp.main();
}
void draw()
{
}
float startTimer;
boolean timerStarted = false;
void keyPressed()
{
if (key == CODED) {
// the statement if (keyCode == COMMAND_KEY)
// not always worked. Work-around with IsKeyPressed class...
if (ikp.isAppleKeyPressed()) {
key_command = true;
if (!timerStarted) {
timerStarted = true;
startTimer = millis();
}
}
}
if (key == 'o' || key == 'O') {
key_open = true;
if (!timerStarted) {
timerStarted = true;
startTimer = millis();
}
}
checkComboKeys();
}
void keyReleased()
{
println("keyReleased()");
if (key_command == true && key_open == true)
resetComboKeys();
}
void checkComboKeys() {
if (key_command && key_open) { // command-apple + O
println("command + O pressed");
if (millis() - startTimer < 800.0){
openFile();
}else{
resetComboKeys();
}
timerStarted = false;
}
}
void resetComboKeys() {
key_command = false;
key_open = false;
}
void openFile() {
selectInput("Select a file to open:", "openSelected");
resetComboKeys();
}
void openSelected(File selection) {
if (selection == null) {
println("Window closed or cancelled.");
} else {
println("User selected: " + selection.getAbsolutePath());
}
}
// IsKeyPressed class (.java)
// detect if apple-command key is pressed.
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
public class IsKeyPressed {
private static volatile boolean appleKeyPressed = false;
public static boolean isAppleKeyPressed(){
synchronized (IsKeyPressed.class) {
return appleKeyPressed;
}
}
public static void main() {
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent ke) {
synchronized (IsKeyPressed.class) {
switch (ke.getID()) {
case KeyEvent.KEY_PRESSED:
if (ke.getKeyCode() == KeyEvent.VK_META) {
System.out.println("apple key");
appleKeyPressed = true;
}
break;
case KeyEvent.KEY_RELEASED:
if (ke.getKeyCode() == KeyEvent.VK_META) {
appleKeyPressed = false;
}
break;
}
return false;
}
}
}
);
}
}
I added a println() in the keyPressed() method as below.
void keyPressed(KeyEvent e){
println("key: " + e.getKeyCode());
if(key == CODED){
if (keyCode == COMMAND_KEY){
key_command = true;
}
}
if(key == 'o' || key == 'O'){
key_open = true;
}
checkComboKeys();
}
It prints 'key:157' (command key) and 'key:0' alternately with the above program. I wonder if this is a bug or my use of selectInput() is not correct?
Hi, I have a question about a behaviour of opening a file with the combination of Command key and 'O' key. The code is as below. It almost works, but when I open a file or cancel the dialog box after selectInput() method was called, and then immediately after that trying to open another file by pressing Command+O it just doesn't work. If I press the command key once before pressing Command+O then it works again, so it seems its something to do with Command key. Can anyone tell me what the problem is?
boolean key_command;
boolean key_open;
int COMMAND_KEY = 157; // apple-command key
void setup()
{
size(100, 100);
key_command = false;
key_open = false;
}
void draw()
{
}
void keyPressed()
{
if (key == CODED) {
if (keyCode == COMMAND_KEY) {
key_command = true;
}
}
if (key == 'o' || key == 'O')
key_open = true;
checkComboKeys();
}
void keyReleased()
{
println("keyReleased()");
resetComboKeys();
}
void checkComboKeys() {
if (key_command && key_open) { // command-apple + O
println("command + O pressed");
openFile();
}
}
void resetComboKeys() {
key_command = false;
key_open = false;
}
void openFile() {
selectInput("Select a file to open:", "openSelected");
}
void openSelected(File selection) {
if (selection == null) {
println("Window closed or cancelled.");
} else {
println("User selected: " + selection.getAbsolutePath());
}
}
Thanks for your speedy reply and forgive my ignorance. I hope you can make something of this:
import java.awt.event.KeyEvent;
import javax.swing.JOptionPane;
import processing.serial.*;
Serial port = null;
// select and modify the appropriate line for your operating system
// leave as null to use interactive port (press 'p' in the program)
String portname = null;
//String portname = Serial.list()[0]; // Mac OS X
//String portname = "/dev/ttyUSB0"; // Linux
//String portname = "COM6"; // Windows
boolean streaming = false;
float speed = 0.001;
String[] gcode;
int i = 0;
void openSerialPort()
{
if (portname == null) return;
if (port != null) port.stop();
port = new Serial(this, portname, 9600);
port.bufferUntil('\n');
}
void selectSerialPort()
{
String result = (String) JOptionPane.showInputDialog(this,
"Select the serial port that corresponds to your Arduino board.",
"Select serial port",
JOptionPane.PLAIN_MESSAGE,
null,
Serial.list(),
0);
if (result != null) {
portname = result;
openSerialPort();
}
}
void setup()
{
size(500, 250);
openSerialPort();
}
void draw()
{
background(0);
fill(255);
int y = 24, dy = 12;
text("INSTRUCTIONS", 12, y); y += dy;
text("p: select serial port", 12, y); y += dy;
text("1: set speed to 0.001 inches (1 mil) per jog", 12, y); y += dy;
text("2: set speed to 0.010 inches (10 mil) per jog", 12, y); y += dy;
text("3: set speed to 0.100 inches (100 mil) per jog", 12, y); y += dy;
text("arrow keys: jog in x-y plane", 12, y); y += dy;
text("page up & page down: jog in z axis", 12, y); y += dy;
text("$: display grbl settings", 12, y); y+= dy;
text("h: go home", 12, y); y += dy;
text("0: zero machine (set home to the current location)", 12, y); y += dy;
text("g: stream a g-code file", 12, y); y += dy;
text("x: stop streaming g-code (this is NOT immediate)", 12, y); y += dy;
y = height - dy;
text("current jog speed: " + speed + " inches per step", 12, y); y -= dy;
text("current serial port: " + portname, 12, y); y -= dy;
}
void keyPressed()
{
if (key == '1') speed = 0.001;
if (key == '2') speed = 0.01;
if (key == '3') speed = 0.1;
if (!streaming) {
if (keyCode == LEFT) port.write("G91\nG20\nG00 X-" + speed + " Y0.000 Z0.000\n");
if (keyCode == RIGHT) port.write("G91\nG20\nG00 X" + speed + " Y0.000 Z0.000\n");
if (keyCode == UP) port.write("G91\nG20\nG00 X0.000 Y" + speed + " Z0.000\n");
if (keyCode == DOWN) port.write("G91\nG20\nG00 X0.000 Y-" + speed + " Z0.000\n");
if (keyCode == KeyEvent.VK_PAGE_UP) port.write("G91\nG20\nG00 X0.000 Y0.000 Z" + speed + "\n");
if (keyCode == KeyEvent.VK_PAGE_DOWN) port.write("G91\nG20\nG00 X0.000 Y0.000 Z-" + speed + "\n");
if (key == 'h') port.write("G90\nG20\nG00 X0.000 Y0.000 Z0.000\n");
if (key == 'v') port.write("$0=75\n$1=74\n$2=75\n");
//if (key == 'v') port.write("$0=100\n$1=74\n$2=75\n");
if (key == 's') port.write("$3=10\n");
if (key == 'e') port.write("$16=1\n");
if (key == 'd') port.write("$16=0\n");
if (key == '0') openSerialPort();
if (key == 'p') selectSerialPort();
if (key == '$') port.write("$$\n");
}
if (!streaming && key == 'g') {
gcode = null; i = 0;
File file = null;
println("Loading file...");
selectInput("Select a file to process:", "fileSelected", file);
}
if (key == 'x') streaming = false;
}
void fileSelected(File selection) {
if (selection == null) {
println("Window was closed or the user hit cancel.");
} else {
println("User selected " + selection.getAbsolutePath());
gcode = loadStrings(selection.getAbsolutePath());
if (gcode == null) return;
streaming = true;
stream();
}
}
void stream()
{
if (!streaming) return;
while (true) {
if (i == gcode.length) {
streaming = false;
return;
}
if (gcode[i].trim().length() == 0) i++;
else break;
}
println(gcode[i]);
port.write(gcode[i] + '\n');
i++;
}
void serialEvent(Serial p)
{
String s = p.readStringUntil('\n');
println(s.trim());
if (s.trim().startsWith("ok")) stream();
if (s.trim().startsWith("error")) stream(); // XXX: really?
}
I'm not sure how to copy the error in the console but it's:
The Function "showInputDialog()" expects parameters like: "showInputDialog(Components, Objects, String, int, Icon, Object[], Object )"
Thanks Again
Thank you @akenaton. I corrected the problem in the function I created, added two Images. "Imagetoedit" and "imagemodified". (imagetoedit at the beginning it's the same of the image that i load in setup) the function creates image accepts inputs of the dials in the original position and outputs the modified image that will be replaced by the original. my idea from the first moment was this, so I would not need to use the indexes but to repeat a single operation at each click but it still does not work.
p.s btw my version of processing doesn't recognizes the object PImage [4] immagine;
PImage immagine;
PImage immagineDaModificare;
PImage immagineModificata;
PImage a;
PImage b;
PImage c;
PImage d;
PImage e;
boolean modalitaMostra=true;
void setup(){
background(255);
String pathimmagine= selectInput("Scegli l'immagine da elaborare");
immagine = loadImage(pathimmagine);
size(immagine.width,immagine.height);
immagineDaModificare=immagine;
localizzaQuadranti();
image (a, 0, 0, width/2, height/2);
image (b, width/2, 0, width/2, height/2);
image (c,width/2, height/2, width/2, height/2);
image (d, 0, height/2, width/2, height/2);
};
void draw(){}
void localizzaQuadranti(){
a= immagineDaModificare.get( 0, 0, width/2, height/2);
b= immagineDaModificare.get (width/2, 0, width/2, height/2);
c= immagineDaModificare.get (width/2, height/2, width/2, height/2);
d= immagineDaModificare.get( 0, height/2, width/2, height/2);
}
PImage creaImmagine (PImage immagineDaModificare) {
immagineDaModificare.loadPixels();
image (d, 0, 0, width/2, height/2);
image (a, width/2, 0, width/2, height/2);
image (b,width/2, height/2, width/2, height/2);
image (c, 0, height/2, width/2, height/2);
e=a;
d=c;
c=b;
b=a;
a=e;
immagineModificata.updatePixels();
return immagineModificata;
}
void keyTyped (){
if (key=='m'){
if (modalitaMostra=true){
modalitaMostra =false;
}
else{
modalitaMostra = true;
}}}
void mouseClicked(){
if (modalitaMostra==false){
creaImmagine(immagineDaModificare);
immagineDaModificare=immagineModificata;
}}
Sorry again, I think I found a simpler way, the program starts correctly but I get the error "NullPointerExeption". Would you tell me what I did not initialize properly?
PImage immagine;
PImage a;
PImage b;
PImage c;
PImage d;
boolean modalitaMostra=true;
void setup(){
background(255);
String pathimmagine= selectInput("Scegli l'immagine da elaborare");
immagine = loadImage(pathimmagine);
size(immagine.width,immagine.height);
localizzaQuadranti();
image (a, 0, 0, width/2, height/2);
image (b, width/2, 0, width/2, height/2);
image (c,width/2, height/2, width/2, height/2);
image (d, 0, height/2, width/2, height/2);
};
void draw(){}
void localizzaQuadranti(){
PImage a= immagine.get( 0, 0, width/2, height/2);
PImage b= immagine.get (width/2, 0, width/2, height/2);
PImage c= immagine.get (width/2, height/2, width/2, height/2);
PImage d= immagine.get( 0, height/2, width/2, height/2);
}
PImage creaImmagine (PImage immagine) {
immagine.loadPixels();
image (d, 0, 0, width/2, height/2);
image (a, width/2, 0, width/2, height/2);
image (b,width/2, height/2, width/2, height/2);
image (c, 0, height/2, width/2, height/2);
immagine.updatePixels();
return immagine;
}
void keyTyped (){
if (key=='m'){
if (modalitaMostra=true){
modalitaMostra =false;
}
else{
modalitaMostra = true;
}}}
void mouseClicked(){
if (modalitaMostra==false){
creaImmagine(immagine);
}}
@Steve921===
Not sure about what you want (and your code cannot run!) - Something like that???
PImage immagine;
boolean Show=true;
int nbre=0;
PImage a;
PImage b;
PImage c;
PImage d;
ArrayList<PImage> tabIma;
void setup(){
background(255);
String pathimmagine= selectInput("Scegli l'immagine da elaborare");
immagine = loadImage(pathimmagine);
size(immagine.width,immagine.height);
image(immagine,0,0);
tabIma= new ArrayList<PImage>();
decoupe();
};
void draw(){
background(255);
if(Show){
image(immagine, 0,0);
}else {
float px=0;
float py=0;
for(int i = 0;i<tabIma.size();i++){
if(i==0){
px= 0;
py=0;
}
if(i==1){
px= width/2;
py=0;
}if(i==2){
px = width/2;
py= height/2;
}if (i==3){
px = 0;
py= height/2;
}
image(tabIma.get(i),px, py);
}
}
};
void decoupe(){
a= immagine.get( 0, 0, width/2, height/2);
b= immagine.get (width/2, 0, width/2, height/2);
c= immagine.get (width/2, height/2, width/2, height/2);
d= immagine.get( 0, height/2, width/2, height/2);
tabIma.add(a);
tabIma.add(b);
tabIma.add(c);
tabIma.add(d);
};
void mouseReleased(){
if(nbre<tabIma.size()-1){
nbre++;
}else{
nbre=0;
}
tabIma.clear();
tabIma= new ArrayList<PImage>();
if(nbre==1){
tabIma.add(d);
tabIma.add(a);
tabIma.add(b);
tabIma.add(c);
}
if(nbre==2){
tabIma.add(c);
tabIma.add(d);
tabIma.add(a);
tabIma.add(b);
}
if(nbre==3){
tabIma.add(b);
tabIma.add(c);
tabIma.add(d);
tabIma.add(a);
}
if(nbre==0){
tabIma.add(a);
tabIma.add(b);
tabIma.add(c);
tabIma.add(d);
}
}
void keyPressed (){
if (key=='m'){
if (Show){
Show=false;;
}
else if(!Show){
Show=true;
}
}
};
Hi everybody, i have a problem with the code below ... My goal is: Ask processing to load any image from disk. When you press the m key, the image will be divided into four dials, and if you click the mouse, the dials will rotate clockwise. I can not find the error, please help me!
PImage immagine;
boolean Show=true;
PImage a;
PImage b;
PImage c;
PImage d;
void setup(){
String pathimmagine= selectInput("Scegli l'immagine da elaborare");
immagine = loadImage(pathimmagine);
size(immagine.width,immagine.height);
image(immagine,0,0);
}
void keyTyped (){
if (key==m){
if (Show=true){
Show =false;
}
else{
Show = true;
}
else{
image(immagine,0,0);
}
}
}
void mouseClicked(){
if (modalitaMostra==false){
PImage img = createImage(immagine.width,immagine.height , ARGB);
img.loadPixels();
for (int i = 0; i < img.pixels.length; i++) {
img.pixels[i] = immagine.pixels[i];
}
img.updatePixels();
a= (immagine, 0, 0, width/2, height/2);
b= (immagine, width/2, 0, width/2, height/2);
c= (immagine, 0, height/2, width/2, height/2);
d= (immagine, width/2, height/2, width/2, height/2);
e=a
d=c
c=b
b=a
a=e
return img
immagine=img;
image(immagine,0,0);
}
else{
image(immagine,0,0);
}
}
Look at the reference for selectInput please
At the end there are variants of the parameters and one is with File. Use this version.
So before selectInput say
File defaultFile = new File (yourNameFromAutoLoad);
And then use selectInput with that defaultFile
quick question back on this. .. hopefully a simple answer I've overlooked here.
I'm using selectInput() &
selectOutput()
to open a popup and let user pick a file (as you do) this "abstract"? file path is passed to the callback functions :
openSession(File selection) and saveSession(File selection)
All good, but I also have autoSave and autoLoad functions, which save/load to/from one set "autosavefile" created at the sketchPath() +"/data"
.
Rather than having these entire extra autoSave/load functions which save exactly the same data as the user driven save/load options. I would like to just pass the file path of my "autosavefile" to the openSession() and saveSession() functions...but I can't figure out at all how to do it, do I need to convert the pathname String to pathname abstract ? and if so how?
Hi there!,
I was trying to use the selectInput
for loading an image in processing android mode and it didn't work. I also tried to use the SelectFile library, which is unfortunately not working with the latest processing.
any other libraries or methods to dynamically load image?
Any help would be much appreciated!
Thanks in advance :)
I'm back here since I've finally managed to pull together the language definition! There are a few minor inconveniences though, that I will explain here.
Firstly, for function names that are the same as an already defined keyword (Such as "boolean" and "boolean()"), you have to use [escapechar = "char"] and \color{"color"}{"text"} to color them properly. Example:
\begin{lstlisting}[escapechar = ?]
boolean;
?\color{function}{boolean}?(1);
\end{lstlisting}
Secondly, there is no bold style. In Processing, a few of the function names are defaulted to using bold font, but this could not be implemented.
Bold style is now working as of v1.2.
Copy and paste the below template if you want to use it. Alternatively, you can copy only the necessary parts. If in that case, note that \usepackage{listings} and \usepackage{color} is a must for this to work.
Also note, I have licensed this work with CreativeCommons license CC-BY-SA, so please remember to give some credit to me ;)
If you find any typos or any other errors, please tell me and I'll try to fix them as much as possible.
Download version: http://www.mediafire.com/file/cw861uy156xftkv/article_listing_Processing_v1.2.tex
Full template below:
\documentclass{article}
\usepackage{graphicx}
\usepackage{url}
\usepackage{verbatim}
\usepackage{listings}
\usepackage{color}
% Processing language definition template for LaTeX listings package v1.2
%
% Credits to ebigunso for creating this LaTeX listings language definition template for Processing
% This template is licensed with CreativeCommons license CC-BY-SA 4.0
% license info:
% https://creativecommons.org/licenses/by-sa/4.0/legalcode
%Define Colors
\definecolor{black}{RGB}{0,0,0}
\definecolor{gray}{RGB}{102,102,102} %#666666
\definecolor{function}{RGB}{0,102,153} %#006699 lightblue
\definecolor{lightgreen}{RGB}{102,153,0} %#669900
\definecolor{bluegreen}{RGB}{51,153,126} %#33997e
\definecolor{magenta}{RGB}{217,74,122} %#d94a7a
\definecolor{orange}{RGB}{226,102,26} %#e2661a
\definecolor{purple}{RGB}{125,71,147} %#7d4793
\definecolor{green}{RGB}{113,138,98} %#718a62
\lstdefinelanguage{Processing}{
%keyword1&2&6
morekeywords = [3]{abstract, break, class, continue, default, enum, extends, false, final, finally, implements, import, instanceof, interface, native, new, null, package, private, protected, public, static, strictfp, throws, transient, true, void, volatile, length, assert, case, return, super, this, throw},
%keyword3
morekeywords = [4]{catch, do, for, if, else, switch, synchronized, while, try},
%keyword4
morekeywords = [5]{width, height, pixelHight, displayHeight, displayWidth, focused, frameCount, frameRate, key, keyCode, keyPressed, mouseButton, mousePressed, mouseX, mouseY, pixels, pixelWidth, pmouseX, pmouseY},
%keyword5
morekeywords = [6]{Array, ArrayList, Boolean, Byte, BufferedReader, Character, Class, Double, Float, Integer, HashMap, PrintWriter, String, StringBuffer, StringBuilder, Thread, boolean, byte, char, color, double, float, int, long, short, FloatDict, FloatList, IntDict, IntList, JSONArray, JSONObject, PFont, PGraphics, PImage, PShader, PShape, PVector, StringDict, StringList, Table, TableRow, XML},
%literal2
morekeywords = [7]{ADD, ALIGN_CENTER, ALIGN_LEFT, ALIGN_RIGHT, ALPHA, ALPHA_MASK, ALT, AMBIENT, ARC, ARROW, ARGB, BACKSPACE, BASELINE, BEVEL, BLEND, BLUE_MASK, BLUR, BOTTOM, BOX, BURN, CENTER, CHATTER, CHORD, CLAMP, CLICK, CLOSE, CMYK, CODED, COMPLAINT, COMPOSITE, COMPONENT, CONCAVE_POLYGON, CONTROL, CONVEX_POLYGON, CORNER, CORNERS, CROSS, CUSTOM, DARKEST, DEGREES, DEG_TO_RAD, DELETE, DIAMETER, DIFFERENCE, DIFFUSE, DILATE, DIRECTIONAL, DISABLE_ACCURATE_2D, DISABLE_DEPTH_MASK, DISABLE_DEPTH_SORT, DISABLE_DEPTH_TEST, DISABLE_NATIVE_FONTS, DISABLE_OPENGL_ERRORS, DISABLE_PURE_STROKE, DISABLE_TEXTURE_MIPMAPS, DISABLE_TRANSFORM_CACHE, DISABLE_STROKE_PERSPECTIVE, DISABLED, DODGE, DOWN, DRAG, DXF, ELLIPSE, ENABLE_ACCURATE_2D, ENABLE_DEPTH_MASK, ENABLE_DEPTH_SORT, ENABLE_DEPTH_TEST, ENABLE_NATIVE_FONTS, ENABLE_OPENGL_ERRORS, ENABLE_PURE_STROKE, ENABLE_TEXTURE_MIPMAPS, ENABLE_TRANSFORM_CACHE, ENABLE_STROKE_PERSPECTIVE, ENTER, EPSILON, ERODE, ESC, EXCLUSION, EXIT, FX2D, GIF, GRAY, GREEN_MASK, GROUP, HALF, HALF_PI, HAND, HARD_LIGHT, HINT_COUNT, HSB, IMAGE, INVERT, JAVA2D, JPEG, LEFT, LIGHTEST, LINE, LINES, LINUX, MACOSX, MAX_FLOAT, MAX_INT, MIN_FOAT, MIN_INT, MITER, MODEL, MOVE, MULTIPLY, NORMAL, NORMALIZED, NO_DEPTH_TEST, NTSC, ONE, OPAQUE, OPEN, ORTHOGRAPHIC, OVERLAY, PAL, PDF, P2D, P3D, PERSPECTIVE, PI, PIE, PIXEL_CENTER, POINT, POINTS, POSTERIZE, PRESS, PROBLEM, PROJECT, QUAD, QUAD_STRIP, QUADS, QUARTER_PI, RAD_TO_DEG, RADIUS, RADIANS, RECT, RED_MASK, RELEASE, REPEAT, REPLACE, RETURN, RGB, RIGHT, ROUND, SCREEN, SECAM, SHAPE, SHIFT, SPAN, SPECULAR, SPHERE, SOFT_LIGHT, SQUARE, SUBTRACT, SVG, SVIDEO, TAB, TARGA, TAU, TEXT, TFF, THIRD_PI, THRESHOLD, TIFF, TOP, TRIANGLE, TRIANGLE_FAN, TRIANGLES, TRIANGLE_STRIP, TUNER, TWO, TWO_PI, UP, WAIT, WHITESPACE},
%function1
morekeywords = [8]{start, stop, breakShape, createPath, str, loadMatrix, parseBoolean, parseByte, parseChar, parseFloat, parseInt, saveFile, savePath, sketchFile, sketchPath, abs, acos, alpha, ambient, ambientLight, append, applyMatrix, arc, arrayCopy, asin, atan, atan2, background, beginCamera, beginContour, beginRaw, beginRecord, beginShape, bezier, bezierDetail, bezierPoint, bezierTangent, bezierVertex, binary, blend, blendColor, blendMode, blue, box, brightness, camera, ceil, clear, clip, color, colorMode, concat, constrain, copy, cos, createFont, createGraphics, createImage, createInput, createOutput, createReader, createShape, createWriter, cursor, curve, curveDetail, curvePoint, curveTangent, curveTightness, curveVertex, day, degrees, delay, directionalLight, displayDensity, dist, ellipse, ellipseMode, emissive, endCamera, endContour, endRaw, endRecord, endShape, exit, exp, expand, fill, filter, floor, frustum, fullScreen, get, green, hex, hint, hour, hue, image, imageMode, join, launch, lerp, lerpColor, lightFalloff, lights, lightSpecular, line, loadBytes, loadFont, loadImage, loadJSONArray, loadJSONObject, loadPixels, loadShader, loadShape, loadStrings, loadTable, loadXML, log, loop, mag, map, match, matchAll, max, millis, min, minute, modelX, modelY, modelZ, month, nf, nfc, nfp, nfs, noClip, noCursor, noFill, noise, noiseDetail, noiseSeed, noLights, noLoop, norm, normal, noSmooth, noStroke, noTint, ortho, parseJSONArray, parseJSONObject, parseXML, perspective, list, pixelDnsity, point, pointLight, popMatrix, popStyle, pow, print, printArray, printCamera, println, printMatrix, printProjection, pushMatrix, pushStyle, quad, quadraticVertex, radians, random, randomGaussian, randomSeed, rect, rectMode, red, redraw, requestImage, resetMatrix, resetShader, reverse, rotate, rotateX, rotateY, rotateZ, round, saturation, save, saveBytes, saveFrame, saveJSONArray, saveJSONObject, saveStream, saveStrings, saveTable, saveXML, scale, screenX, screenY, screenZ, second, selectFolder, selectInput, selectOutput, set, shader, shape, shapeMode, shearX, shearY, shininess, shorten, sin, size, smooth, sort, specular, sphere, sphereDetail, splice, split, splitTokens, spotLight, sq, sqrt, stroke, strokeCap, strokeJoin, strokeWeight, subset, tan, text, textAlign, textAscent, textDescent, textFont, textLeading, textMode, textSize, texture, textureMode, textureWrap, textWidth, thread, tint, translate, triangle, trim, unbinary, unhex, updatePixels, vertex, year},
%function2
morekeywords = [9]{cache, readLine, close, flush, print, println, charAt, equals, indexOf, substring, toLowerCase, toUpperCase, getDouble, getLong, getColumnTitles, getColumnTypes, getColumnType, setDouble, setLong, add, clear, div, get, hasKey, keyArray, keys, mult, remove, set, size, sortKeys, sortKeysReverse, sortValues, sortValuesReverse, sub, valueArray, values, append, array, hasValue, max, min, mult, remove, reverse, shuffle, sort, sortReverse, increment, getBoolean, getFloat, getInt, getIntArray, getJSONArray, getJSONObject, getString, getStringArray, isNull, setBoolean, setFloat, setInt, setJSONArray, setJSONObject, setString, beginDraw, endDraw, blend, copy, filter, loadPixels, mask, resize, save, updatePixels, addChild, beginContour, beginShape, disableStyle, enableStyle, endContour, endShape, getChild, getChildCount, getVertex, getVertexCount, isVisible, resetMatrix, rotate, rotateX, rotateY, rotateZ, scae, setFill, setStroke, setVertex, setVisible, translate, angleBetween, cross, dist, dot, fromAngle, heading, lerp, limit, mag, magSq, normalize, randm2D, random3D, setMag, lower, upper, addColumn, addRow, clearRows, findRow, findRows, getColumnCount, getRow, getRowcount, getStringColumn, matchRow, matchRows, removeColumn, removeRow, removeTokens, rows, trim, getColumnTitle, format, getAttributeCount, getChildren, getContent, getNam, getParent, hasAttribute, hasChildren, listAttributes, listChildren, removeChild, setContent, setName, toString},
%function4
morekeywords = [10]{draw, keyReleased, keyTyped, mouseClicked, mouseDragged, mouseMoved, mouseReleased, mouseWheel, settings, setup},
keywordstyle = [3]\color{bluegreen},
keywordstyle = [4]\color{lightgreen},
keywordstyle = [5]\color{magenta},
keywordstyle = [6]\color{orange},
keywordstyle = [7]\color{green},
keywordstyle = [8]\color{function},
keywordstyle = [9]\color{function},
keywordstyle = [10]\color{function},
sensitive = true,
morecomment = [l][\color{gray}]{//},
morecomment = [s][\color{gray}]{/*}{*/},
morecomment = [s][\color{gray}]{/**}{*/},
morestring = [b][\color{purple}]",
morestring = [b][\color{purple}]'
}
\renewcommand{\ttdefault}{pcr}
\lstset{
language={Processing},
basicstyle={\small\ttfamily},
identifierstyle={\small},
commentstyle={\small\itshape},
keywordstyle={\small\bfseries},
ndkeywordstyle={\small},
stringstyle={\small\ttfamily},
frame={tb},
breaklines=true,
columns=[l]{fullflexible},
numbers=left,
xrightmargin=0em,
xleftmargin=3em,
numberstyle={\scriptsize},
stepnumber=1,
numbersep=1em,
lineskip=-0.5ex,
}
% Use escapechar and \color{<color>}{<text>} to color function names properly, that is already defined as a different color keyword.
%
% \begin{lstlisting}[escapechar = ?]
% boolean;
% ?\color{function}{boolean}?(1);
% \end{lstlisting}
\title{}
\author{}
\date{}
\begin{document}
\maketitle
\section{}
\begin{thebibliography}{9}
\end{thebibliography}
\end{document}
Previous posts that you might be interested in exploring:
https://forum.processing.org/two/search?Search=jfilechooser
https://forum.processing.org/two/search?Search=selectinput
Kf