如何让 JButton 知道它在哪个面板上被点击? [英] How to make JButton know on which panel it has been clicked on?

查看:41
本文介绍了如何让 JButton 知道它在哪个面板上被点击?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 GUI 上模拟汽车租赁系统.由于我对 Swing 组件不是很熟悉,所以我决定使用 GridBagLayout 创建一个汽车列表.

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.

汽车列表

详细信息"按钮通过列表中的所有面板共享.我正在寻找一种方法,让详细信息"在按下时从面板获取标题和价格文本,然后将它们保存在变量中.

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.

汽车详情

这是按钮的事件:

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 的示例,剩下的就是使用标签在父面板中放置的位置从父面板获取标签.

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

推荐答案

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

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

这篇关于如何让 JButton 知道它在哪个面板上被点击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆