Search code examples
javaswingbuttonactionlistener

How to use single button to carry out different actions on different panels?


I'm making a panel to display a property advertisement with "Buy" and "Favorite" buttons at the bottom. Instead of making same panels multiple times, I've created a method that produces an advertisement panel for me and I simply call the method multiple times with different co-ordinate.

public JPanel createAdvertisement(int price, String owner, String location, int bedrooms, int bathrooms,
        int stories, int area) {
    JPanel adPanel = new JPanel();
    adPanel.setBackground(Color.WHITE);
    adPanel.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
    adPanel.setBounds(50, 138, 500, 230);
    this.add(adPanel);
    adPanel.setLayout(null);

    JLabel housePicture = new JLabel("");
    housePicture.setIcon(new ImageIcon(BrowseAds.class.getResource("/images/stock house.jpg")));
    housePicture.setBounds(10, 0, 194, 200);
    adPanel.add(housePicture);

    JLabel priceLabel = new JLabel(String.valueOf(price));
    priceLabel.setFont(new Font("SansSerif", Font.BOLD, 18));
    priceLabel.setIcon(new ImageIcon(BrowseAds.class.getResource("/images/price.png")));
    priceLabel.setBounds(214, 11, 276, 32);
    adPanel.add(priceLabel);

    JLabel ownerLabel = new JLabel(owner);
    ownerLabel.setIcon(new ImageIcon(BrowseAds.class.getResource("/images/owner.png")));
    ownerLabel.setFont(new Font("SansSerif", Font.PLAIN, 16));
    ownerLabel.setBounds(218, 50, 270, 21);
    adPanel.add(ownerLabel);

    JLabel locationLabel = new JLabel("<html>" + location + "</html>");
    locationLabel.setIcon(new ImageIcon(BrowseAds.class.getResource("/images/location.png")));
    locationLabel.setFont(new Font("SansSerif", Font.PLAIN, 12));
    locationLabel.setBounds(220, 75, 270, 30);
    adPanel.add(locationLabel);

    JLabel bedroomLabel = new JLabel(String.valueOf(bedrooms) + " Rooms");
    bedroomLabel.setIcon(new ImageIcon(BrowseAds.class.getResource("/images/bedroom.png")));
    bedroomLabel.setFont(new Font("SansSerif", Font.PLAIN, 12));
    bedroomLabel.setBounds(224, 118, 100, 21);
    adPanel.add(bedroomLabel);

    JLabel bathroomLabel = new JLabel(String.valueOf(bathrooms) + " Baths");
    bathroomLabel.setIcon(new ImageIcon(BrowseAds.class.getResource("/images/bathroom.png")));
    bathroomLabel.setFont(new Font("SansSerif", Font.PLAIN, 12));
    bathroomLabel.setBounds(350, 118, 100, 21);
    adPanel.add(bathroomLabel);

    JLabel storiesLabel = new JLabel(String.valueOf(stories) + " Stories");
    storiesLabel.setIcon(new ImageIcon(BrowseAds.class.getResource("/images/floors.png")));
    storiesLabel.setFont(new Font("SansSerif", Font.PLAIN, 12));
    storiesLabel.setBounds(224, 150, 100, 21);
    adPanel.add(storiesLabel);

    JLabel areaLabel = new JLabel(String.valueOf(area) + " Marla");
    areaLabel.setIcon(new ImageIcon(BrowseAds.class.getResource("/images/area.png")));
    areaLabel.setFont(new Font("SansSerif", Font.PLAIN, 12));
    areaLabel.setBounds(350, 150, 100, 21);
    adPanel.add(areaLabel);

    buyButton = new JButton("Buy");
    buyButton.addActionListener(this);
    buyButton.setFont(new Font("SansSerif", Font.PLAIN, 10));
    buyButton.setBounds(214, 196, 120, 23);
    adPanel.add(buyButton);

    JButton btnAddToFavorite = new JButton("Add to Favorite");
    btnAddToFavorite.setFont(new Font("SansSerif", Font.PLAIN, 10));
    btnAddToFavorite.setBounds(360, 196, 120, 23);
    adPanel.add(btnAddToFavorite);

    return adPanel;
}

I want to call different methods on the same button based on its location. E.g. If the user clicks the 3rd "Buy" button on the screen, I want to send the data of that advertisement to the back-end. Can you suggest me a way to carry different actions using the same button.

The code for making advertisements:

public void viewAds() {
    for (int i = 0; i < 4; i++) {
        int index = ((pageNumber - 1) * 4) + i;
        if (index < totalCount) {
            Ad curr = array.get(i);
            JPanel panel = createAdvertisement(curr.price, curr.owner, curr.location, curr.bedrooms, curr.bathrooms,
                    curr.stories, curr.area);
            if (index % 4 == 0) {
                panel.setBounds(70, 138, 500, 230);
            }
            if (index % 4 == 1) {
                panel.setBounds(700, 138, 500, 230);
            }
            if (index % 4 == 2) {
                panel.setBounds(70, 380, 500, 230);
            } else if (index % 4 == 3) {
                panel.setBounds(700, 380, 500, 230);
            }
        } else {
            break;
        }
    }
}

Solution

  • SExtend JButton to include a field private or otherwise that records which one it is. All that is needed is an ID. Going further than that is a form of caching or it might be better to have a component/container that keeps info, for example coords on screen.

    class SButton extends JButton {
    
        int myID;
    
        // Code that accepts an ActionListener and applies it to this button.
        // Or use super classes' methods and constructors.
    
        // Constructor has to set the button's command to include the ID
        // The ID can be generated statically in sequence or provide by
        // outside code.  This is because the command is passed through
        // the ActionEvent generated by the thread.  So a simple way
        // is to append the ID at the end of the command.  This can
        // be easy because the SButtons will all have the same label
        // or you can provide a single base for their command for all.
    
    }
    
    
    class Ad {
    
        Point myLocation;
    
        // Ad code creates panel that uses an SButton, maybe providing ID.
    
    }
    
    class AdManager implements ActionListener {
    
        Ad [] myAds = new Ad []; // use lists, hashmaps, etc. as appropriate.
    
        void initAds () {
            for (some kind of loop) {
                make some kind of Ad;
                set its ActionListener to this AdManager;
                put it in myAds;
            }
        }
    
        public void actionPerformed (ActionEvent e) {
            String cmd = e.getActionCommand ();
            int anID = cmd.subString (some index at the end);
            theOneMethodThatSyedWroteThatHandlesAllTheSButtons (anID);
        }
    }