簡體   English   中英

如果我有多個具有相同文本的按鈕,如何檢查我的 JFrame 中的哪個按鈕被單擊?

[英]How to check which button in my JFrame was clicked if I have more than one button with the same text?

我在java中設計黑白棋游戲,結構如下:

一種。 一個帶有 64 個按鈕的 JFrame。 按鈕存儲在一個數組中。

JButton 將有黑色圓圈或白色圓圈。

因此,每當要進行移動時,程序都會突出顯示可以進行移動的那些框,但是當所有按鈕都以相同方式突出顯示時,我怎么知道點擊了哪個按鈕(我想知道該按鈕的索引) ?

您可能在所有按鈕上都添加了一個 ActionListener。 然后傳遞給 performAction 的 ActionEvent getSource 有信息。 這很丑陋,就像測試按鈕文本一樣。

比較正常的就是使用Action (看一看),設置不同的動作承載64個狀態。

public BoardAction extends AbstractAction {
    public BoardAction(int x, int y) { ... }

    @Override
    public void actionPerformed(ActionEvent e) {
        ...
    }
}

JButton button = new JButton(new BoardAction(x, y));

在 Action 中,您還可以指定按鈕標題,並且 Action 也可以(重新)在 JMenuItem 等中使用。

由於需要額外的間接性,大多數示例使用 ActionListener,但 Swing 內部經常使用 Action。 例如,有一個帶有剪切/復制/粘貼的編輯菜單和一個帶有剪切/復制/粘貼圖標、上下文菜單的工具欄。

根據我的理解,您正在嘗試檢測特定 JButton 何時被按下。 最簡單的方法是實現 ActionListener。

public class ExampleClass implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == buttonNameOne)
            System.out.println("Button One was pressed");
        else if (e.getSource() == buttonNameTwo)
            System.out.pringln("Button Two was pressed);
    }
}

檢測動作

每當按下任何按鈕時,actionPerformed(ActionEvent e) 方法都會激活。

記錄動作源

當它被按下時,它會自動檢測這個動作的來源(按鈕)並將其存儲在參數“e”中。

使用記錄的動作來源

通過簡單地執行 e.getSource(),您可以獲取調用此方法的組件,並將其與程序中預先存在的組件進行比較。

自定義參數

對於每個 if 語句,您都可以自定義和個性化條件的結果(即按下的按鈕是否等於特定按鈕)。 通過將參數放在每個條件語句的主體中來做到這一點:

if (e.getSource == sayHiButton)
   System.out.println("Hi");

暫無
暫無

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

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