Alia Su Alia Su - 18 days ago 6
Java Question

How to already display text in textarea when running file - JAVA

I am trying to make it that a user doesn't have to copy and paste a text in the textarea when running the program so instead when running, the textarea already contains the text.My program parses normal text into JSON then into Java,I am trying to make the normal text display in the textarea when starting the program. My code :

TextArea Code

private void InputKeyPressed(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
String text = "Call me Ishmael. Some years ago-never mind how long precisely-having "
+ "little or no money in my purse, and nothing particular to interest me on shore, "
+ "I thought I would sail about a little and see the watery part of the world. "
+ "It is a way I have of driving off the spleen and regulating the circulation. "
+ "Whenever I find myself growing grim about the mouth; whenever it is a damp, "
+ "drizzly November in my soul; whenever I find myself involuntarily pausing before "
+ "coffin warehouses, and bringing up the rear of every funeral I meet; and especially "
+ "whenever my hypos get such an upper hand of me, that it requires a strong moral "
+ "principle to prevent me from deliberately stepping into the street, and methodically "
+ "knocking people's hats off-then, I account it high time to get to sea as soon as I can. "
+ "This is my substitute for pistol and ball. With a philosophical flourish Cato throws himself "
+ "upon his sword; I quietly take to the ship. There is nothing surprising in this. "
+ "If they but knew it, almost all men in their degree, some time or other, cherish "
+ "very nearly the same feelings towards the ocean with me. There now is your insular "
+ "city of the Manhattoes, belted round by wharves as Indian isles by coral reefs-commerce surrounds "
+ "it with her surf. Right and left, the streets take you waterward.";

Input.setText(text);
}


I was unsure in which Event to choose so I just went with KeyPressed. So how can I make the text already appear in the textarea when running the file? Thanks for your time:)

Answer

This comment:

it shows up as blank still when running.

Is the key information that you need to give us and suggests that your program is running long-running code on the Swing event thread, and that by doing this, you're preventing the event thread from doing its necessary duties, including drawing the GUI -- including text within the JTextArea, and interacting with the user.

If this is the problem then the solution is to do the long-running code within a background thread, but in doing so, taking care to update the GUI on the event thread only. A SwingWorker could help you do this. SwingWorker Tutorial