在NetBeans事件列表中显示定制组件操作事件

ibps3vxo  于 2022-11-10  发布在  其他
关注(0)|答案(2)|浏览(159)

我尝试在NetBeans中创建一个自定义组件,该组件在面板上包含2个按钮。

import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JPanel;

public class CustomComponent extends JPanel {

    JButton button1 = new JButton("Button 1");
    JButton button2 = new JButton("Button 2");

    public CustomComponent() {

        setLayout(new FlowLayout());
        add(button1);
        add(button2);

        button1.setSize(100, 30);
        button2.setSize(100, 30);
    }

}

当我在另一个项目的JFrame(使用GUI设计器)上使用此自定义组件时,这两个按钮需要有两个不同的ActionPerformed事件,并且这些事件必须显示在Netbean的事件列表中。是否可以做到这一点?
(目前,我只能看到JPanel拥有的事件。)

先谢谢你

hmtdttj4

hmtdttj41#

按照上面的链接,你可以添加一个动作监听器,如下所示。这个例子针对的是一个通用的ActionEvent,但是你也可以修改代码来处理其他类型的事件:

//The button to add an event to
JButton test = new JButton();

//The first option
test.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        System.out.println("Action performed");
    }
});

//The second option. This only works on Java 8 and newer
test.addActionListener((ActionEvent e) ->
{
    System.out.println("Action performed");
});

//Or a simplified form for a single call
test.addActionListener(e -> System.out.println("Action performed"));

在您的案例中有一个工作示例:

public CustomComponent() {

    setLayout(new FlowLayout());
    add(button1);
    add(button2);

    button1.setSize(100, 30);
    button2.setSize(100, 30);

    //Add events
    button1.addActionListener(e -> System.out.println("Button 1 action performed"));
    button2.addActionListener(e -> System.out.println("Button 2 action performed"));
}
x759pob2

x759pob22#

我没有通过构造函数传递侦听器,而是创建了另一个setter,因为GUI不支持它。

public void setListners(ActionListener btn1ActionListner, ActionListener btn2ActionListner){
        button1.addActionListener(btn1ActionListner);
        button2.addActionListener(btn2ActionListner);
    }

在另一个项目上

public NewJFrame() {
        initComponents();

        ActionListener al1 = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null, "Button 1");
            }
        };

        ActionListener al2 = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null, "Button 2");
            }
        };

        customComponent1.setListners(al1, al2);
    }

相关问题