【问题标题】:how to put actionlistenerand actioncommand to multiple jbuttons如何将actionlistener和actioncommand放到多个jbuttons
【发布时间】:2016-03-10 02:03:42
【问题描述】:

所以我希望我的按钮标记为 1-9,但我不想列出每个按钮的所有动作侦听器和动作命令。我该怎么做呢

而且我不能使用 add.ActionListener(this) 那我可以用什么

    JButton[] button = new JButton[9];
    panel.setLayout(new GridLayout(3,3));
    for (int i = 0; i < button.length; i++) {
        button[i] = new JButton();
        panel.add(button[i]);
        String bu = Integer.toString(i);
        button[i].setActionCommand(bu);
        button[i].addActionListener(new ActionListener());

抱歉,我是 java swing 新手,所以还是有点混乱

【问题讨论】:

  • 也许可以考虑使用Action,见How to Use Actions
  • @kina I cannot use add.ActionListener(this) 我将其解释为“您仍然可以使用ActionListener”只是您不想让容器类实现ActionListener。对吗?

标签: java swing jbutton


【解决方案1】:

我不能使用 add.ActionListener(this) 那我可以用什么

您创建一个实现 ActionListener 的类。

或者更好的是创建一个实现 Action 的类。 Action 与 ActionListener 相同。好处是 Action 可以与 Key Bindings 一起使用。

这是一个基本的例子:

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.setCaretPosition( display.getDocument().getLength() );
                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(30, 30) );
            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()
    {
        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();
            }
        });
    }
}

现在您可以单击按钮或输入数字,然后该值将插入到文本字段中。

【讨论】:

    【解决方案2】:

    只需添加执行的主要操作方法。

    示例如下:

    public void actionPerformed(ActionEvent e){
           // your todo code here
    }
    

    确保导入适当的包。

    【讨论】:

      【解决方案3】:

      你必须实现actionListener

      公共类 Butt 实现 ActionListener {

      public JPanel method()
      {
      
      JPanel panel = new JPanel();
      JButton[] button = new JButton[9];
      panel.setLayout(new GridLayout(3, 3));
      for (int i = 0; i < button.length; i++)
      {
          button[i] = new JButton(""+i);
          panel.add(button[i]);
          String bu = Integer.toString(i);
          button[i].setActionCommand(bu);
          button[i].addActionListener(this);
      
      }
      return panel;
      }
      
      @Override
      public void actionPerformed(ActionEvent e)
      {
      
      }
      
      public static void main(String[] args)
      {
      
      JFrame frame = new JFrame();
      frame.add(new Butt().method());
      frame.setVisible(true);
      frame.setSize(500, 500);
      }
      

      } 看看现在没有错误。

      results

      【讨论】:

        【解决方案4】:

        而且我不能使用 add.ActionListener(this) 那我可以用什么

        我将你这里的意思解释为“你不允许让容器类实现ActionListener,但仍然允许使用ActionListener”。

        如果是这样,您至少还有 2 个选择:

        • 为 ActionListener 创建一个匿名类
        • 为 ActionListener 创建一个内部类

        使用带有内部类 Actionlistener 的 GridLayout 的示例:

        如何将actionlistener和actioncommand放到多个jbuttons

        下面使用内部类来处理按钮的动作。

        class MainPanel extends JPanel  //not implementing ActionListener here
        {  
            private JButton[] btns;
        
            public MainPanel(){
                setPreferredSize(new Dimension(150, 150));
                setLayout(new GridLayout(3, 3));
                initComponents();
                addComponents();
            }
        
            private void initComponents(){
                btns = new JButton[9];
                ButtonHandler bh = new  ButtonHandler();
                for(int x=0; x<btns.length; x++){
                    btns[x] = new JButton(Integer.toString(x+1));
                    btns[x].addActionListener(bh);    //NOT using addActionListener(this)
                }                
            }
        
            private void addComponents(){
                for(int x=0; x<btns.length; x++)
                    add(btns[x]);                     //Add in sequential order into grid layout   
            }
        
            private class ButtonHandler implements ActionListener
            {
                @Override
                public void actionPerformed(ActionEvent e){
                    String s = ((JButton)e.getSource()).getText();
                    JOptionPane.showMessageDialog(null, "Button " + s + " was clicked.");
                }   
            }
        }
        

        最后,在 EDT 中运行您的代码:

        class TestRunner
        {
            public static void main(String[] args)
            {
                SwingUtilities.invokeLater(new Runnable(){
                    @Override
                    public void run(){
                        JFrame frame = new JFrame("Buttons Pad");
                        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        frame.add(new MainPanel());
                        frame.pack();
                        frame.setLocationRelativeTo(null);
                        frame.setVisible(true);             
                    }
                }); 
            }
        }
        

        【讨论】:

        • @kina 你可以看看这里看看有没有帮助。
        猜你喜欢
        • 1970-01-01
        • 2014-10-26
        • 2015-11-07
        • 1970-01-01
        • 2015-07-18
        • 2013-02-14
        • 2015-06-08
        • 1970-01-01
        • 2013-05-17
        相关资源
        最近更新 更多