我试图让“生成”JButton每次按下时在文本区域中放置一个新单词。我试过循环,这导致我的GUI停止响应。
示例用户输入:点击“生成”按钮3次 文本区域中的示例输出:applepotatocucumber
有什么建议吗?
以下是代码:
public Generator(){
String[] words = {apple, pear, cucumber, lettuce, tomato, potato};
String random = (words[new Random().nextInt(words.length)]);
setBackground(Color.CYAN);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
SpringLayout sl_contentPane = new SpringLayout();
contentPane.setLayout(sl_contentPane);
JLabel lblNewLabel = new JLabel("Random Word Generator");
sl_contentPane.putConstraint(SpringLayout.NORTH, lblNewLabel, 10, SpringLayout.NORTH, contentPane);
sl_contentPane.putConstraint(SpringLayout.WEST, lblNewLabel, 27, SpringLayout.WEST, contentPane);
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 21));
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
contentPane.add(lblNewLabel);
JLabel lblInfo = new JLabel("Result will be printed in the white space.");
sl_contentPane.putConstraint(SpringLayout.NORTH, lblResultsWillBe, 73, SpringLayout.NORTH, contentPane);
sl_contentPane.putConstraint(SpringLayout.WEST, lblResultsWillBe, 124, SpringLayout.WEST, contentPane);
lblResultsWillBe.setHorizontalAlignment(SwingConstants.CENTER);
contentPane.add(lblInfo);
JTextArea textArea = new JTextArea();
textArea.setWrapStyleWord(true);
sl_contentPane.putConstraint(SpringLayout.NORTH, textArea, 150, SpringLayout.NORTH, contentPane);
sl_contentPane.putConstraint(SpringLayout.WEST, textArea, 141, SpringLayout.WEST, contentPane);
sl_contentPane.putConstraint(SpringLayout.SOUTH, textArea, 12, SpringLayout.SOUTH, contentPane);
sl_contentPane.putConstraint(SpringLayout.EAST, textArea, -124, SpringLayout.EAST, contentPane);
contentPane.add(textArea);
JButton btnGenerate = new JButton("Generate");
sl_contentPane.putConstraint(SpringLayout.NORTH, btnGenerate, 41, SpringLayout.NORTH, contentPane);
sl_contentPane.putConstraint(SpringLayout.WEST, btnGenerate, 163, SpringLayout.WEST, contentPane);
contentPane.add(btnGenerate);
btnGenerate.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
textArea.setText(random);
Object source = e.getSource();
if (source == btnGenerate){
textArea.setText(random);
}
}});
JLabel txtResults = new JLabel();
sl_contentPane.putConstraint(SpringLayout.SOUTH, txtResults, -100,
SpringLayout.SOUTH, contentPane);
sl_contentPane.putConstraint(SpringLayout.EAST, txtResults, -143, SpringLayout.EAST, contentPane);
contentPane.add(txtResults);
}
答案 0 :(得分:1)
文本区域中的示例输出:applepotatocucumber
请勿使用setText()
方法。这取代了现有的文本。
改为使用:
textArea.append(random);
因此,每次单击该按钮时,新文本都将附加到文本区域。