【发布时间】:2015-06-29 21:37:36
【问题描述】:
我有一个这样的方法,给定一个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);
}
}
【问题讨论】:
-
您以线性/程序化的方式思考,这不是 UI 的工作方式,UI 是事件驱动的,这意味着某事发生(在某个时间点)并且您对其做出响应。将值退回给 foo 方法是没有意义的,因为代码在通知 ActionListener 之前很久就已经完成执行。最好让侦听器自己执行所需的操作
标签: java swing return listener