Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Question on using JFrames and ActionListeners

  1. #1
    Member
    Join Date
    Dec 2012
    Location
    Detroit Mi
    Posts
    125
    My Mood
    Nerdy
    Thanks
    14
    Thanked 0 Times in 0 Posts

    Default Question on using JFrames and ActionListeners

    Below is my assignment just to give you idea what I'm working on.

    CSC 275 Assignment 6
    Instructor: Joshua L. Smith
    Question Subject Line: CSC 275 Assignment 6 Question
    Answer Subject Line: CSC 275 Assignment 6 Solution
    After a huge success selling our flower packs to local shops we’ve acquired enough money to replace all of our items and had plenty left over to leave Alexander and Elizabeth so that they can hire a doctor to travel in and hopefully help Elizabeth recover. Things have been happening very quickly and we haven’t had much time to process what we’ve accomplished, so here’s a little recap of everything we’ve done since we started our journey.
    Created a basic flower pack that can add and remove (using arrays) – Assignment 1
    Searched through the flower pack. – Assignment 1
    Sorted the flower pack. – Assignment 1
    Created a flower object to hold attributes of each flower. – Assignment 2
    Upgraded our flower pack (to now use an ArrayList) – Assignment 3
    Filter the flower pack based on a partial search. – Assignment 3
    Upgraded our flower pack (to now hold multiple different types of plants) – Assignment 4
    Saved and Loaded information to/from a file. – Assignment 5
    *This list does not include information or tasks specific to labs

    Several days after we’ve left and have been restarted the journey which we began so long ago we come to another small town that looks like a great place to stay for the night. The first thing we do, and have always done, is look for an inn. After we find what looks like the best inn we’ve ever seen and reserve our room we head to the tavern to socialize and hopefully find someone that catches our eye. After sitting at the bar for a bit a nice older lady comes up to us and starts a simple conversation. During this, we discover that she is the owner of the small flower shop on the corner (what are the chances!). We politely tell her about our system that we’ve developed, but sadly she isn’t interested. The bar tended overhears our conversation and when the lady leaves he comes over to ask us more about our system.

    The next morning we wake up in our room and look to our night stand where there is a candle that apparently burned the entire night and is hanging on to the last bit of light that it can produce. Below the candle we notice a contact with what could only be construed as our signature on the bottom. What did we agree to last night??

    After reading the contract it appears that we’ve agreed to create a flower pack for the bartended to use. The bar tender hopes to take our system that we’ve created, make copies and sell as many as he can to rebuild the home that he lost in a fire a long time ago. There is a drawing on the first page with what appears to be some sort of interface, but it can’t be interpreted in any meaningful way.





    Here’s our task for the week, since violating a contract results in death, we have no option but to finish.

    Create an interface for the user to add, remove, sort, filter, save and load information from our flower pack.
    You should use all of the following at least once in your interface
    JFrame
    JButton
    JLabel
    JTextField
    JCheckBox
    Layout (you can use any layout found in the lecture or book)
    JMenu
    JMenuItem

    The flower pack should hold flowers, weeds, fungus, and now herbs. All should be a subclass of a plant class.
    Each subclass shares certain qualities (ID, Name, and Color)
    Flower traits include (Thorns, and Smell)
    Fungus traits include (Poisonous)
    Weed traits include (Poisonous, Edible and Medicinal)
    Herb traits include (Flavor, Medicinal, Seasonal)


    Here is my actual code below


     
    import javax.swing.JLabel;
    import javax.swing.JFrame;
    import javax.swing.JCheckBox;
    import javax.swing.JMenu;
    import javax.swing.JButton;
    import javax.swing.*;
    import java.awt.*;
     
     
     
    public class GuiShell extends JFrame 
    {
           public GuiShell()
           {
     
     
            JFrame newFrame = new JFrame();
            newFrame.setTitle(" Plant Application ");
            newFrame.setSize(600,600);
            newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            newFrame.setLocationRelativeTo(null);
            newFrame.setVisible(true);        
     
            JMenuBar jmb = new JMenuBar();
            newFrame.setJMenuBar(jmb);
     
            JMenu file = new JMenu(" File");
            jmb.add(file);  
     
            JMenuItem open1 = new JMenuItem( " Load file.... ");
            file.add(open1);
     
            JMenuItem open2 = new JMenuItem( " Save file.... ");
            file.add(open2);        
     
            JMenuItem open3 = new JMenuItem( " Close ");
            file.add(open3);    
     
            JPanel p1 = new JPanel();
            p1.setLayout(new GridLayout(4,3));
     
            JButton addItem = new JButton(" Add Items");
            p1.add(addItem);
            JButton removeItem = new JButton(" Remove Items");
            p1.add(removeItem);
            JButton searchItem = new JButton(" Search Items");
            p1.add(searchItem);
            JButton displayItem = new JButton(" Display Items");
            p1.add(displayItem);        
            JButton filterItem = new JButton(" Filter Items");
            p1.add(filterItem);        
            JButton addLoadItem = new JButton(" Save/Load File");
            p1.add(addLoadItem);        
     
            newFrame.add(p1);
     
            JPanel p2 = new JPanel( new BorderLayout() );
            DefaultListModel listModel = new DefaultListModel();
            JList test = new JList (listModel);
            p2.add( test , BorderLayout.CENTER);
            test.setVisibleRowCount(50);
            test.setFixedCellHeight(15);
            test.setFixedCellWidth(100);
            p2.add(new JLabel(" Hello User Welcome!  Below is the item window and option buttons. "), BorderLayout.NORTH);
            p2.add(p1, BorderLayout.SOUTH);
     
            newFrame.add(p2);
     
     
          }
    }


    My question is can I use my JFrame buttons in the MAIN method? What I want to do is have the actionlisteners as well as my additional code(that's already written) be run in the main method i.e if I click my add item button it will allow me to create an item using that button from other JFrame. I really just really want my shell or gui be another class so I can use my code more efficiently. I hope that make sense. If you need clarification on what I mean please let me know. FYI my other code will be listed below as well


     
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
     
    public class Assignment5 
    {
        public static void main( String[] args) throws IOException
        {
           new Assignment5();
     
        }
     
     
        public Assignment5() throws IOException
        {
         Scanner input = new Scanner(System.in);
         ArrayList<Plantclass> plantPack = new ArrayList<Plantclass>();
     
        System.out.println("Welcome to my plant pack application.");
        System.out.println("Please select a options below");
        System.out.println("");
     
     
        while (true) 
        {
         // Give the user a list of their options
         System.out.println("1: Add an item to the pack.");
         System.out.println("2: Remove an item from the pack.");
         System.out.println("3: Search for a plant.");
         System.out.println("4: Display the plant in the pack.");
         System.out.println("5: Filter plant pack by incomplete name.");
         System.out.println("6: Add/Load a plant file.  ");
         System.out.println("0: Exit the plant pack interface.");
         System.out.print( "Answer:");
         // Get the user input
         int userChoice = input.nextInt();
     
         switch (userChoice) 
         {
                case 1:
                    addPlant(plantPack);
                    break;
                case 2:
                    removePlant(plantPack);
                    break;
                case 3:
                    searchPlant(plantPack);
                    break;
                case 4:
                    displayPlant(plantPack);
                    break;
                case 5:
                    filterPlant(plantPack);
                    break;
                case 6:
                    saveOrLoadPlant(plantPack);
                    break;
                case 0:
                    System.out.println("Thank you for using the flower pack interface. See you again soon!");
                    System.exit(0);
          }
        } 
     
        }
     
     
     
     
        public void addPlant( ArrayList<Plantclass> plantPack)
        {
           String iD,name,color,smell,thorns,poisonous,edible,medicinal;
     
           Scanner scan = new Scanner(System.in);
           Plantclass test = new Plantclass();
     
           System.out.println( "Hello please make a selection. ");
           System.out.println( "Option 1: Add Flower ");
           System.out.println( "Option 2: Add Fungus ");
           System.out.println( "Option 3: Add Weed ");
           System.out.print(  "Answer:");
           int ans = scan.nextInt();
     
           switch(ans)
           {
               case 1:                         
               System.out.print( " Please enter your ID number for your flower.");
               iD = scan.next();
     
               System.out.print( " Please enter the name of your flower. ");
               name = scan.next();
     
               System.out.print(" Please enter the color of your color. ");
               color = scan.next();
     
               System.out.print( " Is there any thorns? (Yes/No) ");
               thorns = scan.next();
     
               System.out.print( " Is there a smell? (Yes/No) ");
               smell = scan.next();
     
               Flower newFlower = new Flower(iD, name,color, thorns, smell );
     
               plantPack.add(newFlower);
               System.out.println();
               break;
     
               case 2:
               System.out.print( " Please enter your ID number for your flower.");
               iD = scan.next();
     
               System.out.print( " Please enter the name of your Fungus. ");
               name = scan.next();
     
               System.out.print( " Please enter the color of your Fungus. ");
               color = scan.next();
     
               System.out.print( " Is it poisonous? (Yes/No) ");
               poisonous = scan.next();           
     
               Fungus newFungus = new Fungus(iD, name,color, poisonous );
     
               plantPack.add(newFungus);
               System.out.println();
               break;
     
               case 3:
               System.out.print( " Please enter your ID number for your ID.");
               iD = scan.next();
     
               System.out.print( " Please enter the name of your weed. ");
               name = scan.next();
     
               System.out.print( " Please enter the color of your weed. ");
               color = scan.next();
     
               System.out.print( " Is it poisonous? (Yes/No) ");
               poisonous = scan.next();   
     
               System.out.print( " Is it edible? (Yes/No) ");
               edible = scan.next();   
     
               System.out.print( " Is it used for medicinal? (Yes/No) ");
               medicinal = scan.next(); 
     
               Weed newWeed = new Weed(iD, name, color, poisonous, edible, medicinal);
     
               plantPack.add(newWeed);
               System.out.println();
               break;           
     
     
     
     
           }
     
        }
     
     
         private void removePlant(ArrayList<Plantclass> plantPack) 
        {
     
            Scanner scan = new Scanner(System.in);
            String s;
     
     
            System.out.println( " Please enter the plant name you would like to remove. ");
            System.out.print(" Ans:");
            s = scan.next();
     
     
            for(int i = 0; i < plantPack.size(); i++)  
           {
             Plantclass removePlant = plantPack.get(i);
     
             if(removePlant.getName().equalsIgnoreCase(s))
             { 
               plantPack.remove(i);
               break;
             } 
     
           }
     
        }
     
     
        private void displayPlant(ArrayList<Plantclass> plantPack) 
        {
            System.out.println();
            for(int i = 0; i < plantPack.size(); i++)
            {
            System.out.println(plantPack.get(i));
     
            }
            System.out.println();
        }
     
     
     
        public void searchPlant(ArrayList<Plantclass> plantPack)
        {
            Scanner scan = new Scanner(System.in);
     
            System.out.println(" Please search for the plant you would to search for. ");
            System.out.print(" Ans:");
            String stringAns = scan.next();
     
            boolean FlagAns = false;
     
     
            for(int i = 0; i < plantPack.size(); i++)
            {
                Plantclass newPlantPack = plantPack.get(i);
     
                if( newPlantPack.getName().equalsIgnoreCase(stringAns) )
                {
                    FlagAns = true;
                    break;
                }
     
            }
     
     
     
            if(FlagAns)
            {
             System.out.println(" Yes! " + stringAns + " is in the pack of plants."); 
            }
            else
            {
             System.out.println(" Sorry! " + stringAns + " is not in the pack of plants.");    
            }
     
     
        }
     
     
        public void filterPlant(ArrayList<Plantclass> plantPack)
        {
            Scanner scan = new Scanner(System.in);
            String keyWord;
            boolean checkAns = false;
     
            System.out.println(" Please enter the character or word your would like to search for.");
            System.out.println(" This application will search through the list for your result. ");  
            System.out.print(" Ans:");        
            keyWord = scan.nextLine();
     
     
            for(int i = 0;  i < plantPack.size(); i++)
            {
                Plantclass newPlantPack = plantPack.get(i);
     
                if(newPlantPack.getName().contains(keyWord))
                {
                    System.out.println();
                    System.out.println(" " +newPlantPack.getName());
                    checkAns = true;
                }
     
            }
     
            if(checkAns == false)
            {
              System.out.println( " Sorry user, but are database could not any results."); 
            }
     
            if(checkAns == true)
            {
              System.out.println( " Above is the queer of results we located.");
            }
            System.out.println("");
     
        }
     
     
     
        public void saveOrLoadPlant(ArrayList<Plantclass> plantPack) throws IOException
        {
     
            Scanner scan = new Scanner(System.in);
     
     
            System.out.println(" Option 1: Would like to SAVE your file? ");
            System.out.println(" Option 2: Would like to LOAD a file? ");
            System.out.print( " answer:");
            int i = scan.nextInt();
     
     
            Plantclass testjr = new Plantclass();
     
           if(i == 1)
           {
     
     
                   File file = new File("C:/Users/gshavers/Desktop/plantFile.txt ");
                   FileOutputStream outFileStream  = new FileOutputStream(file);
                   PrintWriter outStream = new PrintWriter(outFileStream);           
     
     
                   for(int x = 0; x < plantPack.size(); x++)
                   {
     
                      outStream.println(plantPack.get(x));
     
                   }
                   System.out.println();
     
                   System.out.println(" File created.....PLEASE check your desktop for plantFile.txt.");
                   System.out.println(); 
                   outStream.close();
     
     
     
           }
     
     
           if(i == 2)
           {
     
              String iD,name,color,smell,thorns,poisonous,edible,medicinal;  
     
              JFileChooser fileChooser = new JFileChooser();
     
              if( fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
               {
                   File file = fileChooser.getSelectedFile();
                   Scanner input = new Scanner(file);
     
     
     
                   while(input.hasNext())
                   {
                       String test = input.nextLine();
                       StringTokenizer st = new StringTokenizer(test);   
                       int count = st.countTokens();
     
                      if(count == 4)//fungus object
                      {
     
                          iD= st.nextToken();
                          name = st.nextToken();
                          color = st.nextToken();
                          poisonous = st.nextToken();    
     
                          Fungus newFungus = new Fungus( iD, name, color, poisonous);
     
                          plantPack.add(newFungus);
     
                      }
     
                        if(count == 5)//flower object
                      {
                          iD = st.nextToken();
                          name = st.nextToken();
                          color = st.nextToken();
                          thorns = st.nextToken();
                          smell = st.nextToken();
     
                          Flower newFlower = new Flower(iD, name, color, thorns, smell);
                          plantPack.add(newFlower);
                      }
     
                      if(count == 6){//weed object
     
                          iD = st.nextToken();
                          name = st.nextToken();
                          color = st.nextToken();
                          poisonous = st.nextToken();
                          edible = st.nextToken();
                          medicinal = st.nextToken();
     
                          Weed newWeed = new Weed(iD,name,color,poisonous,edible,medicinal);
                          plantPack.add(newWeed);
                      }
     
     
                      }
     
     
                      System.out.println(" File has beeen uploaded.");
                      System.out.println();      
     
     
     
                   input.close();  
                   }
                   System.out.println();
     
              }     
     
     
     
     
     
     
     
     
     
            }
     
     
     
     
     
     
     
     
           }
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
    	Plantclass
     
    public class Plantclass
    {
       public String ID;
       public String Name;
     
     
       public Plantclass()
       {
     
       }
     
     
       public Plantclass(String SetID, String SetName)
       {
           ID = SetID;
           Name = SetName;
     
       }
     
       public void setId(String setId)
       {
           ID = setId;
     
       }
     
       public String getId()
       {
           return ID;
     
       }
     
       public void setName(String setName)
       {
           Name = setName;
     
       }
     
       public String getName()
       {
           return Name;
     
       }
     
     
    }
     
     
    	Flower class
     
    public class Flower extends Plantclass
    {
        public String color;
        public String thorns;
        public String smell;
        public String setIdJr;
        public String setNameJr;
     
       public Flower()
       {
     
       }
     
     
        public Flower(String SetID, String SetName, String color, String thorns, String smell)
        {
           super(SetID,SetName);  
           this.color = color;
           this.thorns  = thorns;
           this.smell = smell;
           setIdJr = SetID;
           setNameJr = SetName;
     
        }
     
        public void setColor(String color)
        {
            this.color = color;
        }
     
     
        public void setThorns(String thorns)
        {
          thorns  = thorns;
        }
     
     
        public void setSmell(String smell)
        {
            this.smell = smell;
        }
     
        public String getColor()
        {
            return color;
        }
     
        public String getThorns()
        {
            return thorns;
        }
     
         public String getSmell()
        {
            return smell;
        }
     
     
         public String toString()
        {
            return setIdJr + " " + setNameJr + " " +  color + " "  + thorns + " " + smell;
     
        }
     
     
    }
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
    	Fungus class
     
    public class Fungus extends Plantclass
    {
        public String color;
        public String poisonous;
        public String setIdJr;
        public String setNameJr;
     
        public Fungus()
       {
     
       }    
     
        public Fungus(String SetID, String SetName, String color, String poisonous)
        {
           super(SetID,SetName);  
           this.color = color;
           this.poisonous = poisonous;
           setIdJr = SetID;
           setNameJr = SetName;
        }
     
        public void setColor(String color)
        {
            this.color = color;
        }
     
     
        public void setPoisonous(String poisonous)
        {
            this.poisonous = poisonous;
        }
     
     
        public String getColor()
        {
            return color;
        }
     
        public String getPoisonous()
        {
            return poisonous;
        }
     
     
         public String toString()
        {
            return setIdJr + " " + setNameJr + " " +  color + " "  + poisonous;
     
        }
     
     
    }
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
    	Weed class
     
     
    public class Weed extends Plantclass
    {
     
        public String color;
        public String poisonous;
        public String edible;
        public String medicinal;
        public String setIdJr;
        public String setNameJr;
     
        public Weed()
        {
     
        }
     
        public Weed(String SetID, String SetName, String color, String poisonous, String edible, String medicinal)
        {
           super(SetID,SetName);  
           this.color = color;
           this.poisonous = poisonous;
           this.edible = edible;
           this.medicinal = medicinal;
           setIdJr = SetID;
           setNameJr = SetName;
     
        }
     
        public void setColor(String color)
        {
            this.color = color;
        }
     
        public void setPoisonous(String poisonous)
        {
            this.poisonous = poisonous;
        }
     
         public void setEdible(String edible)
        {
            this.edible = edible;
        }
     
        public void setmedicinal(String medicinal)
        {
            this.medicinal = medicinal;
        }
     
     
        public String getColor()
        {
            return color;
        }
     
        public String getPoisonous()
        {
            return poisonous;
        }
     
         public String setEdible()
        {
            return edible;
        }
     
          public String setMedicinal()
        {
            return medicinal;
        }
     
        public String toString()
        {
            return setIdJr + " " + setNameJr + " " +  color + " "  + poisonous + " " + edible + " " +  medicinal;
     
        }
     
     
     
     
    }


  2. #2
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Question on using JFrames and ActionListeners

    Quote Originally Posted by Rain_Maker View Post
    My question is can I use my JFrame buttons in the MAIN method? What I want to do is have the actionlisteners as well as my additional code(that's already written) be run in the main method i.e if I click my add item button it will allow me to create an item using that button from other JFrame.
    The main method is running a loop which will repeatedly prompt the user (forever or until 0 or exception) for input. Buttons work in a different manner. I am not 100% sure I understand what you are asking, but close... and if so the answer is no. You can not have the thread tied up waiting on input from the loop in main and respond to a button click. Please do explain better exactly what you mean with the quoted text above to get more clarification on what you can and can not get away with

  3. #3
    Member
    Join Date
    Dec 2012
    Location
    Detroit Mi
    Posts
    125
    My Mood
    Nerdy
    Thanks
    14
    Thanked 0 Times in 0 Posts

    Default Re: Question on using JFrames and ActionListeners

    okay,

    I ended up just just using the GUIShell class. I do have another question. I'm trying to print a list of objects. I want to have a list of object printed on my JLabel. Is this possible? Right now I have a JList....I was going to use it to print on my JLabel. Can I do this?

  4. #4
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Question on using JFrames and ActionListeners

    What happened when you tried it?

  5. #5
    Member
    Join Date
    Dec 2012
    Location
    Detroit Mi
    Posts
    125
    My Mood
    Nerdy
    Thanks
    14
    Thanked 0 Times in 0 Posts

    Default Re: Question on using JFrames and ActionListeners

    Well that's thing I didn't lol I don't know what to do it.. lol.....A light bub did come up in my heard when I was trying to figure it out. I realize I don't need to use a jList. I just need to have my plantobject print on my Jlabel.

  6. #6
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Question on using JFrames and ActionListeners

    Well give it a try and post what you have when you get stuck. Members on the forum are always happy to offer suggestions

  7. #7
    Member
    Join Date
    Dec 2012
    Location
    Detroit Mi
    Posts
    125
    My Mood
    Nerdy
    Thanks
    14
    Thanked 0 Times in 0 Posts

    Default Re: Question on using JFrames and ActionListeners

    okay will do thanks again jps

Similar Threads

  1. Learning ActionListeners, help please.
    By Smelnick in forum AWT / Java Swing
    Replies: 4
    Last Post: November 20th, 2013, 09:58 AM
  2. Connecting Two Different ActionListeners
    By steme in forum Java Theory & Questions
    Replies: 1
    Last Post: April 26th, 2013, 08:35 AM
  3. How to use multiple actionlisteners
    By pottsiex5 in forum AWT / Java Swing
    Replies: 9
    Last Post: November 19th, 2011, 08:37 AM
  4. [SOLVED] Quick question regarding ActionListeners
    By Stockholm Syndrome in forum Java Theory & Questions
    Replies: 2
    Last Post: October 4th, 2011, 12:02 PM
  5. [SOLVED] NullPointerException on ActionListeners
    By cherryduck in forum What's Wrong With My Code?
    Replies: 2
    Last Post: December 7th, 2010, 03:17 PM