GUI初学者。
我的问题不是创建GUI界面,而是让2个按钮在界面内的JTextArea中打印字符串。
第一个“学习”按钮从数组中获取一个随机元素并打印出来。
第二个按钮“clear”只是在按下时打印一个字符串
我有两个按钮的动作监听器,但仍然无法得到它。
感谢您的时间。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
public class GUI extends JFrame {
String [] sentences = {"Random sentence 1", "random sentence 2", "random sentence 3", "random sentence 4", random sentence 5", "random sentence 6"};
private Container contents;
JButton learned = new JButton("Learned");
JButton clear = new JButton("Clear");
JTextArea clearDisplay;
public GUI()
{
super ("GUI"); //title bar text
contents = getContentPane ();
contents.setLayout(new FlowLayout()); //make buttons appear
//set the layout manager
//instantiate buttons
learned = new JButton("I Learned");
clear = new JButton("Clear");
//add components to window
contents.add(learned);
contents.add(clear);
//instantiate event handler
ButtonHandler bh = new ButtonHandler ();
//add event handler as listener for both buttons
learned.addActionListener (bh);
clear.addActionListener(bh);
setSize (400, 200); //size of window
setVisible (true); //see the window
}
public class ButtonHandler implements ActionListener
{
//implement ActionPerformed method
public void actionPerformed(ActionEvent e)
{
Container contentPane = getContentPane();
if (e.getSource() == learned)
{
String random = (sentances[new Random().nextInt(sentances.length)]); //random from array
JTextArea learned = new JTextArea(random);
}
else if (e.getSource() == clear)
{
JTextArea clearDisplay = new JTextArea("This is where it will display what I learned. \\nMessage Displayed Here.");
}
}
}
public static void main(String[] args)
{
GUI basicGui = new GUI ();
basicGui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //program exits on close
}
}
答案 0 :(得分:2)
你的问题在这里:
else if (e.getSource() == clear)
{
JTextArea clearDisplay = new JTextArea("This is where it will display what I learned. \\nMessage Displayed Here.");
}
您正在创建一个永远不会添加到GUI的新JTextArea。你应该这样写:
else if (e.getSource() == clear)
{
clearDisplay = new JTextArea("This is where it will display what I learned. \\nMessage Displayed Here.");
}
并将其添加到GUI。
您还应该考虑另一种方法:首先创建JTextField,将其添加到GUI,然后仅在上面的代码中更改其文本。
另外,你有一些拼写错误:
String random = (sentances[new Random().nextInt(sentances.length)]);
答案 1 :(得分:1)
不要在动作侦听器中创建新的JTextAreas。而是在GUI的构造函数和侦听器中创建一个单独的JTextArea,只需将相应的文本写入JTextArea,或者通过调用.setText(...)
(如果要完全更改文本)或.append(...)
(如果要更改)在现有文本中添加其他文字。