我对此GUI代码有疑问。如何出现在JLabel随机词上?
基本上,该程序的目的是创建一个GUI按钮,单击该按钮时从数组中选择一个随机单词并将其放入JLabel.
我遇到的麻烦是让单词出现在 上JLabel,我不太确定应该怎么做。
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GuiQuiz {
public static void main(String[] args) {
JFrame frame = new JFrame("Button Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setBackground(Color.BLUE);
mainPanel.setPreferredSize(new Dimension(500, 500));
JPanel subPanel1 = new JPanel();
subPanel1.setBackground(new Color(134, 179, 0));
subPanel1.setPreferredSize(new Dimension(150, 100));
subPanel1.add(new JLabel("Random word here"));
String[] names = { "Class", "Charger", "Pencil", "Dog", "Robot", "Ninja", "Teacher", "Video", "Book",
"Computer" };
JButton button = new JButton("Generates a random word");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = names[(int) (Math.random() * names.length)];
((JButton) e.getSource()).setText(name);
}
});
mainPanel.add(button);
mainPanel.add(subPanel1);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setVisible(true);
}
}
交互式爱情
相关分类