下面是一个示例代码,演示了如何在按下GUI按钮时从数组中随机选择一个单词,并将其放置在JLabel上。
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class RandomWordGUI extends JFrame implements ActionListener {
private JButton button;
private JLabel label;
private String[] words = {"apple", "banana", "cherry", "date", "elderberry"};
public RandomWordGUI() {
super("Random Word");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
button = new JButton("Generate Random Word");
button.addActionListener(this);
add(button);
label = new JLabel();
add(label);
pack();
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
Random random = new Random();
int index = random.nextInt(words.length);
String randomWord = words[index];
label.setText(randomWord);
}
}
public static void main(String[] args) {
new RandomWordGUI();
}
}
这个示例代码创建了一个包含一个按钮和一个标签的GUI窗口。当按钮被点击时,actionPerformed
方法将被调用,并从数组中随机选择一个单词。选中的单词将被设置为标签的文本。
下一篇:按下一个键后重复一行代码。