无法在gridbaglayout中添加动作侦听器

时间:2017-10-23 12:49:39

标签: java actionlistener gridbaglayout

这是我的代码我怎么能添加动作监听器我已经尝试了我已知的方法但由于静态方法我无法添加它.Netbeans IDE建议程序中的动作监听器但是我无法使用它可以有人提出一种更简单的方法来声明动作监听器。

public class Calc {

public static void addComponentsToPane(Container pane) {


        pane.setLayout(new GridBagLayout());
        GridBagConstraints gBC = new GridBagConstraints();

        gBC.ipady = 40;
        gBC.ipadx = 40;

        JTextField JTextField = new JTextField("Hello");
        gBC.fill = GridBagConstraints.HORIZONTAL;
        gBC.gridx = 0;
        gBC.gridy = 0;
        gBC.gridwidth = 4;
        JTextField.setEditable(false);
        pane.add(JTextField, gBC);

        //JButton jbnButton;
        gBC.gridwidth = 1;

        JButton b7 = new JButton("7");
        gBC.gridx = 0;
        gBC.gridy = 1;
        pane.add(b7, gBC);
        // more calculator buttons declared here

//这里是如何建议actionlistner

        b0.addActionListener(new java.awt.event.ActionListener() {
        @Override
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            b0ActionPerformed(evt);
        }

        private void b0ActionPerformed(ActionEvent evt)  }
        `
    });
    b0.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
        b0ActionPerformed(evt);
    }
    private void b0ActionPerformed(Actionenter Event evt) {}
    });}

    private static void createAndShowGUI() {}

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

}

1 个答案:

答案 0 :(得分:0)

我试试看你。您可以在addComponentsToPane方法中为您声明的每个组件添加动作侦听器。此外,您忘记传递帧,以便您可以像我一样在主方法中传递它。

public class Calc {

public static void addComponentsToPane(Container pane) {

    pane.setLayout(new GridBagLayout());
    GridBagConstraints gBC = new GridBagConstraints();

    gBC.ipady = 40;
    gBC.ipadx = 40;

    JTextField JTextField = new JTextField("Hello");
    gBC.fill = GridBagConstraints.HORIZONTAL;
    gBC.gridx = 0;
    gBC.gridy = 0;
    gBC.gridwidth = 4;
    JTextField.setEditable(false);
    pane.add(JTextField, gBC);

    //JButton jbnButton;
    gBC.gridwidth = 1;

    JButton b7 = new JButton("7");
    gBC.gridx = 0;
    gBC.gridy = 1;
    pane.add(b7, gBC);
    // more calculator buttons declared here

    b7.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            // Write your action here

        }
    });

}

private static void createAndShowGUI(JFrame pane) {
    addComponentsToPane(pane);
    pane.setVisible(true);
}

public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI(new JFrame());
        }
    });
}

}