How to add different actionlisteners to the same object

假装没事ソ 提交于 2019-12-25 11:55:45

问题


How do I add different actionlisteners to the p1 objects. I want the program to be able to set the textbar to the appropriate number when pressed with the appropriate button. Since they are not different variables I cannot simply use the code below(in my actionPerformed function),

if (e.getSource() == button1){ txtField.setText("1"); }

import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class Telephone extends Applet implements ActionListener
{
   TextField txtField;

   public void init() {
       setLayout(new BorderLayout());

       txtField = new TextField("");
       add(txtField, BorderLayout.NORTH);

       Panel p1 = new Panel();
       p1.setLayout(new GridLayout(4, 3));
       p1.add(new Button("1"));
       p1.add(new Button("2"));
       p1.add(new Button("3"));
       p1.add(new Button("4"));
       p1.add(new Button("5"));
       p1.add(new Button("6"));
       p1.add(new Button("7"));
       p1.add(new Button("8"));
       p1.add(new Button("9"));
       p1.add(new Button("*"));
       p1.add(new Button("0"));
       p1.add(new Button("#"));       
       add(p1, BorderLayout.CENTER);

   }

   public void actionPerformed(ActionEvent e) {


    }
}

回答1:


Don't have your GUI class also be your listener class as that's asking the class to do too much. Instead consider using anonymous inner listener classes or private inner classes. Incidentally, I don't see where you're adding any listeners to your buttons. Also, for my money, I'd create a Swing GUI, not an AWT GUI as Swing is much more robust and flexible.

Also note, for the example above, I would in fact give all my button objects the same action listener. If using Swing, I could simply get the ActionEvent object's actionCommand which would be the number String of interest. No need for 10 if blocks or a switch block.

For example, this demonstrates very simple logic of displaying the number in a JTextField, but has no calculation logic:

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;

import javax.swing.*;

public class CalcEg {
   private static final float BTN_FONT_SIZE = 18f;
   private static final String[][] BTN_LABELS = {
      {"7", "8", "9", "-"},
      {"4", "5", "6", "+"},      
      {"1", "2", "3", "/"},
      {"0", ".", "=", "*"}
   };
   private JPanel mainPanel = new JPanel();
   private JTextField textField = new JTextField(10);

   public CalcEg() {
      int rows = BTN_LABELS.length;
      int cols = BTN_LABELS[0].length;
      int gap = 4;

      JPanel buttonPanel = new JPanel(new GridLayout(rows, cols, gap, gap));
      for (String[] btnLabelRow : BTN_LABELS) {
         for (String btnLabel : btnLabelRow) {
            JButton btn = createButton(btnLabel);
            if ("0123456789.".contains(btnLabel)) {
               btn.setAction(new NumberListener(btnLabel));
            } 
            buttonPanel.add(btn);
         }
      }

      textField.setFont(textField.getFont().deriveFont(BTN_FONT_SIZE));

      mainPanel.setLayout(new BorderLayout(gap, gap));
      mainPanel.setBorder(BorderFactory.createEmptyBorder(gap, gap, gap, gap));
      mainPanel.add(textField, BorderLayout.PAGE_START);
      mainPanel.add(buttonPanel, BorderLayout.CENTER);
   }

   private JButton createButton(String btnLabel) {
      JButton button = new JButton(btnLabel);
      button.setFont(button.getFont().deriveFont(BTN_FONT_SIZE));
      return button;
   }

   public JComponent getMainComponent() {
      return mainPanel;
   }

   private class NumberListener extends AbstractAction {
      NumberListener(String actionCommand) {
         super(actionCommand);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         String actionCommand = e.getActionCommand();
         textField.setText(textField.getText() + actionCommand);
      }
   }

   private static void createAndShowGui() {
      CalcEg mainPanel = new CalcEg();

      JFrame frame = new JFrame("CalcEg");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel.getMainComponent());
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

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


来源:https://stackoverflow.com/questions/15606414/how-to-add-different-actionlisteners-to-the-same-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!