我目前正在尝试学习 Java 的新知识,并决定开始 GUI 编程。 我使用 ActionListener 和方法“actionPerformed”创建了一个 GUI。
我的问题是我是否可以从此方法(actionPerformed)返回任何内容以及它将落在哪里?因为当我在此 GUI 中执行特定操作时会调用该方法。
或者我怎样才能给这个actionPerformed方法一个其他参数?
提前致谢;)
最佳答案
正如您可能已经知道的,actionPerformed 方法被声明为返回 void
或 nothing,所以不,您不能从中返回任何内容,但您可以更改此方法范围内任何可变字段的状态,例如 JLabel 中显示的文本。
例如:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class ActionListenerTest extends JPanel {
private static final String[] DAYS = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
private int dayIndex = 0;
private JLabel label = new JLabel("", SwingConstants.CENTER);
private JButton button = new JButton("Press Me Please!");
public ActionListenerTest() {
label.setText(DAYS[dayIndex]);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dayIndex++; // advance the index
dayIndex %= DAYS.length; // if index >= the length of the array, make it 0
label.setText(DAYS[dayIndex]);
}
});
setLayout(new GridLayout(2, 1));
add(label);
add(button);
}
private static void createAndShowGui() {
ActionListenerTest mainPanel = new ActionListenerTest();
JFrame frame = new JFrame("ActionListenerTest");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
虽然 actionPerformed 不返回任何内容,但它会将 dayIndex 增加 1,或者如果索引与 String 数组的长度相同,则将其设置为 0。然后该方法使用字符串数组数据设置 JLabel 的文本。
关于java - ActionListener(actionPerformed) 返回一些东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33723933/