简体   繁体   中英

How to make JButton know on which panel it has been clicked on?

I'm trying to simulate a car renting system on a GUI. Since I'm not very experienced with Swing components I decided to create a car list using GridBagLayout.

Each row has different panels each having different rental prices and car names.

CarList

The "Details" button is shared through all the panels in the list. I'm looking for a way in which "Details" gets the title and price text from the panel were it was pressed, then saves them inside variables.

so far whenever I press it, it only saves and sends the text from the last panel in the list even if I pressed the first button in the list.

CarDetails

This is the button's Event:

JButton btnNewButton = new JButton("details");
btnNewButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        String Car, price;
        Car = Name.getText();
        price = Price.getText();
        Main.add(new CarD(Car,price), "2");
        cl.show(Main, "2");
        add.setVisible(false);
    }
});

EDIT:

Following camickr's example, all that was left was to get the labels from the parent Panel using the location where they are placed within it.

        JButton btnNewButton = new JButton("Details");
            btnNewButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    String Car, price;
                    JButton button = (JButton)e.getSource();
                    JPanel panel = (JPanel)button.getParent();
                    JLabel N = (JLabel)panel.getComponentAt(202, 62);
                    JLabel P = (JLabel)panel.getComponentAt(202, 24);

                    Car = N.getText();
                    price = P.getText();
                    Main.add(new CarD(Car,price), "2");
                    cl.show(Main, "2");
                    add.setVisible(false);
                }
            });

In the ActionListener of your "Details" button you can get the button from the ActionEvent and the panel from the button:

JButton button = (JButton)e.getSource();
JPanel panel = (JPanel)button.getParent();

In ActionListener try this :

    public void actionListener(ActionEvent evt)
    {
       if(evt.getSource()==b1)  // b1 is button variable
       {    
         //code
         // this will run if you click on b1 button
       }
       if(evt.getSource()==b2)  // b2 is another button variable
       {    
           //code
           // this will run if you click on b2 button
       }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM