本文介绍了如何向 NetBeans GUI Builder 中的多个组件添加相同的侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 NetBeans GUI Builder 创建一个小型应用程序.首先,让我说我可以手工编写所有代码并立即解决这个问题.但是,我想学习如何使用 GUI Builder.这是我的警告,所有不使用它的建议都会被否决.

I am using the NetBeans GUI Builder to create a small application. To begin, let me just say that I can code everything by hand and solve this problem right away. However, I want to learn how to use the GUI Builder. This is my warning that all suggestions to not use it will get a down vote.

话虽如此,我目前的情况是我有几个 JFormattedTextField ,如果用户输入格式无效的数据,我想在其中显示错误消息.每种情况的逻辑都是一样的.唯一的区别是根据预期的确切格式(即四位数年份、正整数等)显示不同的错误消息.我想简单地编写一个可以为每个文本字段重复使用的侦听器.我为第一个文本框编写了以下方法:

With that said, my current situation is that I have several JFormattedTextFields where I want to display an error message if the user enters data with an invalid format. The logic is the same in every case. The only difference will be to display a different error message depending on the exact formatting expected (i.e. a four digit year, a positive integer, etc.). I would like to simply write one listener that can be reused for every text field. I wrote the following method for the first text box:

private void formattedTextFieldFocustLost(java.awt.event.FocusEvent evt) {
    JFormattedTextField source = (JFormattedTextField)evt.getComponent();

    if (!source.isEditValid()) {
        // TODO: Need a better error message.
        JOptionPane.showMessageDialog(this, "Invalid input.", "Input Error", JOptionPane.ERROR_MESSAGE);
        source.requestFocusInWindow();
    }
}

方法签名由 NetBeans 生成,并从扩展 FocusAdapter 的匿名内部类的生成中调用.现在,当我转到 NetBeans 中的设计"视图并单击另一个组件的 focusLost 事件的组合框时,该方法名称不会显示.

The method signature is generated by NetBeans and is called from a generated of an anonymous inner class which extends FocusAdapter. Now when I go to the Design view in NetBeans and click on the combo box for the focusLost event of another component, this method name doesn't show up.

我还尝试创建一个命名内部类,它扩展了 FocusAdapter.这也不会显示在事件处理程序组合框中.

I also tried to create a named inner class which extends FocusAdapter. This doesn't show up in the event handler comboboxes, either.

如何为所有文本字段创建一个方法?

What do I do to create a single method for all of my text fields?

推荐答案

如果您已经编写了处理程序,请说 btnActionPerformed,复制名称.

If you have written the handler already, say btnActionPerformed, copy the name.

在设计视图中,右键单击要附加处理程序的组件 > 属性 > 事件 > "..." 按钮 > 添加 > 在空白字段中粘贴现有处理程序名称,然后单击确定.

In design view, right-click the component where you want to attach the handler > Properties > Events > "..." button > Add > paste existing handler name in blank field and click OK.

(Netbeans 7.3.1)

(Netbeans 7.3.1)

这篇关于如何向 NetBeans GUI Builder 中的多个组件添加相同的侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 04:20