Howdy, Stranger!

We are about to switch to a new forum software. Until then we have removed the registration on this forum.

  • How to use input with (python) processing running on a mac ?

    I'm using a very rude swing InputDialog:

    def setup():
        answer = input('enter your name')
        println('hi ' + str(answer))
    
    def input(message=''):
        from javax.swing import JOptionPane
        return JOptionPane.showInputDialog(frame, message)
    
  • raw_input() for Processing.py (how to get/use)

    Cancel button will make it return None

    def setup():
        answer = input('enter your name')
        if answer:
            println('hi ' + answer)
        elif answer == '':
            println('[empty string]')
        else:
            println(answer) # Canceled dialog will print None
    
    def input(message=''):
        from javax.swing import JOptionPane
        return JOptionPane.showInputDialog(frame, message)
    
  • raw_input() for Processing.py (how to get/use)

    I'm not sure this helps but here I go:

    How about a nasty swing InputDialog?

    def input(message=''):
        from javax.swing import JOptionPane
        return JOptionPane.showInputDialog(frame, message)
    
  • Letters are not being printed in the correct positions

    Hi I'm trying to print the letters in this game in the correct spaces but it's not working properly. Any suggestion would be helpful. Since this is an assignment I would appreciate it if direct solutions are not provided instead pointing me to the right direction or hints would be great! Thanks! And here's my code..

    import javax.swing.JOptionPane;
    
    String[] myWords = {"hello", "desktop", "computer", "python", "network", "database", "loops", "phone", "laptop", "memory"}; // Array containing the words for the game.
    char[] selectedWord, wrongGuesses, rightGuesses, currentWord; //selectedWord is the array that stores the word selected randomly for the game, wronGuesses store the wrong letters, rightGuesses stores the right letter and currentWord stores the current letter of the word that the user typed in.
    int correctNum, incorrectNum;//correctNum is the total number of Input that has been guessed correctly and incorrectNum is the total number of input that has been guessed incorrectly
    int[] letterIndex;//position of letter in an array
    
    void setup(){
      background(255);//white background
      selectedWord = getWord().toCharArray();//stores the randomly selected string from myWords and stored in selectedWord in char format
      rightGuesses = new char[10];
      wrongGuesses = new char[7];
      correctNum = 0;
      incorrectNum = 0;
       int wordLength = selectedWord.length;
            currentWord = new char[wordLength];
            for(int i = 0; i < wordLength; i++) {
              currentWord[i] = ' ';
            }
            letterIndex = new int[wordLength];
      size(500,500);
      smooth();
      drawBase();//draws the base structure of the game
      drawLetterSpaces();//draws the spaces for the place where the letters needs to be printed
    }
    
    void draw(){
      process();//the main process
    }
    
    //the base structure of the game which is the hangman stand
    void drawBase(){
      strokeWeight(5);
      line(100, 300, 200, 300);
      line(150, 300, 150, 50);
      line(150, 50, 300, 50);
      line(300, 50, 300, 100);
      line(150, 150, 250, 50);
    }
    
    //draws a head
    void drawHead(){
      ellipse(300, 125, 50, 50);
    }
    
    //draws the body
    void drawBody(){
      line(300, 150, 300, 225);
    }
    
    //draws the left leg
    void drawLeftLeg() {
      line(300, 225, 270, 265);
    }
    
    //draws the right leg
    void drawRightLeg() {
      line(300, 225, 330, 265);
    }
    
    //draws the left arm
    void drawLeftArm() {
      line(300, 175, 270, 185);
    }
    
    //draws the right arm
    void drawRightArm() {
      line(300, 175, 330, 185);
    }
    
    //generates a random index number for the myWord array 
    int letterIndexGenerator(){
      return int(random(myWords.length));//generates random index for myWord array
    }
    
    //selects the string from the randomly generated index of myWord array using letterIndexGenerator function
    String getWord(){
      return myWords[letterIndexGenerator()];
    }
    
    //draws the spaces for the letters
    void drawLetterSpaces(){
      int xVal1 = 50;//starting position of the first space
      int xVal2 = 80;//ending position of the first space
      for(int i = 0; i < selectedWord.length; i++){ //loop to draw the required number of spaces for the selected word from getWord function
        line(xVal1, 400, xVal2, 400);
        xVal1 += 50;//draws the starting position of the next spaces after 50 places gap
        xVal2 += 50;//draws the ending position of the next spaces after 50 places gap
      }
    }
    
    //gets the input from user
    char userInput(){
      String input = JOptionPane.showInputDialog("Please enter a character: ");
      if(input.length() == 0){//if input is blank ask again for input
        JOptionPane.showMessageDialog(null, "Invalid Input. Please try again!");
        return userInput();
      }
      else if(input.length() > 1){//if more than one letter is input than count only the first letter
        return input.charAt(0);
      }
      else{
        return input.charAt(0);
      }
    }
    
    //fills the letters input by user in the correct spaces provided
    void fillLetters(char ch, int[] indexes) {
      for(int i = 0; i < indexes.length; i++) {
        if (indexes[i] == 0) {
          textSize(50);
          fill(0);
          text(ch, 50, 400);
        } 
        else if (indexes[i] == 2) {
           textSize(50);
           fill(0);
           text(ch, 100, 400);
        } 
        else if (indexes[i] == 3) {
            textSize(50);
            fill(0);
            text(ch, 150, 400);
        } 
        else if (indexes[i] == 4) {
            textSize(50);
            fill(0);
            text(ch, 200, 400);
        } 
        else if (indexes[i] == 5) {
            textSize(50);
            fill(0);
            text(ch, 250, 400);
        } 
        else if (indexes[i] == 6) {
            textSize(50);
            fill(0);
            text(ch, 300, 400);
        } 
        else if (indexes[i] == 7) {
            textSize(50);
            fill(0);
            text(ch, 350, 400);
        } 
        else if (indexes[i] == 8) {
            textSize(50);
            fill(0);
            text(ch, 400, 400);
        } 
        else if (indexes[i] == 9) {
            textSize(50);
            fill(0);
            text(ch, 450, 400);
        } 
        else if (indexes[i] == 10) {
            textSize(50);
            fill(0);
            text(ch, 500, 400);
        }
      }
    }
    
    //checks if character has been previously input by user
    boolean checkExistChar(char input, char[] array){
        for(int i=0; i< array.length;i++){
          if(array[i] == input)
            return true;
        }
        return false;
    }
    
    //checks if user has gussed all letter correctly
    boolean checkWin(){
        if(selectedWord.length == correctNum){
          return true;
        }
        else{
        return false;
        }
    }
    
    //checks if user has reched the limit of incorrect guesses
    boolean checkLost(){
        if(incorrectNum == 7){
          return true;
        }
        else{
        return false;
        }
    }
    
    //prints the wront letters that has been guessed in the console sectionand for each wrong guess draws a body part of the hangman using decisionMaker function
    void printWrongGuesses(){
        println("Number of mistakes : " + incorrectNum);
        for(int i = 0; i < incorrectNum; i++){
          System.out.print(wrongGuesses[i] + " ");
          decisionMaker();
        }
        println();
    }
    
    //checks the incorrectNum variable for the number of incorrect guesses and draws the parts of hangman based on that
    void decisionMaker(){
      if(incorrectNum == 1){
       drawHead();
      }
      else if(incorrectNum == 2){
        drawBody();
      }
      else if(incorrectNum == 3){
        drawLeftArm();
      }
      else if(incorrectNum == 4){
        drawLeftArm();
      }
      else if(incorrectNum == 5){
        drawRightArm();
      }
      else if(incorrectNum == 6){
        drawLeftLeg();
      }
      else if(incorrectNum == 7){
        drawRightLeg();
      }
    }
    
    //the main process
    void process() {
      char input = userInput();//the input from user
       if(checkLost()){//if game lost display a text and exit
         JOptionPane.showMessageDialog(null, "You have lost! Exiting the game! The word was " + new String(selectedWord));
         System.exit(0);
       }
       else if(checkWin()){//if game won dispay text and exit
         JOptionPane.showMessageDialog(null, "You have won the game.");
         System.exit(0);
       }
       if(checkExistChar(input, rightGuesses)){//if user input a letter which is already present in rightGuesses array display text and ask for input again
         JOptionPane.showMessageDialog(null, "You have repeated the letter "+input+"! Please try again!");
       }
       else if(checkExistChar(input, wrongGuesses)){//if user input a letter which is already present in wrongGuesses array then display text and ask for input again
         JOptionPane.showMessageDialog(null, "You have repeated the letter "+input+"! Please try again!");
       }
       else if(checkExistChar(input, selectedWord)){//if user input is present in the selectedWord array, store the input letter in rightGuesses and currentWord, increment correctNum by 1 and print letter in the spaces provided
          for(int i = 0; i < selectedWord.length; i++){
             if(selectedWord[i] == input){
                rightGuesses[correctNum] = input;
                correctNum++;
                currentWord[i] = input;
                letterIndex[i] = i;
                fillLetters(input, letterIndex);
    
            }
          } 
        }
        else if(!checkExistChar(input, selectedWord)){//if input letter is wrong the store it in wrongGuesses array, increment incorrectNum by 1 and call printWrongGuesses function to print wrong letters in console and draw the hangman parts 
          wrongGuesses[incorrectNum] = input;
           incorrectNum++;
           printWrongGuesses();
        }    
    }
    
  • how to set location of popup window ?

    Example for you to try.

    Kf

    //REFERENCES: https://stackoverflow.com/questions/13760117/how-to-set-the-location-of-joptionpane-showmessagedialog
    //REFERENCES: 
    //REFERENCES:
    
    //INSTRUCTIONS:
    //         *-- This program has three states
    //         *-- First state: Your provided example. Leave input text box blank for this example. Pressing
    //         *-- ok leads to next stage. Cancel wil exit code.
    //         *-- Second state: Shows a scond dialog in a random height in the screen. Press in the x in the 
    //         *-- corner of the dialog to dismiss it. 
    //         *-- Third stage: it does nothing.
    //         *-- Note: Current state is shown in the title bar of the main sketch
    
    //===========================================================================
    // IMPORTS:
    import static javax.swing.JOptionPane.*; 
    
    import javax.swing.JDialog;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JButton;
    
    //===========================================================================
    // FINAL FIELDS:
    
    
    //===========================================================================
    // GLOBAL VARIABLES:
    
    int cidx=0;
    CustomDialog myDialog;
    
    //===========================================================================
    // PROCESSING DEFAULT FUNCTIONS:
    
    void settings() {
      size(400, 600);
    }
    
    void setup() {
    
      textAlign(CENTER, CENTER);
      rectMode(CENTER);
    
      fill(255);
      strokeWeight(2);
    }
    
    
    
    void draw() {
      background(0);
    
      if (cidx==0) {
    
        final String id = showInputDialog("Please enter new ID");
        if (id == null)   exit();
        else if ("".equals(id)) {
          mouseReleased();
          showMessageDialog(null, "Empty ID Input!!!", 
            "Error", ERROR_MESSAGE);
        }
    
        myDialog=null;
      } else if (cidx==1){
        if(myDialog==null)
        myDialog=new CustomDialog(null,true,"Hello");
    
      }
    }
    
    void keyReleased() {
    }
    
    void mouseReleased() {
    
      cidx=(cidx+1)%3;
      surface.setTitle(""+cidx);
    }
    
    
    
    //===========================================================================
    // OTHER FUNCTIONS:
    
    public class CustomDialog extends JDialog {
      private JPanel myPanel = null;
      private JButton yesButton = null;
      private JButton noButton = null;
    
      public CustomDialog(JFrame frame, boolean modal, String myMessage) {
        super(frame, modal);
        myPanel = new JPanel();
        getContentPane().add(myPanel);
        myPanel.add(new JLabel(myMessage));
        yesButton = new JButton("Yes");
        myPanel.add(yesButton);
        noButton = new JButton("No");
        myPanel.add(noButton);
        pack();
        //setLocationRelativeTo(frame);
        setLocation(200, int(random(200,displayHeight-200))); // <--
        setVisible(true);
      }
    }
    
  • how to set location of popup window ?

    processing 3.3.5

    import static javax.swing.JOptionPane.*;          
    void draw() {
              final String id = showInputDialog("Please enter new ID");
              if (id == null)   exit();
              else if ("".equals(id)){
                showMessageDialog(null, "Empty ID Input!!!", 
                "Error", ERROR_MESSAGE);
             }
      }
    
  • WindowJS - cross-mode alert(), confirm(), prompt() & other JS API for Java

    Problem is, both renderers P2D & P3D are OpenGL-based wrapped by JOGL bindings: :-B
    https://JogAmp.org/

    Up till PDE v3.0a5, JOGL was somehow embedded as a Java's Applet. ~O)

    But after that, Processing's PApplet class isn't a subclass of Java's Applet anymore. :-&

    So I've got no idea how to control which component gets the right to be foreground:
    JOptionPane's Swing or P3D's JOGL. :-<

    You can check its API if you wish though: ^#(^
    https://JogAmp.org/deployment/jogamp-next/javadoc/jogl/javadoc/index.html?overview-summary.html

  • WindowJS - cross-mode alert(), confirm(), prompt() & other JS API for Java

    @Chrisir, can you check out whether this Inputs class behaves correctly for all Processing's renderers: :-?
    https://Gist.GitHub.com/GoToLoop/bba0c288aaeeb5ef9bb1

    Aside from its readBoolean() method which directly invokes JOptionPane::showConfirmDialog(), everything else relies on a JDialog instance created outta a customized JOptionPane: :-B

    protected static final JDialog dialog = new JOptionPane(panel, QUESTION_MESSAGE) {
      @Override public void selectInitialValue() {
        field.requestFocusInWindow();
      }
    }
    .createDialog(null, TITLE);
    

    Notice its @Override method invokes method requestFocusInWindow() over a JTextField object. L-)

    Whether that's enough to force Processing's P3D and other renderers to always behave correctly related to foreground placement is your task now. #:-S

    Good luck! B-)

  • WindowJS - cross-mode alert(), confirm(), prompt() & other JS API for Java

    Sorry @Chrisir; but I've never tested it w/ other renderers yet. Just JAVA2D! ~:>

    This library simply invokes JOptionPane's static methods: showMessageDialog(), showConfirmDialog() & showInputDialog().

    Which respectively corresponds to JS' alert(), confirm() & prompt(). ~O)

    Therefore, that is simply a JOptionPane interaction glitch w/ Processing's OpenGL P3D renderer you've just found out AFAIK. :|

    As you can see, JOptionPane is a Swing/AWT class: 8-|
    import static javax.swing.JOptionPane.*;

    And almost n1 knows Processing doesn't behave that well when we use Swing/AWT classes. ^#(^

  • gctrl.pde doesn't work in Mac

    Solved

    JFrame frame = new JFrame("Select the serial port that corresponds to your Arduino board."); String result = (String) JOptionPane.showInputDialog(frame, "Select the serial port that corresponds to your Arduino board.", "Select serial port", JOptionPane.PLAIN_MESSAGE, null, Serial.list(), 0);

    It seems that JFrame must be explicitly stated. Thank you very much to all.

  • gctrl.pde doesn't work in Mac

    Hello:

    I just installed processing on my Mac High Sierra version 10.13.3 and when try to run gctrl.pde does not work. When executing

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

    gives problems in the showInputDialog function.

    Someone could help me?

  • How to let the user select COM (serial) port within a sketch?

    This was perfect except that my Linux box has 32 ports, so mapping to a letter isn't going to happen so easily. I decided to try my hand at Java, and came up with a dropdown list instead.

    Sorry about the code highlighting. I tried highlight-ctrl-o, and the pre-/pre thing, but to no avail. ctrl-t just opened another tab. Apparently wysiwyg isn't what it used to be. The formatting worked after all.

      
    
    // Up near the top
    import javax.swing.JOptionPane; // Had to change this which meant showMessageDialog() changes
    final boolean debugPort = true; 
    
    
    ... 
    
    // in setup()
    
              // Allow user to choose serial port
              String COMx = "";
              try {
                if(debugPort) printArray(Serial.list());
                int numPorts = Serial.list().length;
                 if (numPorts != 0) {
                  if (numPorts >= 2) {
                    COMx = (String) JOptionPane.showInputDialog(null, 
                    "Select COM port", 
                    "Select port", 
                    JOptionPane.QUESTION_MESSAGE, 
                    null, 
                    Serial.list(), 
                    Serial.list()[0]);
            
                    if (COMx == null) exit();
                    if (COMx.isEmpty()) exit();
                  }
                  myPort = new Serial(this, COMx, 9600); // change baud rate to your liking
                  myPort.bufferUntil('\n'); // buffer until CR/LF appears, but not required..
                }
                else {
                  JOptionPane.showMessageDialog(frame,"Device is not connected to the PC");
                  exit();
                }
            
    // Then the rest of setup() because exit() does not exit in Processing until setup() is done.
            
              catch (Exception e)
              { //Print the type of error
                JOptionPane.showMessageDialog(frame,"COM port " + COMx + " is not available (maybe in use by another program)");
                println("Error:", e);
                exit();
              }
    }
    
    
  • How do I change color/customize a JOptionPane window in processing?

    A full example below.

    Kf

    import javax.swing.*;
    import java.awt.Font;
    import java.awt.Color;
    import java.awt.Dimension;
    import javax.swing.UIManager;
    
    void setup() {
    }
    
    void draw() {
    }
    
    void mouseReleased() {
      exit();
    }
    
    void exit() {
    
      UIManager UI=new UIManager();
      UI.put("OptionPane.background", new Color(255, 0, 0));
      UI.put("Panel.background", Color.red);
    
      int choice = JOptionPane.showConfirmDialog(null, "msg", 
        "title", JOptionPane.YES_NO_OPTION);
      //println(choice);
    
    
      if (choice == JOptionPane.YES_OPTION) { 
        println("YES");
      }
    
      if (choice == JOptionPane.NO_OPTION) { 
        println("NO? But WHY?");
      }
    
    
      super.exit();
    }
    
  • please help (seven judges)

    Let's just throw out the second version right now. How can you find the max and min scores if you are only keeping a running total or average? If you aren't recording all the scores, finding the min and max scores will be a pain.

    Looking at the first version, does it seem repetitive to you at all? Does it seem to repeat the same thing a lot? Is it repeating itself? Does it say the same thing in the same way several times? Is it repetitive? Is it repetitive? Is it repetitive? Is it repetitive? Is it repetitive? Is it repetitive? Is it repetitive? Is it repetitive? Is it repetitive? Is it repetitive? Is it repetitive? Is it repetitive? Is it repetitive? Is it repetitive? Is it repetitive? Is it repetitive? Is it repetitive? Is it repetitive?

    This is a good indication that there is (Is it repetitive?) a better way to do things.

    First of all, you have 7 scores. These variables are where you are storing the scores:

    Float FirstFloat;
    Float SecondFloat;
    Float ThirdFloat;
    Float FourthFloat;
    Float FifthFloat;
    Float SixthFloat;
    Float SeventhFloat;
    

    Is this repetitive? Yes. Instead of having a variable that can store one score, and then having seven of those, we can just have one LIST of scores that is seven scores long. This list of variables is commonly called an ARRAY.

    float[] scores; // There is a list of scores.
    scores = new float[7]; // Make space on the list for 7 scores.
    

    Is this repetitive? Yes. We have scores in there twice. We can actually do this on one line:

    float[] scores = new float[7];
    

    Next, look at how you ask for the scores:

    String FirstStr = 
    JOptionPane.showInputDialog("Enter a number: ");
    FirstFloat = Float.parseFloat(FirstStr);
      if(FirstFloat < 1 || FirstFloat > 10)
        JOptionPane.showMessageDialog (null, "Error: Number input is invalid.");
    
    String SecondStr = 
    JOptionPane.showInputDialog("Enter a number: ");
    SecondFloat = Float.parseFloat(SecondStr);
      if(SecondFloat < 1 || SecondFloat > 10)
        JOptionPane.showMessageDialog (null, "Error: Number input is invalid.");
    
    String ThirdStr = 
    JOptionPane.showInputDialog("Enter a number: ");
    ThirdFloat = Float.parseFloat(ThirdStr);
    // ... AND SO ON...
    

    Is this repetitive? Very yes. You could use a LOOP here to do the same thing many times. Since you want exactly as many scores as there are space for in the list, we can use a for loop to ask for each score:

    for( int i = 0; i < scores.length; ){
      String resultStr = JOptionPane.showInputDialog("Enter a number: ");
      scores[i] = Float.parseFloat(resultStr);
      if(scores[i] < 1 || scores[i] > 10){
        JOptionPane.showMessageDialog (null, "Error: Number input is invalid.");
      } else {
        i++;
      }
    }
    

    Now that you have the scores in an array, you can sort them much easier, as GoToLoop has already shown you. Once they are sorted, it is a simple matter to sum up the middle five scores and then computer the average of them.

  • please help (seven judges)
    // Import the library necessary to obtain user input and provide an error message
        import javax.swing.*;
    
        // Define the global variables
        String FirstString;
        Float FirstInteger;
        String OtherString;
        Integer OtherInteger;
        Float Average = 0.0;
    
    
              do {  // do
              FirstString = JOptionPane.showInputDialog ("Enter a number: "); // Prompt the user and obtain a value as a string
              FirstInteger = Float.parseFloat(FirstString); // Convert the string to an integer
                if ((FirstInteger < 7) || (FirstInteger > 7)) // IF the converted value is not valid
                  JOptionPane.showMessageDialog (null,"ERROR: Number is invalid."); // Provide an error message
              } while ((FirstInteger < 7) || (FirstInteger > 7)); // while the converted value is not valid
    
            for (int NewNum = 1; NewNum <= FirstInteger; NewNum++) {  
              do {  // do
              OtherString = JOptionPane.showInputDialog ("Enter a number " + NewNum +": "); // Prompt the user and obtain a value as a string
              OtherInteger = Integer.parseInt(OtherString); // Convert the string to an integer
                if ((OtherInteger < 1) || (OtherInteger > 10)) // IF the converted value is not valid
                  JOptionPane.showMessageDialog (null,"ERROR: Number is invalid."); // Provide an error message
              } while ((OtherInteger < 1) || (OtherInteger > 10)); // while the converted value is not valid 
              Average += OtherInteger;
    
          } // for
          Average /= FirstInteger;
          JOptionPane.showMessageDialog (null, "Average is " + Average);
    
        exit() ;
    
  • please help (seven judges)
        import javax.swing.*;
    
        Float FirstFloat;
        Float SecondFloat;
        Float ThirdFloat;
        Float FourthFloat;
        Float FifthFloat;
        Float SixthFloat;
        Float SeventhFloat;
    
        // Input first number
        String FirstStr = 
        JOptionPane.showInputDialog("Enter a number: ");
        FirstFloat = Float.parseFloat(FirstStr);
          if(FirstFloat < 1 || FirstFloat > 10)
            JOptionPane.showMessageDialog (null, "Error: Number input is invalid.");
    
        String SecondStr = 
        JOptionPane.showInputDialog("Enter a number: ");
        SecondFloat = Float.parseFloat(SecondStr);
          if(SecondFloat < 1 || SecondFloat > 10)
            JOptionPane.showMessageDialog (null, "Error: Number input is invalid.");
    
        String ThirdStr = 
        JOptionPane.showInputDialog("Enter a number: ");
        ThirdFloat = Float.parseFloat(ThirdStr);
          if(ThirdFloat < 1 || ThirdFloat > 10)
            JOptionPane.showMessageDialog (null, "Error: Number input is invalid.");
    
        String FourthStr = 
        JOptionPane.showInputDialog("Enter a number: ");
        FourthFloat = Float.parseFloat(FourthStr);
          if(FourthFloat < 1 || FourthFloat > 10)
            JOptionPane.showMessageDialog (null, "Error: Number input is invalid.");
    
        String FifthStr = 
        JOptionPane.showInputDialog("Enter a number: ");
        FifthFloat = Float.parseFloat(FifthStr);
          if(FifthFloat < 1 || FifthFloat > 10)
            JOptionPane.showMessageDialog (null, "Error: Number input is invalid.");
    
        String SixthStr = 
        JOptionPane.showInputDialog("Enter a number: ");
        SixthFloat = Float.parseFloat(SixthStr);
          if(SixthFloat < 1 || SixthFloat > 10)
            JOptionPane.showMessageDialog (null, "Error: Number input is invalid.");
    
        String SeventhStr = 
        JOptionPane.showInputDialog("Enter a number: ");
        SeventhFloat = Float.parseFloat(SeventhStr);
          if(SeventhFloat < 1 || SeventhFloat > 10)
            JOptionPane.showMessageDialog (null, "Error: Number input is invalid.");
    
    
    
        // Calculate the average of the five middle scores
        float avg = (FirstFloat + SecondFloat + ThirdFloat + FourthFloat + FifthFloat + SixthFloat +
        SeventhFloat) / 5.0;
    
        // Output average
        JOptionPane.showMessageDialog (null, "The average of the middle scores is " + avg );
    
        // Quit the sketch
        exit();
    
  • Accepting user input for visual assignment

    first post here so bear with me :P

    Now I'm not a programmer by trade, but my university offers a programming unit related to digital arts using processing. An assignment I'm working on requires the user to input an integer value which is then used to create a range for randomization. Ideally the output should look like a bunch of random high-rises, creating a city skyline (abstract art don't question it) with 5 "high-rises". However, only one is appearing and the GUI appears again. Any help would be much appreciated as I'm at wits end with my deadline approaching fast :|

    import static javax.swing.JOptionPane.*; //GUI element class

    void setup() { //setup canvas size(1250,750); //sets size of canvas

    frameRate(10);

    }

    void draw(){

        String input = showInputDialog("Type in integer number...");
        int num = parseInt(input == null? "" : input, MIN_INT);
    
        if (input == null)  showMessageDialog(null, "You didn't enter anything!", "Alert", ERROR_MESSAGE);
        else if (num == MIN_INT)  showMessageDialog(null, "Entry \"" + input + "\" isn't a number!", "Alert", ERROR_MESSAGE);
        else showMessageDialog(null, "Number " + num + " has been registered.", "Info", INFORMATION_MESSAGE);
    
    
    
    for(int i = 0 ; i < 5 ; i++) {
    
    
    
    
      background(random(125,175),random(125,175),random(125,175));  //sets colour of canvas, ideally in rgb
    
      fill (random (150,255));
    
      float X = random(num,num+400);
      float Y = random(num,num+450);
    
      rect(X,Y,150,750);
    
    }
    
  • Why can't I get the option pane to show.

    Try this change in line 31:

    String result = (String) JOptionPane.showInputDialog(frame,

    Also I will review the design of your code as line 21 might be unnecessary and potentially problematic.

    Kf

  • Why can't I get the option pane to show.

    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