簡體   English   中英

將多個actionListener添加到多個JButton

[英]Add multiple actionListener to multiple JButtons

我正在使用GUI,並嘗試獲取不同的按鈕來執行不同的任務。

當前,每個按鈕都指向相同的ActionListener。

public class GUIController {

public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}
public static void createAndShowGUI() {
    JFrame frame = new JFrame("GUI");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(new GridLayout(3,3));

    JLabel leight =new JLabel("8");
    frame.getContentPane().add(leight);
    JLabel lfive =new JLabel("0");
    frame.getContentPane().add(lfive);
    JLabel lthree =new JLabel("0");
    frame.getContentPane().add(lthree);

    JButton beight =new JButton("Jug 8");
    frame.getContentPane().add(beight);
    JButton bfive =new JButton("Jug 5");
    frame.getContentPane().add(bfive);
    JButton bthree =new JButton("Jug 3");
    frame.getContentPane().add(bthree);

    LISTN ccal = new LISTN (leight,lfive,lthree);

    beight.addActionListener(ccal);
    bfive.addActionListener(ccal);
    bthree.addActionListener(ccal);

    frame.pack();
    frame.setVisible(true);

}

}

我的動作偵聽器文件

public class JugPuzzleGUILISTN implements ActionListener {
JLabel leight;
JLabel lfive;
JLabel lthree;

JugPuzzleGUILISTN(JLabel leight,JLabel lfive, JLabel lthree){
    this.leight = leight;
    this.lfive = lfive;
    this.lthree = lthree;
}

public void actionPerformed(ActionEvent e) {
    }

}
}

我在ActionEvent中編寫的所有內容都適用於所有三個按鈕,如何使每個按鈕具有自己的功能? 非常感謝!

如何使每個按鈕都有自己的功能

向每個按鈕添加一個不同的ActionListener。

更好的是,使用Action而不是ActionListener。 一個Action只是一個花哨的ActionListener,它具有更多的屬性。

閱讀Swing教程中有關如何使用動作的部分, 獲取定義內部類的示例,以便您可以為每個按鈕創建唯一的Action

我在ActionEvent中編寫的所有內容都適用於所有三個按鈕,如何使每個按鈕具有自己的功能?

您具有希望所有3個按鈕都能觸發的類似操作。 但是,您還需要為每個按鈕實現不同的功能。

一種方法是創建3個以上的偵聽器,每個偵聽器將添加到各自的按鈕中。 因此,每個按鈕現在將添加2個偵聽器(您當前的一個+新創建的偵聽器)。

//Example:

beight.addActionListener(ccal);
bfive.addActionListener(ccal);
bthree.addActionListener(ccal);

beight.addActionListener(ccal_beight);
bfive.addActionListener(ccal_bfive);
bthree.addActionListener(ccal_bthree);

還有其他方法,例如在當前的偵聽器中使用if語句來檢查單擊了哪個按鈕,但是我發現使用較低的代碼耦合更容易維護單獨的偵聽器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM