Java ActionListener将变量返回到包含ActionListener的方法

时间:2015-06-29 21:37:36

标签: java swing return listener

我有一个像这样的方法,给出一个JButton数组,并在按下它们时返回它们的文本:

public static String foo(JButton[] buttons) {
    for (JButton i : buttons) {
        i.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                return i.getText();
            }
        });
    }
}

但是,当然,这段代码不会编译,因为我将一个变量返回给null方法。那么,我如何i.getText()返回其输出foo()方法?

编辑,所有代码:

import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class JCustomFrame {
    public static void showMessageFrame(String title, String message,
            String[] textOnButtons, ImageIcon icon) {
        final JFrame frame = new JFrame();
        JPanel panel = new JPanel();

        panel.setLayout(new GridBagLayout());
        panel.setBackground(Color.WHITE);

        GridBagConstraints c = new GridBagConstraints();
        c.anchor = GridBagConstraints.EAST;
        c.fill = GridBagConstraints.RELATIVE;
        c.gridx = 0;
        c.gridy = 0;
        c.insets = new Insets(5, 5, 5, 5);

        JLabel messageLabel = new JLabel(message);
        messageLabel.setFont(messageLabel.getFont().deriveFont(16.0f));

        panel.add(messageLabel, c);

        c.gridy = 1;
        c.gridx = 0;
        for (int i = 0; i < textOnButtons.length; i++) {
            JButton button = new JButton(textOnButtons[i]);
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    return ((JButton) arg0.getSource()).getText();
                    frame.dispose();
                }
            });
            button.setFont(button.getFont().deriveFont(16.0f));
            panel.add(button, c);
            c.gridx++;
        }

        if (icon == null) {
            frame.setIconImage(new BufferedImage(1, 1,
                    BufferedImage.TYPE_INT_ARGB_PRE));
        } else {
            frame.setIconImage(icon.getImage());
        }
        frame.add(panel);
        frame.setTitle(title);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.pack();
    }

    public static void main(String[] args) {
        JCustomFrame.showMessageFrame("Test Frame",
                "Do you really want to do this?", new String[] { "Hell No",
                        "Sure, Why Not" }, null);
    }
}

2 个答案:

答案 0 :(得分:4)

这句话没有意义:

  

那么,我怎么能让i.getText()返回它的输出foo()方法?

在将ActionListener添加到按钮后,方法foo()不再运行,并且当用户按下按钮时,根据事件驱动编程规则,它肯定会结束。相反,尽管你可以让ActionListeners改变类的状态,任何类,这应该足够了。例如:

class FooClass {
    private String text;

    public void foo(JButton[] buttons) {
        for (JButton i : buttons) {
            i.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    text = e.getActionCommand(); 
                }
            });
        }
    }
}

如果您需要有关可行解决方案的更多详细信息,请告诉我们有关您的实际计划和具体问题的更多详细信息。

现在,如果您确实需要一个方法来返回按下的按钮的值,您需要通过通知机制和回调方法来执行此操作,但是解决方案的细节将再次取决于实际的详细信息问题和代码。

修改

您正试图模仿JOptionPane。您的解决方案是使用JOptionPane,向其添加JPanel,或使用模态JDialog创建自己的:

import java.awt.Color;
import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class JCustomFrame2 {

   public static String showMessageFrame(Window owner, String title,
         String message, String[] textOnButtons, ImageIcon icon) {
      final JDialog dialog = new JDialog(owner);
      StringBuilder sb = new StringBuilder();

      // make it application modal!
      dialog.setModalityType(ModalityType.APPLICATION_MODAL);
      JPanel panel = new JPanel();

      panel.setLayout(new GridBagLayout());
      panel.setBackground(Color.WHITE);

      GridBagConstraints c = new GridBagConstraints();
      c.anchor = GridBagConstraints.EAST;
      c.fill = GridBagConstraints.RELATIVE;
      c.gridx = 0;
      c.gridy = 0;
      c.insets = new Insets(5, 5, 5, 5);

      JLabel messageLabel = new JLabel(message);
      messageLabel.setFont(messageLabel.getFont().deriveFont(16.0f));

      panel.add(messageLabel, c);

      c.gridy = 1;
      c.gridx = 0;
      for (int i = 0; i < textOnButtons.length; i++) {
         JButton button = new JButton(textOnButtons[i]);
         button.addActionListener(new ButtonListener(sb));
         button.setFont(button.getFont().deriveFont(16.0f));
         panel.add(button, c);
         c.gridx++;
      }

      if (icon == null) {
         dialog.setIconImage(new BufferedImage(1, 1,
               BufferedImage.TYPE_INT_ARGB_PRE));
      } else {
         dialog.setIconImage(icon.getImage());
      }
      dialog.add(panel);
      dialog.setTitle(title);
      dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
      dialog.pack();
      dialog.setVisible(true);

      return sb.toString();
   }

   private static class ButtonListener implements ActionListener {
      private StringBuilder sb;

      public ButtonListener(StringBuilder sb) {
         this.sb = sb;
      }


      @Override
      public void actionPerformed(ActionEvent e) {
         sb.append(e.getActionCommand());
         Component component = (Component) e.getSource();
         Window win = SwingUtilities.getWindowAncestor(component);
         if (win != null) {
            win.dispose();
         }
      }
   }

   public static String showMessageFrame(String title,
         String message, String[] textOnButtons, ImageIcon icon) {
      return showMessageFrame(null, title, message, textOnButtons, icon);
   }


   public static void main(String[] args) {
      String result = JCustomFrame2.showMessageFrame("Test Frame",
            "Do you really want to do this?", new String[] { "Hell No",
                  "Sure, Why Not" }, null);

      System.out.println(result);
   }
}

答案 1 :(得分:0)

为什么这么复杂?无论foo应该做什么,简单地从ActionListener内部调用另一个方法并以按钮的名称作为参数将会容易得多。或者,如果你真的想要达到这样的目的,那就让线程等待用户按下按钮。

public void doSomething(){
    JButton[] someButtons = ...;//whereever you create the buttons

    System.out.println(foo(someButtons));
}

public static String foo(JButton[] buttons){
    final String someString = "";

    final Object lock = new Object();

    for(JButton b : buttons){
        b.addActionListener(e -> {
             someString.concat(b.getName());

             synchronized(lock){
                 lock.notifyAll();
             }
        });
    }

    synchronized(lock){
        try{
            lock.wait();
        }catch(InterruptedException e){}
    }

    return someString;
}