質問

My question is very simple: I'm trying to add a WindowListener and an onClose Listener (or Listener in general), but what I don't know how to do is where to add the code in Netbeans 8.0.

I have this doubt because Netbeans creates the JFrame entirely by itself, and hides that code. I have to add the Listener somewhere in this custom code created by Netbeans or in the Class Constructor, or any other place?

役に立ちましたか?

解決

You can add many listeners to the JFrame using JFrame's Properties -> Events and Properties (Bindings can help you sometimes too).

If you don't get what you need, just place your code into the constructor or - if it's a lot - make private method you call in the ctor.

I mostly prefer a private method than putting all into ctor, but that's really something of your choice.

Example:

public class Example extends javax.swing.JFrame
{
    public Example()
    {
        initComponents(); // This is generated by NB - do NOT remove!

        addListeners(); // add listeners here
    }


    /**
     * Adds listeners to the frame
     */ 
    private void addListeners()
    {
        // Add your listeners here as usual
        this.addWindowListener(new WindowListener()
        {
            @Override
            public void windowOpened(WindowEvent e)
            {
                /* ... */
            }

            /* Other methods of WindowListener ... */
        });
    }

    /* ... */
}

Just one thing here: Add your listeners after initComponents() - that's the generated method witch initializes all components - otherwise some components may not be ready.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top