繁体   English   中英

如何使JButton知道在哪个面板上单击了它?

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

我正在尝试在GUI上模拟租车系统。 由于我对Swing组件不是很熟悉,因此决定使用GridBagLayout创建汽车清单。

每行都有不同的面板,每个面板具有不同的租金价格和汽车名称。

汽车清单

列表中的所有面板都共享“详细信息”按钮。 我正在寻找一种方法,其中“详细信息”从被按下的面板中获取标题和价格文本,然后将其保存在变量中。

到目前为止,每当我按下它时,即使我按下了列表中的第一个按钮,它也只会保存并发送列表中最后一个面板中的文本。

车详情

这是按钮的事件:

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

编辑:

按照camickr的示例,剩下的就是使用放置在父面板中的位置从父面板获取标签。

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

在“详细信息”按钮的ActionListener中,您可以从ActionEvent中获取按钮,并从按钮中获取面板:

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

在ActionListener中,尝试以下操作:

    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
       }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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