简体   繁体   English

通过循环添加ActionListener

[英]Adding ActionListener with a loop

package javaapplication2;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;



public class Calc extends JFrame implements ActionListener {

private JButton b1, b2, b3, b4,b5,b6,b7,b8,b9,b0;
JButton[] label = {b1, b2, b3, b4, b5,b6,b7,b8,b9,b0};
String[] numKeys = {"1","2","3","4","5","6","7","8","9","0"};
JPanel numPad;
JPanel opPad;
JTextField displayPanel;

 public Calc() {
 super("Calculator");
 setSize(250,200);
    setDefaultCloseOperation(EXIT_ON_CLOSE);    
    setVisible(true);

    displayPanel = new JTextField(20);
    numPad = new JPanel();
    numPad.setLayout(new GridLayout(4, 3));  
    opPad = new JPanel();
    opPad.setLayout(new GridLayout(4, 1));
    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(numPad,BorderLayout.LINE_START);
    getContentPane().add(displayPanel, BorderLayout.PAGE_START);

    for (int i = 0; i <label.length;i++) {
        label[i] = new JButton(numKeys[i]);
        numPad.add(label[i]);
        label[i].addActionListener(this);


    }


    b2.addActionListener(this);

 }
 public void actionPerformed(ActionEvent a) {
    if (a.getSource() == b1)                     
            displayPanel.setText("1");
}


    public static void main(String args[]) {
Calc c = new Calc();






}
}

Hi, I've attempted to add numbered Jbuttons and add the action listener within a single loop in my attempt to make a calculator, The buttons are created and added to the panel however pressing "1" has no effect when it should display a 1 on the text field 嗨,我尝试添加编号的Jbutton并在单个循环内添加动作侦听器,以尝试制作一个计算器。这些按钮已创建并添加到面板中,但是当应显示1时按“ 1”无效在文本字段上

private JButton b1, b2, b3, b4,b5,b6,b7,b8,b9,b0;
JButton[] label = {b1, b2, b3, b4, b5,b6,b7,b8,b9,b0};

b1-b0 are null by default. b1-b0默认为null In this code: 在此代码中:

for (int i = 0; i <label.length;i++) {
    label[i] = new JButton(numKeys[i]);
    numPad.add(label[i]);
    label[i].addActionListener(this);
}

you assign the buttons to the label array, but not to the variables b1-b0. 您可以将按钮分配给label数组,而不分配给变量b1-b0。 Therefore you are actually checking for == null here 因此,您实际上是在这里检查== null

if (a.getSource() == b1)

The solution: remove those b1-b0 variables (you got the array anyway) and check like this: 解决方案:删除那些b1-b0变量(无论如何,您都得到了数组)并进行如下检查:

if (a.getSource() == label[0])

First you initialize the buttons to null and fill the label array with those null references. 首先,将按钮初始化为null,然后使用这些null引用填充标签数组。

During the loop, you create new objects and replace them in the label array. 在循环期间,您将创建新对象并将其替换为标签数组。 The original references are still pointing to null. 原始引用仍指向null。

In the action event you compare source = the new buttons with the old references which are pointing to null. 在动作事件中,您将source =新按钮与指向空的旧引用进行比较。 This is fault. 这是错

Just initialize the buttons before you add them to the label array, and don't create new buttons in your loop. 只需在将按钮添加到标签数组之前对其进行初始化,并且不要在循环中创建新按钮。 Fixed! 固定!

I would recommend using actioncommand in for loop and then checking the same in action listener, label[i].setActionCommand(numKeys[i]); 我建议在for循环中使用actioncommand ,然后在动作侦听器中检查相同的内容label[i].setActionCommand(numKeys[i]); and then in action listener something like this if (a.getActionCommand().equals("1")) 然后在动作监听器中, if (a.getActionCommand().equals("1"))

Check out this SO question, Java Button Action Command , it explains usage of ActionCommand 看看这个SO问题Java Button Action Command ,它解释了ActionCommand的用法

Hope this helps !!! 希望这可以帮助 !!!

I do not think it a good idea to store buttons in array but if you do still want it is better to use Arrais.asList () 我认为将按钮存储在数组中不是一个好主意,但是如果您仍然想要,最好使用Arrais.asList()

    import java.awt.*;
    import java.awt.event.*;
    import java.util.Arrays;
    import java.util.Collection;
    import javax.swing.*;

    class Calc extends JFrame {
      Collection<JButton> buttons = Arrays.asList(
        new JButton("1"),
        new JButton("2"),
        new JButton("3"),
        new JButton("4"),
        new JButton("5"),
        new JButton("6"),
        new JButton("7"),
        new JButton("8"),
        new JButton("9"),
        new JButton("0"));
      JPanel numPad;
      JPanel opPad;
      JTextField displayPanel;

      public Calc() {
        super("Calculator");
        setSize(250, 200);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);    

        displayPanel = new JTextField(20);
        numPad = new JPanel();
        numPad.setLayout(new GridLayout(4, 3));
        opPad = new JPanel();
        opPad.setLayout(new GridLayout(4, 1));
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(numPad, BorderLayout.LINE_START);
        getContentPane().add(displayPanel, BorderLayout.PAGE_START);    

        for (final JButton button : buttons) {
          button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
              displayPanel.setText(displayPanel.getText() + button.getText());
            }
          });
          numPad.add(button);
        }
      }

  public static void main(String args[]) {
    Calc c = new Calc();
  }
}

Write a generic Action so you don't have to use nested if statements: 编写通用动作,这样您就不必使用嵌套的if语句:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class CalculatorPanel extends JPanel
{
    private JTextField display;

    public CalculatorPanel()
    {
        Action numberAction = new AbstractAction()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                display.replaceSelection(e.getActionCommand());
            }
        };

        setLayout( new BorderLayout() );

        display = new JTextField();
        display.setEditable( false );
        display.setHorizontalAlignment(JTextField.RIGHT);
        add(display, BorderLayout.NORTH);

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout( new GridLayout(0, 5) );
        add(buttonPanel, BorderLayout.CENTER);

        for (int i = 0; i < 10; i++)
        {
            String text = String.valueOf(i);
            JButton button = new JButton( text );
            button.addActionListener( numberAction );
            button.setBorder( new LineBorder(Color.BLACK) );
            button.setPreferredSize( new Dimension(50, 50) );
            buttonPanel.add( button );

            InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
            inputMap.put(KeyStroke.getKeyStroke(text), text);
            inputMap.put(KeyStroke.getKeyStroke("NUMPAD" + text), text);
            button.getActionMap().put(text, numberAction);
        }
    }

    private static void createAndShowUI()
    {
//      UIManager.put("Button.margin", new Insets(10, 10, 10, 10) );

        JFrame frame = new JFrame("Calculator Panel");
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.add( new CalculatorPanel() );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

This example also uses Key Bindings , so you can press "1" on the keyboard or click the "1" button. 此示例还使用了Key Bindings ,因此您可以在键盘上按“ 1”或单击“ 1”按钮。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM