为了账号安全,请及时绑定邮箱和手机立即绑定

如何让 JButton 知道它在哪个面板上被点击?

如何让 JButton 知道它在哪个面板上被点击?

不负相思意 2022-11-02 17:17:04
我正在尝试在 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);                }            });
查看完整描述

2 回答

?
紫衣仙女

TA贡献1839条经验 获得超15个赞

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

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


查看完整回答
反对 回复 2022-11-02
?
慕桂英4014372

TA贡献1871条经验 获得超13个赞

在 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

       }

    }


查看完整回答
反对 回复 2022-11-02
  • 2 回答
  • 0 关注
  • 82 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信