在Netbeans中添加侦听器 [英] Adding listeners in Netbeans
问题描述
我的问题很简单:我试图添加一个WindowListener和一个onClose Listener(或通常的Listener),但是我不知道怎么做是在Netbeans 8.0中的哪里添加代码.
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.
我有一个疑问,因为Netbeans完全自己创建了JFrame,并隐藏了该代码.我必须在Netbeans创建的自定义代码中,类构造器中或其他任何地方添加侦听器?
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?
推荐答案
您可以使用 JFrame's Properties -> Events
和 Properties
( Bindings
有时也可以为您提供帮助.
You can add many listeners to the JFrame using JFrame's Properties -> Events
and Properties
(Bindings
can help you sometimes too).
如果您没有得到所需的东西,只需将代码放入构造器中,或者-如果数量很多,请使用私有方法 调用在ctor中.
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.
与将所有内容都放入ctor相比,我更喜欢私有方法,但这确实是您的选择.
I mostly prefer a private method than putting all into ctor, but that's really something of your choice.
示例:
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 ... */
});
}
/* ... */
}
这里只有一件事:在之后 initComponents()
添加您的侦听器-这是生成的方法,它初始化了所有组件-否则某些组件可能尚未准备就绪.
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.
这篇关于在Netbeans中添加侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!