由于某种原因,我无法让 JTextArea“answersTA”显示任何内容。调用append() 和setText() 不会更新框中的信息。
这是我的程序的目标:接收一个字符串并将其存储到“word”,接收一个字符串并从中解析一个 int 并将其存储到“num”,将它们输入到solutions()方法中,然后显示solutions()返回的数组。我一生都无法展示任何东西。
public class CWGui extends JFrame
{
private static final int WIDTH = 800;
private static final int HEIGHT = 400;
private JLabel pattern, number, answers;
private JTextField patternTF, numberTF;
private JButton execute, exitB;
private JTextArea answersTA;
//Button handlers:
private ExecuteButtonHandler eHandler;
private ExitButtonHandler ebHandler;
public CWGui()
{
pattern = new JLabel("Enter the pattern: ", SwingConstants.RIGHT);
number = new JLabel("Enter the number of solutions: ", SwingConstants.RIGHT);
answers = new JLabel("Solutions: ", SwingConstants.LEFT);
patternTF = new JTextField(10);
numberTF = new JTextField(10);
answersTA = new JTextArea();
//SPecify handlers for each button and add (register) ActionListeners to each button.
execute = new JButton("Execute");
eHandler = new ExecuteButtonHandler();
execute.addActionListener(ebHandler);
exitB = new JButton("Exit");
ebHandler = new ExitButtonHandler();
exitB.addActionListener(ebHandler);
setTitle("Crossword Solution Generator");
Container pane = getContentPane();
pane.setLayout(new GridLayout(4, 2));
//Add things to the pane in the order you want them to appear (left to right, top to bottom)
pane.add(pattern);
pane.add(patternTF);
pane.add(number);
pane.add(numberTF);
pane.add(execute);
pane.add(exitB);
pane.add(answers);
pane.add(answersTA);
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private class ExecuteButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
try{
String word = patternTF.getText();
int num = Integer.parseInt(numberTF.getText());
FileParser fp = new FileParser("TWL06.txt");
List<String> dict = fp.getAllWords();
CWSolution c = new CWSolution(dict);
List<String> result = c.solutions(word,num);
answersTA.setText(result.toString());
}
catch(Exception t){}
}
}
public class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
public static void main(String[] args)
{
CWGui generator = new CWGui();
}
}
最佳答案
确保对事件调度线程调用的 GUI 进行任何更新。该线程将更新 gui,因此不会卡住它,也正因为如此,请确保任何可能需要一段时间的进程都在 SwingWorker 线程上运行,该线程与 EDT 是分开的。 SwingWorker 线程可以在后台运行,同时还可以在此过程中为您提供更新。您可以在官方文档中获得对这些内容的详细描述。我最近才学会它,它很有帮助。
关于java - JTextArea 不显示我告诉它的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20445472/