【问题标题】:Adding action to a JButton when using a for loop使用 for 循环时向 JButton 添加操作
【发布时间】:2013-12-13 06:49:05
【问题描述】:

我正在尝试动态添加按钮 (JButtons),它每次都会更改名称。我用 for 循环来做这件事并没有真正的问题。但是当添加一个动作监听器或识别哪个按钮被按下时,事情就不那么好了。

MyFrame.java

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

public class MyFrame extends JFrame implements ActionListener 
{
    private JPanel panel;
    private static JButton[] buttons  = new JButton[18];
    // set all static calculate JButtons
    private static JButton equalsBtn, addBtn, subBtn, multiBtn, divBtn, clearBtn, plusMinusBtn, decimalBtn;
    // set all static number JBtuttons
    private static JButton zeroBtn, oneBtn, twoBtn, threeBtn, fourBtn, fiveBtn, sixBtn, sevenBtn, eightBtn, nineBtn;
    private static JTextField resultField;
    // numOne is the first row of figures en the second numSecond is the second row
    private static double numOne, numSecond, result;
    private static double plusMinus;
    private static int addClick = 0, subClick = 0, multiClick = 0, divClick = 0;
    private static int clearField;

    public MyFrame() {
        // configure the JFrame
        super("Rekennen maar!");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        setSize(230, 370);
        setLocationRelativeTo(null);

        // confugure the JPanel
        panel = new JPanel();
        panel.setSize(230, 370);
        panel.setLayout(new GridLayout(5, 0));

        // array string whit all the button names
        String a_btnNames[] = {"clearBtn", "plusMinusBtn", "divBtn", "multiBtn", "sevenBtn", "eightBtn", "nineBtn", "subBtn", "fourBtn", "fiveBtn", "sixBtn",                               "addBtn", "oneBtn", "twoBtn", "threeBtn", "equalsBtn", "zeroBtn", "decimalBtn"};
        // array String whit all button characters
        String a_btnCharts[] = {"C", "+/-", "/", "*", "7", "8", "9", "-", "4", "5", "6", "+", "1", "2", "3", "=", "0", "."};

        for(int i = 0; i < buttons.length; i++)
        {
            // make new button name 
            buttons[i]  = new JButton(a_btnNames[i]);
            // add button to panel
            panel.add(new JButton(a_btnCharts[i]));
            //System.out.println(buttons[i]);
        }

        // add panel when he's filled 
        add(panel);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        // press the button
        if ( e.getSource() == ...... ) {
            System.out.println("123");  
        }   
    } 
}

Main.java

public class Main {
    public static void main(String[] arg) {
        MyFrame mf = new MyFrame();
    }
}

【问题讨论】:

  • 你为什么使用new JButton("" + a_btnNames[i]);new JButton(a_btnNames[i]); 也可以。另外,您不会创建buttons.length 按钮,而是创建buttons.length*2。尝试使用buttons[i]=new JButton(...); panel.add(buttons[i])

标签: java swing arraylist jpanel jbutton


【解决方案1】:

把循环改成这样。

for(int i = 0; i < buttons.length; i++)
    {
        // make new button name 
        JButton btn = new JButton("" + a_btnNames[i]);
        buttons[i]  = btn;
        btn.addActionListener(this);
        // add button to panel
        panel.add(btn);
        //System.out.println(buttons[i]);
    }

然后有一个像这样的 actionPerformed()。

public void actionPerformed(ActionEvent evt) {
   Object src = evt.getSource();
   if (src == buttons[0]) {
     //First button actions
   } else if (src == buttons[1]) {
     //Second button actions
   }
}

应该可以。

【讨论】:

  • 我会用 switch 语句替换 if 块,否则 +1。忽略最后一点,只记得Java不喜欢开关
【解决方案2】:

按下按钮时没有任何监听。创建每个按钮时,必须为它们提供动作侦听器。

此外,您应该添加与您创建的按钮相同的按钮。

buttons[i] = new JButton("" + a_btnNames[i]);
//buttons[i] should now be added to the panel

新的 for 循环应该是...

for(int i = 0; i < buttons.length; i++){
    buttons[i] = new JButton("" + a_btnNames[i]); //create button & add to array
    buttons[i].addActionListener(this); //add an action listener to the current button
    panel.add(buttons[i]); //add that same button to the panel

}

【讨论】:

    【解决方案3】:

    变化不大

    for(int i = 0; i < buttons.length; i++)
        {
            // make new button name 
            buttons[i]  = new JButton(a_btnCharts[i]);
            buttons[i].setName(a_btnNames[i]); // assign button name
            buttons[i].addActionListener(this); // assign action listener 
            // add button to panel
            panel.add(buttons[i]);
        }
    

    @Override
    public void actionPerformed(ActionEvent e) {
        // press the button
          System.out.println(e.getActionCommand()); 
          JButton btn=(JButton)e.getSource();
          System.out.println(btn.getName());  // use name or action command in if statment
    } 
    

    你的主要方法应该是

    public static void main(String[] arg) {
        SwingUtilities.invokeLater( new Runnable() {
            @Override
            public void run() {
                MyFrame mf = new MyFrame();
            }
        });
    }
    

    阅读The Event Dispatch Thread

    【讨论】:

      【解决方案4】:

      记得先将 ActionListener 添加到 JButtons。然后,以这种方式使用 getSource() 对您的情况没有帮助,因为您没有保留对要添加到面板的 JButton 的引用。您可以改用 getActionCommand() - 默认行为是它返回按钮的标签,但您可以使用 setActionCommand(...) 覆盖它:

      if ( e.getActionCommand().equals(a_btnCharts[0] ) {
      

      【讨论】:

        【解决方案5】:
        1. 好吧,当您知道evt.getSource() 返回ActionEvent 的源组件时,我没有看到任何问题。

        2. 要将动作监听器注册到JButton 之类的组件,我们通常这样做:

          jButton.addActionListener(anActionListener);
          

          对于您的上下文,您可以使用this 的帮助传递ActionListener

        3. 不要将ActionListener 接口实现到某些不侦听此类事件或没有此类事件的类。如果需要,通过实现它来声明一个新类并使用该类的实例来注册监听器。

           class MyActionListener implements ActionListener
           {
               public void actionPerformed(ActionEvent e) {
                   // press the button
                }     
            }
          
            MyActionListener actionListener = new MyActionListener();
            jButton1.addActionListener(actionListener);
            jButton2.addActionListener(actionListener);
            jButton3.addActionListener(actionListener);
          

        我正在尝试动态添加按钮 (JButtons),它会更改名称 每次。

        但是您可能对使用new JButton("some text") 设置名称有误解。 这不会设置按钮的名称,而是设置文本内容。您需要改用button.setName("aName")

        但是,您始终可以使用getNamegetText 方法来识别您的特定按钮。

        public void actionPerformed(ActionEvent e) {
                // press the button
        
                JButton button = (JButton)e.getSource();
                Syestem.out.println(button.getName()); // get the name
                System.out.println(button.getText()) // get the text content
        
                if(button.getText().equals("clearBtn"))
                    // clear things for me
            } 
        

        【讨论】:

          【解决方案6】:

          循环遍历 JButton 数组:

          for (int i = 0; i < buttons.length; ++i) {
          if (e.getSource()==buttons[i]){
              System.out.println("Button name: " + a_btnNames[i] +"<> Char:"+ a_btnCharts[i] + " pressed");
          }
          

          }

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-07-09
            • 1970-01-01
            • 2013-02-06
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-07-24
            • 1970-01-01
            相关资源
            最近更新 更多