1

マウス プレス イベントに関連付けられた青、白、赤、緑 (myComponent) の 4 つの正方形があるとします。ある時点で、マウスがそのうちの 1 つ (たとえば、黄色のもの) の上で押されると、イベントがアクティブになります。

現在、制御フラックスはイベント処理関数内にあります。ここからこれを引き起こした MyComponent - 黄色の四角形 - を取得するにはどうすればよいですか?

編集

別の質問があります。コンポーネントの位置を知る方法はありますか? 私の問題は、私が言ったことよりも少し複雑です。

基本的に、正方形でいっぱいのグリッドがあります。正方形の 1 つをクリックすると、それがどれであるかを知る必要があるため、マトリックスを更新できます。問題は、自分で計算すると、特定の解像度でしか機能しないということです。

GridBagLayout があり、その中に myComponents があります。コンポーネント[2][2]のように、どのコンポーネントが中断を引き起こしたのかを正確に知る必要があります。

つまり、どのコンポーネントがそれを行ったかはわかりますが、それがマトリックスのどこにあるかはわかりません。

4

2 に答える 2

4

MouseEvent.getSource()イベントが最初に発生したオブジェクトを返します。

がありGridBagLayout、その中に がありmyComponentsます。component[2][2]どのコンポーネントが中断を引き起こしたかを正確に知る必要があります。

たとえば、インデックスをマトリックスに追加するときに(2,2)、それぞれの中にインデックスを格納できます。myComponentそうすれば、コンポーネントが与えられれば、マトリックス内での位置をいつでも特定できます。

class MyComponent extends JButton
{
    final int i; // matrix row
    final int j; // matrix col

    // constructor
    MyComponent(String text, int i, int j)
    {
        super(text);
        this.i = i;
        this.j = j;
    }

    ...
}
于 2009-02-25T01:57:54.787 に答える
1

MouseListener(または、すべてのMouseListener MouseEvent`]MouseAdapterをオーバーライドする必要がない場合は3を追加することにより、クリックされたコンポーネントを取得するために使用できます。MouseListener' methods) to each of your colored boxes, when an event such as a mouse click occurs, thewill be called with a [

例えば:

final MyBoxComponent blueBox =   // ... Initialize blue box
final MyBoxComponent whiteBox =  // ... Initialize white box
final MyBoxComponent redBox =    // ... Initialize red box
final MyBoxComponent greenBox =  // ... Initialize green box

MouseListener myListener = new MouseAdapter() {
    public void mouseClicked(MouseEvent e)
    {
        // Obtain the Object which caused the event.
        Object source = e.getSource();

        if (source == blueBox)
        {
            System.out.println("Blue box clicked");
        }
        else if (source == whiteBox)
        {
            System.out.println("White box clicked");
        }
        // ... and so on.
    }
};

blueBox.addMouseListener(myListener);
whiteBox.addMouseListener(myListener);
redBox.addMouseListener(myListener);
greenBox.addMouseListener(myListener);
于 2009-02-25T02:07:15.810 に答える