1

私は JFrame を持っています。ボタンの 1 つはフレーム自体を親として渡す必要があります。私はthisキーワードを使用していましたが、JFrame の代わりに actionlistener を返しています。回避策はありますか、それとも私の書き方が悪いのでしょうか?

コード:

start.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            kMeans=new KMeans(mainWindow.table, Integer.parseInt(centroids.getText()),this);
        }
    });
4

5 に答える 5

2

このコードのため:

new ActionListener()
{
    public void actionPerformed(ActionEvent e)
    {
        kMeans=new KMeans(mainWindow.table, Integer.parseInt(centroids.getText()),this);
    }
}

実際に新しいオブジェクトを作成しました。thisこの実装のメソッドでキーワードを使用するActionListenerと、文字通りthisオブジェクトが使用されますActionListener

上記のブロックの外で使用するthisと、JFrame インスタンスを参照します。

thisActionListener 内の AFrame のインスタンスを参照する場合はAFrame.this、コメントに記載されているように実行できます。AFrame はフレーム クラスの名前ですが、コードにどの名前があるかわかりません。

于 2013-03-11T16:34:43.587 に答える
2

回避策があります。this外部クラスへの参照でキーワードを使用するには、 を使用できますClassName.this。例えば:

class MyFrame extends JFrame {
    public void someMethod () {
        someButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                ActionListener thisListener = this; // obviously
                MyFrame outerThis = MyFrame.this; // here's the trick
            }
        });
    }
}
于 2013-03-11T16:37:33.280 に答える
1

外部クラスの参照を匿名の内部クラスに渡そうとしています。そのためには、 を使用する必要がありますOuterClassName.this。以下の例を参照してください。

import javax.swing.*;
import java.awt.event.*;
class FrameExample extends JFrame
{
    private void createAndShowGUI()
    {
        JButton button = new JButton("Click");
        getContentPane().add(button);
        button.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent evt)
            {
                JOptionPane.showMessageDialog(FrameExample.this,"This is the message","Message",JOptionPane.OK_OPTION);//Passing the reference of outer class object using FrameExample.this
            }
        });
        pack();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }
    public static void main(String[] args) 
    {
        SwingUtilities.invokeLater( new Runnable()
        {
            @Override
            public void run()
            {
                FrameExample fe = new FrameExample();
                fe.createAndShowGUI();
            }
        });
    }
}
于 2013-03-11T16:41:22.690 に答える
0

You should use JFrameClassName.this. So if the name of the JFrame is MainWindow, your code would be:

new ActionListener()
{
    public void actionPerformed(ActionEvent e)
    {
        kMeans=new KMeans(mainWindow.table, Integer.parseInt(centroids.getText()), MainWindow.this);
    }
}
于 2013-03-11T16:36:40.383 に答える
0

Use the getSource() method in the ActionEvent to acces the object where the event occured. Example : JMenuItem menuItem = (JMenuItem) e.getSource();

于 2013-03-11T16:39:32.723 に答える