亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何讓 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 關注
  • 142 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號