我正在嘗試在 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();

慕桂英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
}
}
添加回答
舉報
0/150
提交
取消