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 19 of 19

Thread: Trying to loop actionListeners together for 56 JButton objects to reduce code size

  1. #1
    Junior Member
    Join Date
    Jul 2018
    Posts
    14
    Thanks
    7
    Thanked 9 Times in 9 Posts

    Default Trying to loop actionListeners together for 56 JButton objects to reduce code size

    Hi, can someone help me understand what I need to do to reduce my code size so I won't need 56 separate methods to add all of my actionListeners for a JButton array? I'll just include smaller chunks of my code since the full set is about 800 lines. Any help is much appreciated & this is not for any homework assignment. I genuinely enjoy writing code.

    Here's what the code does: It's a map making application which uses an array of default JButtons as the 'map' which can be edited by clicking from sample JButtons on a side panel. It's essentially a palette of MS Paint .pngs I created which you can click on the map with to alter their state. I use it to draw dungeons in video games, but you could reconfigure it to be let's say, a chess board. If anyone would like to see the code in it's entirety, I can share more.

    variable creation & import statements:

    /*Created by John Thrush 06/25/18
       WizMapMaker is a video game supplement
    	that works as a drawing tool. The application creates
       an array of buttons which the user can toggle to 
       paint images from a side panel.
    */
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
     
    public class WizMapMakerEdit extends JFrame 
    {
       private final static int ROWS = 27;
    	private final static int COLS = 32; 
       private JPanel outerPane = new JPanel();
       private JPanel gridPane = new JPanel();
       private JPanel innerPane = new JPanel();
       private JPanel optionsPane = new JPanel();
       private JPanel samplePane = new JPanel();
    	private JButton tiles[][];
       private JButton oButtons[];
       private String oButtonNames[];
       //add new buttons: PLACE NEW ITEM HERE - STEP 1
    	private JButton floor = new JButton("");
       private JButton wallFill = new JButton("");
    ....

    More variables.. see the commented for loop. That's what I'm trying to figure out.
    private JLabel previewLabel= new JLabel();
       private JLabel buttonLabel = new JLabel("");
       private ReportClick handler = new ReportClick();
       private GridLayout gl = new GridLayout(12,5);
       private GridLayout bl = new GridLayout(ROWS,COLS);
       private GridLayout sl = new GridLayout(1,1);   
       private DefaultListCellRenderer dr = new DefaultListCellRenderer();
     
    	public WizMapMakerEdit(String title)
       {   
           //set a title & min size for outer frame
           super(title);
           setMinimumSize(new Dimension(1800, 985));
     
    		 //add components to panels 
           tiles = new JButton[ROWS][COLS];
           dr.setHorizontalAlignment(DefaultListCellRenderer.CENTER);
           previewLabel.setIcon(new ImageIcon(getClass().getResource("Floor.png"))); 
           addOptions();       
           //add new button listeners: PLACE NEW ITEM HERE - STEP 2
     
           for(int m=0; m<56; m++)
           {
             oButtons[m].addActionListener(new ActionListener()
             {
               public void actionPerformed(ActionEvent e)
               {
                 // change the icon displayed when button is pressed
                 previewLabel.setIcon(new ImageIcon(getClass().getResource(oButtonNames[m])));
               }
             }
             );
           }/*
     
           for(int i=0; i<56; i++)
         {
           oButtons[i].setIcon(new ImageIcon(getClass().getResource(oButtonNames[i])));
           optionsPane.add(oButtons[i]);
         }
     
    		 floor.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 // change the icon displayed when button is pressed
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("Floor.png")));
              }
           }
           );
     
           wallFill.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 // change the icon displayed when button is pressed
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("WallFill.png")));
              }
           }
           );*/

    This chunk is where I have about 56 repeated code for each of the JButtons. It's highly inefficient- I know there is a better way..

     
    floor.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 // change the icon displayed when button is pressed
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("Floor.png")));
              }
           }
           );

    Here's where the button array is configured:

     
    private void buildButtons()
       {
         for(int i=0; i < ROWS; i++)
         {
            for(int j=0; j < COLS; j++)
            {
               tiles[i][j] = new JButton();
    			  tiles[i][j].addActionListener(handler);
               tiles[i][j].setSize(300,300);  
    			  tiles[i][j].add(buttonLabel);
    			  gridPane.add(tiles[i][j]);
            }
         }
       } 
       //add new images to options: PLACE NEW ITEM HERE - STEP 3  
       private void addOptions()
       {
         JButton oButtons[] = new JButton[] {floor, wallFill, cornerNW, cornerSW, cornerNE, cornerSE,
         wallN, wallS, wallW, wallE, bumpNW, bumpNE, bumpSW, bumpSE, doorN, doorS, doorW, 
         doorE, capN, capS, capW, capE, hallH, hallV, StairsUp, StairsDown, EVator, WarpIn,
         WarpOut, Pool, Pit, SPit, Shaft, SShaft, Spinner, Darkness, Boss, Event, NPC, 
         NPCPatrol, LockDoorN, LockDoorS, LockDoorW, LockDoorE, SDoorN, SDoorS, SDoorW, SDoorE, 
         FWallN, FWallS, FWallW, FWallE, OneDoorN, OneDoorS, OneDoorW, OneDoorE};
     
         String[] oButtonNames = new String[] {"floor.png", "wallFill.png", "cornerNW.png", "cornerSW.png", "cornerNE.png", "cornerSE.png",
         "wallN.png", "wallS.png", "wallW.png", "wallE.png", "bumpNW.png", "bumpNE.png", "bumpSW.png", "bumpSE.png", "doorN.png", "doorS.png", "doorW.png",
         "doorE.png", "capN.png", "capS.png", "capW.png", "capE.png", "hallH.png", "hallV.png", "StairsUp.png", "StairsDown.png", "EVator.png", "WarpIn.png", 
         "WarpOut.png", "Pool.png", "Pit.png", "SPit.png", "Shaft.png", "SShaft.png", "Spinner.png", "Darkness.png", "Boss.png", "Event.png", "NPC.png", 
         "NPCPatrol.png", "LockDoorN.png", "LockDoorS.png", "LockDoorW.png", "LockDoorE.png", "SDoorN.png", "SDoorS.png", "SDoorW.png", "SDoorE.png",
         "FWallN.png", "FWallS.png", "FWallW.png", "FWallE.png", "OneDoorN.png", "OneDoorS.png", "OneDoorW.png", "OneDoorE.png"};
     
         for(int i=0; i<56; i++)
         {
           oButtons[i].setIcon(new ImageIcon(getClass().getResource(oButtonNames[i])));
           optionsPane.add(oButtons[i]);
         }
         optionsPane.add(erase);
       }

    Again, thanks for any assistance on this! The error I get says something about an inner class in the loop. I'm assuming I have some recursion going on.

    B1F_Map_Wizardry5.jpg
    Last edited by Sizzlewump; July 19th, 2018 at 02:53 PM. Reason: Including an image

  2. The Following User Says Thank You to Sizzlewump For This Useful Post:


  3. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Trying to loop actionListeners together for 56 JButton objects to reduce code size

    error I get says something about an inner class
    Please copy the full text of the error message and paste it here. It has important info about the error.

    When there is a bunch of repeated code, often it can be reduced to a method that is called with the unique bits for each repeated bit of code.
    An idea would be to have an array to hold references to an instance of a class holds references to the component and the image
    For example, given this code:
    floor.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 // change the icon displayed when button is pressed
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("Floor.png")));
              }
           }
           );
    Define a class with a reference to the component (floor) and the String for the image file: "Floor.png".
    If you don't understand my answer, don't ignore it, ask a question.

  4. The Following 2 Users Say Thank You to Norm For This Useful Post:

    Sizzlewump (July 25th, 2018)

  5. #3
    Junior Member
    Join Date
    Jul 2018
    Posts
    14
    Thanks
    7
    Thanked 9 Times in 9 Posts

    Default Re: Trying to loop actionListeners together for 56 JButton objects to reduce code size

    WizMapMakerEdit.java:110: error: local variables referenced from an inner class must be final or effectively final
                 previewLabel.setIcon(new ImageIcon(getClass().getResource(oButtonNames[m])));
                                                                                        ^
    1 error

    This is the message I'm not understanding. It's from the 8th line in this code:

      for(int m=0; m<56; m++)
           {
             oButtons[m].addActionListener(new ActionListener()
             {
               public void actionPerformed(ActionEvent e)
               {
                 // change the icon displayed when button is pressed
                 previewLabel.setIcon(new ImageIcon(getClass().getResource(oButtonNames[m])));
               }
             }
             );
           }/*

  6. The Following User Says Thank You to Sizzlewump For This Useful Post:


  7. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Trying to loop actionListeners together for 56 JButton objects to reduce code size

    The value of m will have changed (actually lost when the loop exits) when that setIcon() method is called.

    This might work:
          for(int m=0; m<56; m++)
           {
             String tempName = oButtonNames[m];     
             oButtons[m].addActionListener(new ActionListener()
             {
               String theName = tempName;     //  save the name in a variable in the anonymous class
               public void actionPerformed(ActionEvent e)
               {
                 // change the icon displayed when button is pressed
                 previewLabel.setIcon(new ImageIcon(getClass().getResource(theName))); 
               }
             }
             );
           }

    Another way would be to save the reference in the oButtons element using the clientProperties put/get methods
    and then get the reference to the oButton object from the source of the ActionEvent.
    If you don't understand my answer, don't ignore it, ask a question.

  8. The Following 2 Users Say Thank You to Norm For This Useful Post:

    Sizzlewump (July 25th, 2018)

  9. #5
    Junior Member
    Join Date
    Jul 2018
    Posts
    14
    Thanks
    7
    Thanked 9 Times in 9 Posts

    Default Re: Trying to loop actionListeners together for 56 JButton objects to reduce code size

    The value of m will have changed (actually lost when the loop exits) when that setIcon() method is called.
    Yes, the way the previewLabel works in the long code (an actionListener coded separately for each of the oButtons) is it's like a little thumbnail preview of the last .png button which was clicked (from oButtons; oButtons is basically the 'palette' shown on the right panel of buttons in the image). In the picture I posted, previewLabel appears as the top-right most image. So when a button on the map is pressed, the Icon for it becomes the image from the previewLabel.

    So my goal to shorten the code is to have one method with a loop which listens for any button click (from oButtons[]) and updates the previewLabel based on that. There would never be a possibility (that I know of) to click 2 or more oButtons at once to crash the code.

    Also, I tried your suggested loop exactly as you have it and got a null pointer exception:

    Exception in thread "main" java.lang.NullPointerException
    	at javax.swing.ImageIcon.<init>(ImageIcon.java:217)
    	at WizMapMakerEdit.<init>(WizMapMakerEdit.java:99)
    	at WizMapMakerEdit.main(WizMapMakerEdit.java:777)

    What are clientProperties?

  10. The Following User Says Thank You to Sizzlewump For This Useful Post:


  11. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Trying to loop actionListeners together for 56 JButton objects to reduce code size

    got a null pointer exception:
    Are the image files in the correct location? You get a NPE when the image files are not found:
          new ImageIcon(new TestCode24().getClass().getResource("NoFile"));
    The above statement gives this error when executed:
    Exception in thread "main" java.lang.NullPointerException
    at java.desktop/javax.swing.ImageIcon.<init>(Unknown Source)
    at TestCode24.main(TestCode24.java:994)
    There is no error when I change "NoFile" to the name of an existing file.

    See the API doc of the JComponent class for a description of clientProperties
    If you don't understand my answer, don't ignore it, ask a question.

  12. The Following 2 Users Say Thank You to Norm For This Useful Post:

    Sizzlewump (July 25th, 2018)

  13. #7
    Junior Member
    Join Date
    Jul 2018
    Posts
    14
    Thanks
    7
    Thanked 9 Times in 9 Posts

    Default Re: Trying to loop actionListeners together for 56 JButton objects to reduce code size

    Thanks, I had to reorganize my resource files. The .java file was in a different folder than the .pngs by mistake. I reran and got a similar error:

    Exception in thread "main" java.lang.NullPointerException
    	at WizMapMakerEdit.<init>(WizMapMakerEdit.java:104)
    	at WizMapMakerEdit.main(WizMapMakerEdit.java:770)

    line 104 from the class instance of WizMapMakerEdit:
    String tempName = oButtonNames[m];

    line 770 from the main method of the WizMapMakerEdit class:
    WizMapMakerEdit wmme = new WizMapMakerEdit("Design a map below:");

  14. The Following User Says Thank You to Sizzlewump For This Useful Post:


  15. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Trying to loop actionListeners together for 56 JButton objects to reduce code size

    I reran and got a similar error:

    Exception in thread "main" java.lang.NullPointerException
    at WizMapMakerEdit.<init>(WizMapMakerEdit.java:104)
    at WizMapMakerEdit.main(WizMapMakerEdit.java:770)
    That error is from a different cause. What variable has a null value when the code on line 104 is executed?
    If you don't understand my answer, don't ignore it, ask a question.

  16. The Following User Says Thank You to Norm For This Useful Post:


  17. #9
    Junior Member
    Join Date
    Jul 2018
    Posts
    14
    Thanks
    7
    Thanked 9 Times in 9 Posts

    Default Re: Trying to loop actionListeners together for 56 JButton objects to reduce code size

    It looks like all of the oButtonNames[] elements have null values at 104. I put a few System.out.println(oButtonNames[1]); statements outside of the loop, replacing the 1 with other array indexes. None of them printed to output. m should not be null since we gave it the value zero, right?

    This may be unrelated, but I do have one special button set to null. It's called Erase and it is not part of oButtons[]. Erase is a button on the same JPanel as oButtons which I use to reset a button icon on the map. In other words, when you click erase from the palette, then you click on any button in the map to clear the image off of the button.

    Here's some context:

    erase.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 // change the icon displayed when button is pressed
    			    previewLabel.setIcon(null);
              }
           }
           );
     
    		 //set layouts to panels
           outerPane.setLayout(new BorderLayout());
           gridPane.setLayout(bl);
           innerPane.setLayout(new BorderLayout());
           optionsPane.setLayout(gl);              
     
           //add panels
           this.add(outerPane);       
           outerPane.add(gridPane, BorderLayout.CENTER);
           outerPane.add(innerPane, BorderLayout.EAST);
           innerPane.add(samplePane, BorderLayout.NORTH);
           innerPane.add(optionsPane, BorderLayout.EAST);              
     
           //add buttons to panels
    		 buildButtons();
         //  addOptions();
           samplePane.add(previewLabel);
           this.setDefaultCloseOperation(EXIT_ON_CLOSE);     
       }
       //create an array of buttons in the grid panel
       private void buildButtons()
       {
         for(int i=0; i < ROWS; i++)
         {
            for(int j=0; j < COLS; j++)
            {
               tiles[i][j] = new JButton();
    			  tiles[i][j].addActionListener(handler);
               tiles[i][j].setSize(300,300);  
    			  tiles[i][j].add(buttonLabel);
    			  gridPane.add(tiles[i][j]);
            }
         }
       } 
       //add new images to options: PLACE NEW ITEM HERE - STEP 3  
       private void addOptions()
       {
         JButton oButtons[] = new JButton[] {floor, wallFill, cornerNW, cornerSW, cornerNE, cornerSE,
         wallN, wallS, wallW, wallE, bumpNW, bumpNE, bumpSW, bumpSE, doorN, doorS, doorW, 
         doorE, capN, capS, capW, capE, hallH, hallV, StairsUp, StairsDown, EVator, WarpIn,
         WarpOut, Pool, Pit, SPit, Shaft, SShaft, Spinner, Darkness, Boss, Interaction, NPC, 
         NPCPatrol, LockDoorN, LockDoorS, LockDoorW, LockDoorE, SDoorN, SDoorS, SDoorW, SDoorE, 
         FWallN, FWallS, FWallW, FWallE, OneDoorN, OneDoorS, OneDoorW, OneDoorE};
     
         String[] oButtonNames = new String[] {"Floor.png", "WallFill.png", "CornerNW.png", "CornerSW.png", "CornerNE.png", "CornerSE.png",
         "WallN.png", "WallS.png", "WallW.png", "WallE.png", "BumpNW.png", "BumpNE.png", "BumpSW.png", "BumpSE.png", "DoorN.png", "DoorS.png", "DoorW.png",
         "DoorE.png", "CapN.png", "CapS.png", "CapW.png", "CapE.png", "HallH.png", "HallV.png", "StairsUp.png", "StairsDown.png", "EVator.png", "WarpIn.png", 
         "WarpOut.png", "Pool.png", "Pit.png", "SPit.png", "Shaft.png", "SShaft.png", "Spinner.png", "Darkness.png", "Boss.png", "Interaction.png", "NPC.png", 
         "NPCPatrol.png", "LockDoorN.png", "LockDoorS.png", "LockDoorW.png", "LockDoorE.png", "SDoorN.png", "SDoorS.png", "SDoorW.png", "SDoorE.png",
         "FWallN.png", "FWallS.png", "FWallW.png", "FWallE.png", "OneDoorN.png", "OneDoorS.png", "OneDoorW.png", "OneDoorE.png"};
     
         for(int i=0; i<56; i++)
         {
           oButtons[i].setIcon(new ImageIcon(getClass().getResource(oButtonNames[i])));
           optionsPane.add(oButtons[i]);
         }
         optionsPane.add(erase);
       } 
     
    	class ReportClick implements ActionListener
       {
          public void actionPerformed(ActionEvent event)
          {
    		   JButton btn = (JButton) event.getSource();  // get reference to clicked button
             btn.setIcon(previewLabel.getIcon());    // set the button's icon
          }
       }   
     
       public static void main(String[] args)
       {
          //make instance of frame object & display it
          WizMapMakerEdit wmme = new WizMapMakerEdit("Design a map below:");
          wmme.pack();
          wmme.setVisible(true);
       }
    }

  18. The Following User Says Thank You to Sizzlewump For This Useful Post:


  19. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Trying to loop actionListeners together for 56 JButton objects to reduce code size

    It looks like all of the oButtonNames[] elements have null values at 104.
    Have you fixed that problem? What happens now?
    If you don't understand my answer, don't ignore it, ask a question.

  20. The Following User Says Thank You to Norm For This Useful Post:


  21. #11
    Junior Member
    Join Date
    Jul 2018
    Posts
    14
    Thanks
    7
    Thanked 9 Times in 9 Posts

    Default Re: Trying to loop actionListeners together for 56 JButton objects to reduce code size

    No, the for loop never executes. I put any print statement in the loop and nothing outputs.

    What is the concept I'm missing - inheritance? Do you see the problem anywhere? I'm sorry, I'm a little thick at this.

  22. The Following User Says Thank You to Sizzlewump For This Useful Post:


  23. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Trying to loop actionListeners together for 56 JButton objects to reduce code size

    Sorry, the small bits of code that have been posted probably don't show the problem.
    Can you make a small, complete test program that compiles, executes and shows the problem?
    If you don't understand my answer, don't ignore it, ask a question.

  24. The Following User Says Thank You to Norm For This Useful Post:


  25. #13
    Junior Member
    Join Date
    Jul 2018
    Posts
    14
    Thanks
    7
    Thanked 9 Times in 9 Posts

    Default Re: Trying to loop actionListeners together for 56 JButton objects to reduce code size

    Yes, ok that's a good possibility. Here is the entire working code. I commented out the possible solution we were collaborating on for now. Thanks again for looking at this. Good help is hard to find.
    /*Created by John Thrush 06/25/18
       WizMapMaker is a video game supplement
    	that works as a drawing tool. The application creates
       an array of buttons which the user can toggle to 
       paint images from a side panel.
    */
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
     
    public class WizMapMaker extends JFrame 
    {
       private final static int ROWS = 27;
    	private final static int COLS = 32; 
       private JPanel outerPane = new JPanel();
       private JPanel gridPane = new JPanel();
       private JPanel innerPane = new JPanel();
       private JPanel optionsPane = new JPanel();
       private JPanel samplePane = new JPanel();
    	private JButton tiles[][];
       private JButton oButtons[];
       private String oButtonNames[];
       //add new buttons: PLACE NEW ITEM HERE - STEP 1
    	private JButton floor = new JButton("");
       private JButton wallFill = new JButton("");
       private JButton cornerNW = new JButton("");
    	private JButton cornerSW = new JButton("");
    	private JButton cornerNE = new JButton("");
       private JButton cornerSE = new JButton("");
       private JButton wallN = new JButton("");
       private JButton wallS = new JButton("");
       private JButton wallW = new JButton("");
       private JButton wallE = new JButton("");
       private JButton bumpNW = new JButton("");
       private JButton bumpNE = new JButton("");
       private JButton bumpSW = new JButton("");
       private JButton bumpSE = new JButton("");
       private JButton doorN = new JButton("");
       private JButton doorS = new JButton("");
       private JButton doorW = new JButton("");
       private JButton doorE = new JButton("");
       private JButton capN = new JButton("");
       private JButton capS = new JButton("");
       private JButton capW = new JButton("");
       private JButton capE = new JButton("");
       private JButton hallH = new JButton("");
       private JButton hallV = new JButton("");
       private JButton StairsUp = new JButton("");
       private JButton StairsDown = new JButton("");
       private JButton EVator = new JButton("");
       private JButton WarpIn = new JButton("");
       private JButton WarpOut = new JButton("");
       private JButton Pool = new JButton("");
       private JButton Pit = new JButton("");
       private JButton SPit = new JButton("");
       private JButton Shaft = new JButton("");
       private JButton SShaft = new JButton("");
       private JButton Spinner = new JButton("");
       private JButton Darkness = new JButton("");
       private JButton Boss = new JButton("");
       private JButton Interaction = new JButton("");
       private JButton NPC = new JButton("");
       private JButton NPCPatrol = new JButton("");
       private JButton LockDoorN = new JButton("");
       private JButton LockDoorS = new JButton("");
       private JButton LockDoorW = new JButton("");
       private JButton LockDoorE = new JButton("");
       private JButton SDoorN = new JButton("");
       private JButton SDoorS = new JButton("");
       private JButton SDoorW = new JButton("");
       private JButton SDoorE = new JButton("");
       private JButton FWallN = new JButton("");
       private JButton FWallS = new JButton("");
       private JButton FWallW = new JButton("");
       private JButton FWallE = new JButton("");
       private JButton OneDoorN = new JButton("");
       private JButton OneDoorS = new JButton("");
       private JButton OneDoorW = new JButton("");
       private JButton OneDoorE = new JButton("");
       private JButton erase = new JButton("Erase");
     
    	private JLabel previewLabel= new JLabel();
       private JLabel buttonLabel = new JLabel("");
       private ReportClick handler = new ReportClick();
       private GridLayout gl = new GridLayout(12,5);
       private GridLayout bl = new GridLayout(ROWS,COLS);
       private GridLayout sl = new GridLayout(1,1);   
       private DefaultListCellRenderer dr = new DefaultListCellRenderer();
     
    	public WizMapMaker(String title)
       {   
           //set a title & min size for outer frame
           super(title);
           setMinimumSize(new Dimension(1800, 985));
     
    		 //add components to panels 
           tiles = new JButton[ROWS][COLS];
           dr.setHorizontalAlignment(DefaultListCellRenderer.CENTER);
           previewLabel.setIcon(new ImageIcon(getClass().getResource("Floor.png"))); //give the previewLabel a default image
           addOptions();       
           //add new button listeners: PLACE NEW ITEM HERE - STEP 2
     
         /*for(int m=0; m<56; m++)
           {
             String tempName = oButtonNames[m];     
             oButtons[m].addActionListener(new ActionListener()
             {
               String theName = tempName;     //  save the name in a variable in the anonymous class
               public void actionPerformed(ActionEvent e)
               {
                 // change the icon displayed when button is pressed 
                 previewLabel.setIcon(new ImageIcon(getClass().getResource(theName))); 
               }
             }
             );
            }
             */
     
    		 floor.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 // change the icon displayed when button is pressed
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("Floor.png")));
              }
           }
           );
     
           wallFill.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("WallFill.png")));
              }
           }
           );  
     
    		 cornerNW.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("CornerNW.png")));
              }
           }
           );
     
           cornerNE.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("CornerNE.png")));
              }
           }
           );
     
    		 cornerSW.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("CornerSW.png")));
              }
           }
           );	  	     
     
           cornerSE.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("CornerSE.png")));
              }
           }
           );
     
           wallN.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("WallN.png")));
              }
           }
           );
     
           wallS.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("WallS.png")));
              }
           }
           );
     
           wallW.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("WallW.png")));
              }
           }
           ); 
     
           wallE.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("WallE.png")));
              }
           }
           );      
     
           bumpNW.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("BumpNW.png")));
              }
           }
           );
     
           bumpNE.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("BumpNE.png")));
              }
           }
           ); 
     
           bumpSW.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("BumpSW.png")));
              }
           }
           );
     
           bumpSE.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("BumpSE.png")));
              }
           }
           );
     
           doorN.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("DoorN.png")));
              }
           }
           );
     
           doorS.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("DoorS.png")));
              }
           }
           );
     
           doorW.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("DoorW.png")));
              }
           }
           );
     
           doorE.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("DoorE.png")));
              }
           }
           );
     
           capN.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("capN.png")));
              }
           }
           );
     
           capS.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("capS.png")));
              }
           }
           );
     
           capW.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("capW.png")));
              }
           }
           );
     
           capE.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("capE.png")));
              }
           }
           );
     
           hallH.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("HallH.png")));
              }
           }
           );
     
           hallV.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("HallV.png")));
              }
           }
           );
     
    		 StairsUp.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("StairsUp.png")));
              }
           }
           );
     
    		 StairsDown.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("StairsDown.png")));
              }
           }
           );
     
    		 EVator.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("EVator.png")));
              }
           }
           );
     
    		 WarpIn.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("WarpIn.png")));
              }
           }
           );
     
    		 WarpOut.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("WarpOut.png")));
              }
           }
           );
     
    		 Pool.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("Pool.png")));
              }
           }
           );
     
    		 Pit.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("Pit.png")));
              }
           }
           );
     
     		 SPit.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("SPit.png")));
              }
           }
           );
     
     		 Shaft.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("Shaft.png")));
              }
           }
           );
     
    		 SShaft.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("SShaft.png")));
              }
           }
           );
     
     		 Spinner.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("Spinner.png")));
              }
           }
           );
     
    		 Darkness.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("Darkness.png")));
              }
           }
           );
     
     		 Boss.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("Boss.png")));
              }
           }
           );
     
    		 Interaction.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("Interaction.png")));
              }
           }
           );
     
     		 NPC.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("NPC.png")));
              }
           }
           );
     
    		 NPCPatrol.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("NPCPatrol.png")));
              }
           }
           );
     
     		 LockDoorN.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("LockDoorN.png")));
              }
           }
           );
     
     		 LockDoorS.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("LockDoorS.png")));
              }
           }
           );
     
     		 LockDoorW.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("LockDoorW.png")));
              }
           }
           );
     
     		 LockDoorE.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("LockDoorE.png")));
              }
           }
           );
     
    		 SDoorN.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("SDoorN.png")));
              }
           }
           );
     
    		 SDoorS.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("SDoorS.png")));
              }
           }
           );
     
    		 SDoorW.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("SDoorW.png")));
              }
           }
           );
     
    		 SDoorE.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("SDoorE.png")));
              }
           }
           );
     
     		 FWallN.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("FWallN.png")));
              }
           }
           );
     
    		 FWallS.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("FWallS.png")));
              }
           }
           );
     
     		 FWallW.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("FWallW.png")));
              }
           }
           );
     
     		 FWallE.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("FWallE.png")));
              }
           }
           );
     
    		 OneDoorN.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("OneDoorN.png")));
              }
           }
           );
     
     		 OneDoorS.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("OneDoorS.png")));
              }
           }
           );
     
    		 OneDoorW.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("OneDoorW.png")));
              }
           }
           );
     
     		 OneDoorE.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 previewLabel.setIcon(new ImageIcon(getClass().getResource("OneDoorE.png")));
              }
           }
           );  
     
           erase.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 // erase the button label when it is pressed
    			    previewLabel.setIcon(null);
              }
           }
           );
     
    		 //set layouts to panels
           outerPane.setLayout(new BorderLayout());
           gridPane.setLayout(bl);
           innerPane.setLayout(new BorderLayout());
           optionsPane.setLayout(gl);              
     
           //add panels
           this.add(outerPane);       
           outerPane.add(gridPane, BorderLayout.CENTER);
           outerPane.add(innerPane, BorderLayout.EAST);
           innerPane.add(samplePane, BorderLayout.NORTH);
           innerPane.add(optionsPane, BorderLayout.EAST);              
     
           //add buttons to panels
    		 buildButtons();
           //addOptions();
           samplePane.add(previewLabel);
           this.setDefaultCloseOperation(EXIT_ON_CLOSE);     
       }
       //create an array of buttons in the grid panel
       private void buildButtons()
       {
         for(int i=0; i < ROWS; i++)
         {
            for(int j=0; j < COLS; j++)
            {
               tiles[i][j] = new JButton();
    			  tiles[i][j].addActionListener(handler);
               tiles[i][j].setSize(300,300);  
    			  tiles[i][j].add(buttonLabel);
    			  gridPane.add(tiles[i][j]);
            }
         }
       } 
       //add new images to options: PLACE NEW ITEM HERE - STEP 3  
       private void addOptions()
       {
         JButton oButtons[] = new JButton[] {floor, wallFill, cornerNW, cornerSW, cornerNE, cornerSE,
         wallN, wallS, wallW, wallE, bumpNW, bumpNE, bumpSW, bumpSE, doorN, doorS, doorW, 
         doorE, capN, capS, capW, capE, hallH, hallV, StairsUp, StairsDown, EVator, WarpIn,
         WarpOut, Pool, Pit, SPit, Shaft, SShaft, Spinner, Darkness, Boss, Interaction, NPC, 
         NPCPatrol, LockDoorN, LockDoorS, LockDoorW, LockDoorE, SDoorN, SDoorS, SDoorW, SDoorE, 
         FWallN, FWallS, FWallW, FWallE, OneDoorN, OneDoorS, OneDoorW, OneDoorE};
     
         String[] oButtonNames = new String[] {"Floor.png", "WallFill.png", "CornerNW.png", "CornerSW.png", "CornerNE.png", "CornerSE.png",
         "WallN.png", "WallS.png", "WallW.png", "WallE.png", "BumpNW.png", "BumpNE.png", "BumpSW.png", "BumpSE.png", "DoorN.png", "DoorS.png", "DoorW.png",
         "DoorE.png", "CapN.png", "CapS.png", "CapW.png", "CapE.png", "HallH.png", "HallV.png", "StairsUp.png", "StairsDown.png", "EVator.png", "WarpIn.png", 
         "WarpOut.png", "Pool.png", "Pit.png", "SPit.png", "Shaft.png", "SShaft.png", "Spinner.png", "Darkness.png", "Boss.png", "Interaction.png", "NPC.png", 
         "NPCPatrol.png", "LockDoorN.png", "LockDoorS.png", "LockDoorW.png", "LockDoorE.png", "SDoorN.png", "SDoorS.png", "SDoorW.png", "SDoorE.png",
         "FWallN.png", "FWallS.png", "FWallW.png", "FWallE.png", "OneDoorN.png", "OneDoorS.png", "OneDoorW.png", "OneDoorE.png"};
     
         for(int i=0; i<56; i++)
         {
           oButtons[i].setIcon(new ImageIcon(getClass().getResource(oButtonNames[i])));
           optionsPane.add(oButtons[i]);
         }
         optionsPane.add(erase);
       } 
     
    	class ReportClick implements ActionListener
       {
          public void actionPerformed(ActionEvent event)
          {
    		   JButton btn = (JButton) event.getSource();  // get reference to clicked button
             btn.setIcon(previewLabel.getIcon());    // set the button's icon
          }
       }   
     
       public static void main(String[] args)
       {
          //make instance of frame object & display it
          WizMapMaker wmm = new WizMapMaker("Design a map below:");
          wmm.pack();
          wmm.setVisible(true);
       }
    } //end code


    --- Update ---

    I have also compressed the image resources into a small 7zip (.7z) file which is only 117KB. Just let me know the best way to upload it if it's doable.

  26. The Following User Says Thank You to Sizzlewump For This Useful Post:


  27. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Trying to loop actionListeners together for 56 JButton objects to reduce code size

    This code has the repeated groups of very similar code. I thought that was going to be merged into a single method with an array and loop to handle instead of all this repeated code.

    The problem is some key variables have local definitions in the addOptions method. They should be assignments to the class fields that are already defined at the top of the class.
    Note:
      String str = "value";  // defines and assigns a value
      str = "value";    // assigns a value to an already defined variable
    If you don't understand my answer, don't ignore it, ask a question.

  28. The Following 2 Users Say Thank You to Norm For This Useful Post:

    Sizzlewump (July 25th, 2018)

  29. #15
    Junior Member
    Join Date
    Jul 2018
    Posts
    14
    Thanks
    7
    Thanked 9 Times in 9 Posts

    Default Re: Trying to loop actionListeners together for 56 JButton objects to reduce code size

    Yes, that's where I would like to go with it. I wanted to get you the working version and go from there. When I was testing, I just commented out lines 119-622.

  30. The Following User Says Thank You to Sizzlewump For This Useful Post:


  31. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Trying to loop actionListeners together for 56 JButton objects to reduce code size

    Check out the end of my last post.

    Also remove the hardcoded value 56. Use the .length field of an array to control the looping.
    If you don't understand my answer, don't ignore it, ask a question.

  32. The Following 2 Users Say Thank You to Norm For This Useful Post:

    Sizzlewump (July 25th, 2018)

  33. #17
    Junior Member
    Join Date
    Jul 2018
    Posts
    14
    Thanks
    7
    Thanked 9 Times in 9 Posts

    Default Re: Trying to loop actionListeners together for 56 JButton objects to reduce code size

    Hi Norm, thanks again for all of your help! It took me some time to process your suggestions but I have been able to get the code down to 203 lines with your help. I'm very happy with the results!

    /*Created by John Thrush 06/25/18
       TestWizMapMaker is a video game supplement
    	that works as a drawing tool. The application creates
       an array of buttons which the user can toggle to 
       paint images from a side panel.
     
       Kudos to Norm at javaprogrammingforums.com for enhancements
    */
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
     
    public class TestWizMapMaker extends JFrame 
    {
       private final static int ROWS = 27;
    	private final static int COLS = 32; 
       private JPanel outerPane = new JPanel();
       private JPanel gridPane = new JPanel();
       private JPanel innerPane = new JPanel();
       private JPanel optionsPane = new JPanel();
       private JPanel samplePane = new JPanel();
    	public JButton tiles[][];
       //add new buttons: PLACE NEW ITEM HERE - STEP 1
    	private JButton floor = new JButton("");
       private JButton wallFill = new JButton("");
       private JButton cornerNW = new JButton("");
    	private JButton cornerSW = new JButton("");
    	private JButton cornerNE = new JButton("");
       private JButton cornerSE = new JButton("");
       private JButton wallN = new JButton("");
       private JButton wallS = new JButton("");
       private JButton wallW = new JButton("");
       private JButton wallE = new JButton("");
       private JButton bumpNW = new JButton("");
       private JButton bumpNE = new JButton("");
       private JButton bumpSW = new JButton("");
       private JButton bumpSE = new JButton("");
       private JButton doorN = new JButton("");
       private JButton doorS = new JButton("");
       private JButton doorW = new JButton("");
       private JButton doorE = new JButton("");
       private JButton capN = new JButton("");
       private JButton capS = new JButton("");
       private JButton capW = new JButton("");
       private JButton capE = new JButton("");
       private JButton hallH = new JButton("");
       private JButton hallV = new JButton("");
       private JButton stairsUp = new JButton("");
       private JButton stairsDown = new JButton("");
       private JButton eVator = new JButton("");
       private JButton warpIn = new JButton("");
       private JButton warpOut = new JButton("");
       private JButton pool = new JButton("");
       private JButton pit = new JButton("");
       private JButton sPit = new JButton("");
       private JButton shaft = new JButton("");
       private JButton sShaft = new JButton("");
       private JButton spinner = new JButton("");
       private JButton darkness = new JButton("");
       private JButton boss = new JButton("");
       private JButton interaction = new JButton("");
       private JButton NPC = new JButton("");
       private JButton NPCPatrol = new JButton("");
       private JButton lockDoorN = new JButton("");
       private JButton lockDoorS = new JButton("");
       private JButton lockDoorW = new JButton("");
       private JButton lockDoorE = new JButton("");
       private JButton sDoorN = new JButton("");
       private JButton sDoorS = new JButton("");
       private JButton sDoorW = new JButton("");
       private JButton sDoorE = new JButton("");
       private JButton fWallN = new JButton("");
       private JButton fWallS = new JButton("");
       private JButton fWallW = new JButton("");
       private JButton fWallE = new JButton("");
       private JButton oneDoorN = new JButton("");
       private JButton oneDoorS = new JButton("");
       private JButton oneDoorW = new JButton("");
       private JButton oneDoorE = new JButton("");
       private JButton erase = new JButton("Erase");
       private String oButtonNames[] = new String[] 
         {"Floor.png", "WallFill.png", "CornerNW.png", "CornerSW.png", "CornerNE.png", "CornerSE.png",
         "WallN.png", "WallS.png", "WallW.png", "WallE.png", "BumpNW.png", "BumpNE.png", "BumpSW.png", "BumpSE.png", "DoorN.png", "DoorS.png", "DoorW.png",
         "DoorE.png", "CapN.png", "CapS.png", "CapW.png", "CapE.png", "HallH.png", "HallV.png", "StairsUp.png", "StairsDown.png", "EVator.png", "WarpIn.png", 
         "WarpOut.png", "Pool.png", "Pit.png", "SPit.png", "Shaft.png", "SShaft.png", "Spinner.png", "Darkness.png", "Boss.png", "Interaction.png", "NPC.png", 
         "NPCPatrol.png", "LockDoorN.png", "LockDoorS.png", "LockDoorW.png", "LockDoorE.png", "SDoorN.png", "SDoorS.png", "SDoorW.png", "SDoorE.png",
         "FWallN.png", "FWallS.png", "FWallW.png", "FWallE.png", "OneDoorN.png", "OneDoorS.png", "OneDoorW.png", "OneDoorE.png"
         };
       private JButton oButtons[] = new JButton[] 
         {floor, wallFill, cornerNW, cornerSW, cornerNE, cornerSE,
         wallN, wallS, wallW, wallE, bumpNW, bumpNE, bumpSW, bumpSE, doorN, doorS, doorW, 
         doorE, capN, capS, capW, capE, hallH, hallV, stairsUp, stairsDown, eVator, warpIn,
         warpOut, pool, pit, sPit, shaft, sShaft, spinner, darkness, boss, interaction, NPC, 
         NPCPatrol, lockDoorN, lockDoorS, lockDoorW, lockDoorE, sDoorN, sDoorS, sDoorW, sDoorE, 
         fWallN, fWallS, fWallW, fWallE, oneDoorN, oneDoorS, oneDoorW, oneDoorE
         };
     
    	private JLabel previewLabel= new JLabel();
       private JLabel buttonLabel = new JLabel("");
       private ReportClick handler = new ReportClick();
       private GridLayout gl = new GridLayout(12,5);
       private GridLayout bl = new GridLayout(ROWS,COLS);
       private GridLayout sl = new GridLayout(1,1);   
       private DefaultListCellRenderer dr = new DefaultListCellRenderer();
     
    	private TestWizMapMaker(String title)
       {   
           //set a title & min size for outer frame
           super(title);
           setMinimumSize(new Dimension(1800, 985));
    		 //add components to panels 
           tiles = new JButton[ROWS][COLS];
           dr.setHorizontalAlignment(DefaultListCellRenderer.CENTER);
           previewLabel.setIcon(new ImageIcon(getClass().getResource("Floor.png")));      
           //add new button listeners: PLACE NEW ITEM HERE - STEP 2
     
           for(int m=0; m<oButtonNames.length; m++)
           {
             String tempName = oButtonNames[m];     
             oButtons[m].addActionListener(new ActionListener()
             {
               String theName = tempName;     //  save the name in a variable in the anonymous class
               public void actionPerformed(ActionEvent e)
               {
                 // change the icon displayed when button is pressed 
                 previewLabel.setIcon(new ImageIcon(getClass().getResource(theName))); 
               }
             }
             );
           }
     
           erase.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 // change the icon displayed when button is pressed
    			    previewLabel.setIcon(null);
              }
           }
           );
     
    		 //set layouts to panels
           outerPane.setLayout(new BorderLayout());
           gridPane.setLayout(bl);
           innerPane.setLayout(new BorderLayout());
           optionsPane.setLayout(gl);              
     
           //add panels
           this.add(outerPane);       
           outerPane.add(gridPane, BorderLayout.CENTER);
           outerPane.add(innerPane, BorderLayout.EAST);
           innerPane.add(samplePane, BorderLayout.NORTH);
           innerPane.add(optionsPane, BorderLayout.EAST);              
     
           //add buttons to panels
           samplePane.add(previewLabel);
           buildButtons();
           addOptions();
     
           this.setDefaultCloseOperation(EXIT_ON_CLOSE);     
       }
       //create an array of buttons in the grid panel
     
       private void buildButtons()
       {
         for(int i=0; i < ROWS; i++)
         {
            for(int j=0; j < COLS; j++)
            {
               tiles[i][j] = new JButton();
    			  tiles[i][j].addActionListener(handler);
               tiles[i][j].setSize(300,300);  
    			  tiles[i][j].add(buttonLabel);
    			  gridPane.add(tiles[i][j]);
            }
         } 
       } 
       //add new images to options: PLACE NEW ITEM HERE - STEP 3  
       public void addOptions()
       {
         for(int i=0; i < oButtonNames.length; i++)
         {
           oButtons[i].setIcon(new ImageIcon(getClass().getResource(oButtonNames[i])));
           optionsPane.add(oButtons[i]);
         }
         optionsPane.add(erase);
       } 
     
    	public class ReportClick implements ActionListener
       {
          public void actionPerformed(ActionEvent event)
          {
    		   JButton btn = (JButton) event.getSource();  // get reference to clicked button
             btn.setIcon(previewLabel.getIcon());    // set the button's icon
          }
       }   
     
       public static void main(String[] args)
       {
          //make instance of frame object & display it
          TestWizMapMaker wmm = new TestWizMapMaker("Design a map below:");
          wmm.pack();
          wmm.setVisible(true);
       }
    }
    Last edited by Sizzlewump; July 25th, 2018 at 10:36 AM. Reason: duplicate entry

  34. The Following User Says Thank You to Sizzlewump For This Useful Post:


  35. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Trying to loop actionListeners together for 56 JButton objects to reduce code size

    Do all the JButton objects need to have their own unique variable names?
    Create new JButton objects inside the loop just before setting their icons and assign them to the elements of oButtons
    If you don't understand my answer, don't ignore it, ask a question.

  36. The Following 2 Users Say Thank You to Norm For This Useful Post:

    Sizzlewump (July 26th, 2018)

  37. #19
    Junior Member
    Join Date
    Jul 2018
    Posts
    14
    Thanks
    7
    Thanked 9 Times in 9 Posts

    Default Re: Trying to loop actionListeners together for 56 JButton objects to reduce code size

    Ok, got it!

    /*Created by John Thrush 06/25/18
       WizMapMaker is a video game supplement
    	that works as a drawing tool. The application creates
       an array of buttons which the user can toggle to 
       paint images from a side panel.
     
       Kudos to Norm at javaprogrammingforums.com for enhancements
    */
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
     
    public class WizMapMaker extends JFrame 
    {
       private final static int ROWS      = 27;
    	private final static int COLS      = 32; 
       private JPanel outerPane           = new JPanel();
       private JPanel gridPane            = new JPanel();
       private JPanel innerPane           = new JPanel();
       private JPanel optionsPane         = new JPanel();
       private JPanel samplePane          = new JPanel();
       private JButton tiles[][]          = new JButton[ROWS][COLS];
       private JButton erase              = new JButton("Erase");
       public  JButton oButton            = new JButton();
       private JLabel previewLabel        = new JLabel();
       private JLabel buttonLabel         = new JLabel("");
       private ReportClick handler        = new ReportClick();
       private GridLayout gl              = new GridLayout(12,5);
       private GridLayout bl              = new GridLayout(ROWS,COLS);
       private GridLayout sl              = new GridLayout(1,1);   
       private DefaultListCellRenderer dr = new DefaultListCellRenderer();
       private String oButtonNames[]      = new String[] 
         {"Floor.png", "WallFill.png", "CornerNW.png", "CornerSW.png", "CornerNE.png", "CornerSE.png",
         "WallN.png", "WallS.png", "WallW.png", "WallE.png", "BumpNW.png", "BumpNE.png", "BumpSW.png", 
         "BumpSE.png", "DoorN.png", "DoorS.png", "DoorW.png", "DoorE.png", "CapN.png", "CapS.png", 
         "CapW.png", "CapE.png", "HallH.png", "HallV.png", "StairsUp.png", "StairsDown.png", "EVator.png", 
         "WarpIn.png", "WarpOut.png", "Pool.png", "Pit.png", "SPit.png", "Shaft.png", "SShaft.png", 
         "Spinner.png", "Darkness.png", "Boss.png", "Interaction.png", "NPC.png", "NPCPatrol.png", 
         "LockDoorN.png", "LockDoorS.png", "LockDoorW.png", "LockDoorE.png", "SDoorN.png", "SDoorS.png", 
         "SDoorW.png", "SDoorE.png", "FWallN.png", "FWallS.png", "FWallW.png", "FWallE.png", "OneDoorN.png", 
         "OneDoorS.png", "OneDoorW.png", "OneDoorE.png"
         };
     
    	private WizMapMaker(String title)
       {   
         //set a title & min size for outer frame
         super(title);
         setMinimumSize(new Dimension(1800, 985));
         dr.setHorizontalAlignment(DefaultListCellRenderer.CENTER);
         previewLabel.setIcon(new ImageIcon(getClass().getResource("Floor.png")));      
         //add options to options panel       
         for(int m=0; m < oButtonNames.length; m++)
         {
           String tempName = oButtonNames[m];
           oButton = new JButton();
           oButton.setIcon(new ImageIcon(getClass().getResource(oButtonNames[m])));
           optionsPane.add(oButton);
           oButton.addActionListener(new ActionListener()
           { 
             String theName = tempName;     //  save the name in a variable in the anonymous class
             public void actionPerformed(ActionEvent e)
             {
               // change the icon displayed when button is pressed 
               previewLabel.setIcon(new ImageIcon(getClass().getResource(theName)));
             }
           }
           );
           }
           optionsPane.add(erase);
     
           erase.addActionListener(new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                // remove the icon displayed when button is pressed
    			   previewLabel.setIcon(null);
              }
           }
           );                   
    		 //set layouts to panels
           outerPane.setLayout(new BorderLayout());
           gridPane.setLayout(bl);
           innerPane.setLayout(new BorderLayout());
           optionsPane.setLayout(gl);             
     
           //add panels
           this.add(outerPane);       
           outerPane.add(gridPane, BorderLayout.CENTER);
           outerPane.add(innerPane, BorderLayout.EAST);
           innerPane.add(samplePane, BorderLayout.NORTH);
           innerPane.add(optionsPane, BorderLayout.EAST);              
     
           //add buttons to panels
           samplePane.add(previewLabel);
           buildButtons();
          // addOptions();
           this.setDefaultCloseOperation(EXIT_ON_CLOSE);     
       } 
       //create an array of buttons in the grid panel 
       private void buildButtons()
       {
         for(int i=0; i < ROWS; i++)
         {
            for(int j=0; j < COLS; j++)
            {
              tiles[i][j] = new JButton();
    			 tiles[i][j].addActionListener(handler);
              tiles[i][j].setSize(300,300);  
    			 tiles[i][j].add(buttonLabel);
    			 gridPane.add(tiles[i][j]);
            }
         } 
       } 
     
    	private class ReportClick implements ActionListener
       {
          public void actionPerformed(ActionEvent event)
          {
    		  JButton btn = (JButton) event.getSource();  // get reference to clicked button
            btn.setIcon(previewLabel.getIcon());    // set the button's icon
          }
       }   
     
       public static void main(String[] args)
       {
         //make instance of frame object & display it
         WizMapMaker wmm = new WizMapMaker("Design a map below:");
         wmm.pack();
         wmm.setVisible(true);
       }
    }
    Thanks for the great suggestion! I'm down to 131 lines now.

Similar Threads

  1. how to get information of jtextfield by using a jbutton in a loop
    By justinbieber1372 in forum AWT / Java Swing
    Replies: 3
    Last Post: January 28th, 2014, 05:51 AM
  2. Need help editing the size of a JButton!?!?
    By syregnar86 in forum What's Wrong With My Code?
    Replies: 6
    Last Post: August 24th, 2013, 09:56 PM
  3. repaint in a JButton while loop.
    By Sevv in forum What's Wrong With My Code?
    Replies: 1
    Last Post: March 14th, 2012, 09:44 AM
  4. Replies: 2
    Last Post: February 17th, 2011, 06:37 AM
  5. Loop not creating objects
    By xecure in forum What's Wrong With My Code?
    Replies: 2
    Last Post: October 30th, 2010, 10:48 PM