簡體   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