簡體   English   中英

使用JButton ActionListener在同一個包中運行不同的類

[英]Using JButton ActionListener to run different class in same package

我遇到了一個問題因為我對GUI比較新。

基本上把每個人都放在圖片中,我有一個包括以下內容的包:

  • 我的MainClass (包括GUI)
  • 單獨的類(除非單擊按鈕,否則不要運行它)
  • 另一個單獨的類,除非點擊特定按鈕,否則我不想運行。

所以我的MainClass GUI基本上就是控制器。

但是,老實說,我不知道如何去做。 被告知必須創建一個構造函數並使用getter / setter? 但是,我仍然不明白如何打電話給那個特定的課程,而另一個關閉“關閉”

謝謝。

好吧,有很多方法可以做到這一點......要么你為每個按鈕創建匿名監聽器,然后根據你想要做什么,觸發其他類中的方法等;

JButton b1 = new JButton();
b1.addActionListener(new ActionListener(){

    public void actionPerformed(ActionEvent e)
    {
        //Do something!
        OtherClass other = new OtherClass();
        other.myMethod();
    }
});

JButton b2 = new JButton();
b2.addActionListener(new ActionListener(){

    public void actionPerformed(ActionEvent e)
    {
        //Do something else!
        ...
    }
});

或者,您使用命令字符串並關聯您在公共偵聽器實現中接收actionPerformed時所比較的唯一命令(最終,最終);

//In your class, somewhere...
public final static String CMD_PRESSED_B1 = "CMD_PRESSED_B1";
public final static String CMD_PRESSED_B2 = "CMD_PRESSED_B2";

//Create buttons
JButton b1 = new JButton();
JButton b2 = new JButton();

//Assign listeners, in this case "this", but it could be any instance implementing ActionListener, since the CMDs above are declared public static
b1.addActionListener(this);
b2.addActionListener(this);

//Assign the unique commands...
b1.setActionCommand(CMD_PRESSED_B1);
b2.setActionCommand(CMD_PRESSED_B2);

然后,在你的監聽器實現中;

public void actionPerformed(ActionEvent e)
{
    if (e.getActionCommand().equals(CMD_PRESSED_B1)
    {
        //Do something!
        OtherClass other = new OtherClass();
        other.myMethod();
    }

    else if (e.getActionCommand().equals(CMD_PRESSED_B2)
    {
        //Do something else!
        ...
    }
}

暫無
暫無

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

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