Java. How to wait? - java

I call a class that creates a jframe and waits from user to input some values.
The problem that I experience is that I need to wait these values before to continue.
So the code is something simple like this
Jframe frame= new jframe(); //here I want the program to show the frame and then wait till it will be disposed
// I want a pause here
System.out.println(frame.getvalue);
Till now the only I could do is to froze the frame before can even appear totally.
Any help?
Please keep it simple since I am new to Java.
THANK YOU!

I think you should use JDialog instead of JFrame. Please follow this example

What you're probably looking for is JOptionPane. This is a blocking routine that returns only after the user has entered some value, like so:
public class test
{
public static void main ( String args[] )
{
String input = JOptionPane.showInputDialog(null, "Thing: ",
"Enter Stuff", JOptionPane.OK_CANCEL_OPTION);
System.out.println ( "won't reach until got input");
System.out.println ( "My value: " + input );
}
}
The great thing about it is you can add Components to it, so you aren't limited to a single input field, but it is still blocking. The following would add two JTextField's to the frame:
public class test
{
public static void main ( String args[] )
{
JTextField input_box = new JTextField(7);
JTextField input_box2 = new JTextField(7);
JComponent[] inputs = new JComponent[] {
new JLabel("Thing 1:"),
input_box,
new JLabel("Thing 2:"),
input_box2 };
int rval = JOptionPane.showConfirmDialog(null, inputs,
"Enter Stuff", JOptionPane.OK_CANCEL_OPTION);
if ( rval == 0)
{
System.out.printf ("%s and %s!", input_box.getText(),
input_box2.getText());
}
}
}

Instead of using a JFrame, consider using a JDialog with modality set to true.
When it comes time to add an 'OK' button or something like that, check out JRootPane.setDefaultButton()

well as you know swing components are not thread safe though you can use SwingWorker to make the waiting in background,
It uses the thread way but it creates a new thread for the waiting ,long term operations in general,
instead of pausing the event dispatch thread so the user can interact with the rest of the application or the rest of the application can continue to work while the waiting goes on.
ofcourse you have to define a way for it to stop the waiting.
check out its documentation here http://docs.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html

This will cause the current thread to wait 5 seconds:
try {
Thread.currentThread().wait(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}

Related

How to return variable from actionPerformed?

I'm not looking for direct answers. Just a general direction where I'm supposed to search or little hints, as this is an assignment for a class.
I am supposed to create a game, and in order for the user to start the game, they must enter their name through a JOPtionPane, at the moment, I have coded this:
JButton nameBtn = new JButton("NAME");
nameBtn.setBounds(25, 10, 250, 30);
nameBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name;
do{
name = JOptionPane.showInputDialog(frame, "ENTER YOUR NAME", "", JOptionPane.QUESTION_MESSAGE);
if(name != null)
;
else
JOptionPane.showMessageDialog(frame, "No name entered");
}while(name == null);
}
});
What I want to do is then display that user entered name unto another panel. How would one go about doing that?
If I am understanding the question correctly, then you want to use the name result from the input dialog and display it in an existing label in the outer class. You can simply create a method in the outer class that takes the name as a String argument and that adds it to any of the components in that outer class. You can call this method from within the ActionListener. Without including the element where the name should end up in your question, I cannot go more specific than this.
Nvm, I found my own answer
// buttons
JButton nameBtn = new JButton("NAME");
nameBtn.setBounds(25, 10, 250, 30);
nameBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name;
do{
name = JOptionPane.showInputDialog(frame, "ENTER YOUR NAME", "", JOptionPane.QUESTION_MESSAGE);
if(name != null)
;
else
JOptionPane.showMessageDialog(frame, "No name entered");
}while(name == null);
//take user input (name) and assign it into a JLabel, which will be added
to my desired Panel
JLabel userName = new JLabel(name);
botPan.add(userName);
userName.setBounds(400, 20, 55, 30);
}
});
Execution continues uninterrupted immediate on from the call to addActionListener. So the code following the listener registration is executed at the wrong time to receive such a returned value.
The action to be performed should be initiated within the actionPerformed method or methods that it calls. And that's about it. In an anonymous inner class, as used in the question, access is available to the enclosing scope.
As a note of style, listener implementations should usually be short, just removing the necessary information from the event (often only that it happened at all) and calling an uncluttered method that does the useful work.
For tasks that may block the AWT Event Dispatch Thread (EDT), work can be done on another thread. Any resultant manipulation to AWT/Swing object need then be performed with a java.awt.EventQueue.invokeLater call to run on the EDT.
Some methods dealing with modal dialogues, such as presumably showInputDialog, use a hack whereby EDT events are processed within the method call. You can see this in stack traces. Modal dialogues are generally considered poor UI.

Making a program wait until a button is clicked

I have a problem that probably has a simple fix but I can't seem to get it to work.
I need my program to pause or wait until the user selects either the skip button, or the positive/negative feedback button, before moving on.
I assume this is going to require basic threading, but I'm not sure how to implement it. Any help will be appreacited.
The gui is displayed in a separate class(GUI) and the rest is another class.
The code is sort of messy as it was coded for a Hackfest in 12 hours.
EDIT: Solved it on my own by removing button listeneers and making the variables static.
public void onStatus(Status status) {
//this is a listener from the Twitter4J class. Every time new Tweet comes in it updates.
for (int i = 0; i <= posWords.length; i++) {
if (status.getText().toLowerCase().contains(gui.sCrit.getText())
&& (status.getText().toLowerCase().contains(posWords[i].toLowerCase()))) {
//If the tweet matches this criteria do the following:
String tweet;
Status tempStoreP;
System.out.println("Flagged positive because of " +posWords[i].toLowerCase()+" " + i);
tempStoreP = status;
tweet = tempStoreP.getUser().getName() + ":" + tempStoreP.getText() + " | Flagged as positive \n\r";
gui.cTweet.setText(tweet);
//Write to log
try {
wPLog.append("~" + tweet);
} catch (IOException e) {
}
//Add action listeneer to gTweet.
//here is my problem. I want it to wait until a user has clicked one of these buttons before moving on and getting the next Tweet. It has to pause the thread until a button is clicked then it can only move on to getting another Tweet.
//the problem is that the button listener uses local variables to work.
gui.gTweet.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (gui.pTweet.getText().equalsIgnoreCase("")) {
gui.pTweet.setText("Please type a response");
} else if (gui.pTweet.getText().equalsIgnoreCase("Please type a response")) {
gui.pTweet.setText("Please type a response");
} else {
try {
Status sendPTweet = twitter
.updateStatus("#" + tempStoreP.getUser().getScreenName() + " "
+ gui.pTweet.getText());
} catch (TwitterException e1) {
}
}
gui.gTweet.removeActionListener(this);
}
});
//add Aaction listert to sTweet
gui.sTweet.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
wPLog.append("Skipped \n\r");
} catch (IOException e1) {
}
gui.sTweet.removeActionListener(this);
}
});
}
Thank you for any help. On a side note, if anyone can tell me why when the button is clicked, it loops and spams people with the same message, it will be helpful. Thank you.
I thought about the multithreading thing and i think it isn't easy enough.
If i were you i would disable all controls except the button that is to click.
Example:
JButton button = new JButton( "Test );
button.setEnabled( false );
The user won't be able to click the button until you use button.setEnabled( true );, if you just disable all controls but the button that should be fine.
In my understand of your problem you can use Multithreading like this:
try{
while(!isSkipClicked){
//your multithreading code
}
//code to move...
}
or
you can use dispose method if you have 2 JFrame.
or
you can use multiple JPanel like while skip button clicked hide pnl1 and show pnl2 using method
pnl1.setvisible(false);
pbl2.setVisible(true);
I assume this is going to require basic threading,
Not true at all.
You say you want your program to "wait." That word doesn't actually mean much to a Swing application. A Swing application is event driven. That is to say, your program mostly consists of event handlers that are called by Swing's top-level loop (a.k.a., the Event Dispatch Thread or EDT) in response to various things happening such as mouse clicks, keyboard events, timers, ...
In an event driven program, "Wait until X" mostly means to disable something, and then re-enable it in the X handler.
Of course, Swing programs sometimes create other threads to handle input from sources that the GUI framework does not know about and, to perform "background" calculations. In that case, "Wait until X" might mean to signal some thread to pause, and then signal it to continue its work in the X handler.

Changing text size of the text someone using my program sees?

Glad to be on this very helpful website. I have a problem with my Java program that will probably either be an easy fix, or impossible to fix.
You know how when you run a program that's open in NetBeans, it shows the output within the NetBeans application? I am trying to create a program that allows anybody who puts it on their computer to execute it, even if they have not installed an IDE like NetBeans or Eclipse. And when somebody executes my program, I want it to show the same thing as when I run it in NetBeans, with the same output and everything. The program doesn't use a GUI or anything like that. I managed to create an executable .jar file with the "Clean and build project" option, and I made a .bat file that successfully executes the program. This should achieve my goal of allowing anyone to run it. When I start up the .bat file, it works, and shows a white-text-black-background screen that runs the program exactly as it ran while in NetBeans.
The problem is that when I run the program (with the .bat file), the text is too small... I've tried looking everywhere for a solution to this, but I could only find discussion about how to make things work with GUIs, or other more complicated things than what my program needs. I am willing to work with GUI stuff if it is necessary, but I don't think it will help, due to what a GUI is. From my understanding, a GUI is not one big thing, but is a user interface composed of smaller parts (such as pop-up input prompts and scroll bars) that are each made by the programmer. I don't need any fancy scroll bars etc., I just need my program to execute like it does when ran in NetBeans (pretty sure this is called the console), and I need to change the text size of the program text when it executes.
I greatly appreciate any help, even if you aren't sure if it will work or not. If the answer requires a lengthy explanation and you don't feel like explaining, that's okay; just tell me what I'd have to learn to figure this out and I can research it if necessary.
I just created one. Try using this one and tell us if it helped or not.
EDIT Added a JTextField to read data. It is more advanced code than the previous one, since it uses concurrency. I tried to make it simple, these are the functions you can use:
MyConsole (): Constructor. Create and show the console
print (String s): Print the s String
println (String s) Print the s String and add a new line
read (): Makes you wait untill the user types and presses Enter
closeConsole (): Closes the console
Here is the code:
public class MyConsole implements ActionListener {
private JFrame frame;
private JTextArea myText;
private JTextField userText;
private String readText;
private Object sync;
/*
* Main and only constructor
*/
public MyConsole() {
// Synchronization object
sync = new Object();
// Create a window to display the console
frame = new JFrame("My Console");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
frame.setLocationRelativeTo(null);
frame.setResizable(true);
frame.setContentPane(createUI());
frame.setVisible(true);
}
/*
* Creates user interface
*/
private Container createUI() {
// Create a Panel to add all objects
JPanel panel = new JPanel (new BorderLayout());
// Create and set the console
myText = new JTextArea();
myText.setEditable(false);
myText.setAutoscrolls(true);
myText.setBackground(Color.LIGHT_GRAY);
// This will auto scroll the right bar when text is added
DefaultCaret caret = (DefaultCaret) myText.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
// Create the input for the user
userText = new JTextField();
userText.addActionListener(this);
panel.add(new JScrollPane(myText), BorderLayout.CENTER);
panel.add(userText, BorderLayout.SOUTH);
return panel;
}
/*
* Waits until a value is typed in the console and returns it
*/
public String read(){
print("==>");
synchronized (sync) {
try {
sync.wait();
} catch (InterruptedException e) {
return readText = "";
}
}
return readText;
}
/*
* Prints s
*/
public synchronized void print(String s){
// Add the "s" string to the console and
myText.append(s);
}
/*
* Prints s and a new line
*/
public synchronized void println(String s){
this.print(s + "\r\n");
}
/*
* Close the console
*/
public void closeConsole(){
frame.dispose();
}
#Override
public void actionPerformed(ActionEvent e) {
// Check if the input is empty
if ( !userText.getText().equals("") ){
readText = userText.getText();
println(" " + readText);
userText.setText("");
synchronized (sync) {
sync.notify();
}
}
}
}
Here is how to use it (an example). It just asks your age and writes something depending on your input:
public static void main(String[] args) {
MyConsole console = new MyConsole();
console.println("Hello! (Type \"0\" to exit)");
int age = 1;
do{
console.println("How old are you ?");
String read = console.read();
try {
age = Integer.valueOf(read);
if ( age >= 18){
console.println("Wow! " + age + " ? You are an adult already!");
}else if ( age > 0 ){
console.println("Oh! " + age + " ? You are such a young boy!");
}else if (age == 0){
console.println("Bye bye!");
}else{
console.println("You can't be " + age + " years old!");
}
}catch (Exception e) {
console.println("Did you write any number there ?");
}
} while ( age != 0 );
console.closeConsole();
}
And here is a image:

Read JTextArea For Jazzy Spell Checker API

Question: Trying to get the same effect as the code below only with JTextArea so I want the JTextArea to be read and spelling suggestions to be recommended every time the user types a new misspelt word.
Below is the working example with 'System.in' which works well.
(Vars userField = JTextArea & dic.txt is a list of the english language for the system to use for suggestions)
CODE (1)
public SpellCheckExample() {
try {
SpellDictionary dictionary = new SpellDictionaryHashMap(new File(dic.txt));
spellCheck = new SpellChecker(dictionary);
spellCheck.addSpellCheckListener(this);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.print("Enter text to spell check: ");
String line = in.readLine();
if (line.length() <= 0)
break;
spellCheck.checkSpelling(new StringWordTokenizer(line));
}
} catch (Exception e) {
e.printStackTrace();
}
}
What I have Been trying:
CODE (2)
public void spellChecker() throws IOException{
String userName = System.getProperty("user.home");
SpellDictionary dictionary = new SpellDictionaryHashMap(new File(userName+"/NetBeansProjects/"+"/project/src/dic.txt"));
SpellChecker spellCheck = new SpellChecker(dictionary);
spellCheck.addSpellCheckListener(this);
try{
StringReader sr = new StringReader(userField.getText());
BufferedReader br = new BufferedReader(sr);
while(true){
String line = br.readLine();
if(line.length()<=0)
break;
spellCheck.checkSpelling(new StringWordTokenizer(line));
}
}catch(IOException e){
e.printStackTrace();
}
}
March 3rd 2016 (Update)
public void spellChecker() throws IOException{
// getting context from my dic.txt file for the suggestions etc.
SpellDictionary dictionary = new SpellDictionaryHashMap(new File("/Users/myname/NetBeansProjects/LifeSaver/src/dic.txt"));
SpellChecker spellCheck = new SpellChecker(dictionary);
// jt = JTextField already defined in constructors and attemtpting to pass this into system and
InputStream is = new ByteArrayInputStream(jt.getText().getBytes(Charset.forName("UTF-8")));
//spellCheck.checkSpelling(new StringWordTokenizer(line)); ""ORIGINAL"""
// reccomending cast to wordfinder
spellCheck.checkSpelling(new StringWordTokenizer(is);
}
You don't want to try to drop console UI code into an event-driven GUI, as it will never work like that. Instead you need to use GUI events to trigger your actions, not readln's.
The first thing you must decide on is which event you wish to use to trigger your spell check. For my money, I'd get the user's input in a JTextField, not a JTextArea since with the former, we can easily trap <enter> key presses by adding an ActionListener on the JTextField. You can always use both, and then once the text is spell checked, move it to the JTextArea, but this is exactly what I'd recommend:
use a JTextField,
add an ActionListener to the JTextField to be notified whenever the field has focus and enter is pressed,
within this listener, extract the text from the JTextField, by calling getText() on the field
Then run your spell check code on extracted text,
and output the result into a nearby JTextArea.
Take a look at Concurrency in Swing for reasons why your current approach won't work, then have a look at Listening for Changes on a Document and Implementing a Document Filter for some possible solutions
As someone is bound to mention it, DON'T use a KeyListener, it's not an appropriate solution for the problem
Put simpler, Swing is a single threaded, event driven framework. So anything you do which blocks the Event Dispatching Thread, will prevent it from processing new events, including paint events, making your UI unresponsive
As an event driven environment, you need to register interested in been notified when some event occurs (this is an example of Observer Pattern) and then take appropriate actions based on those events.
Remember though, you can not make changes to a Document via a DocumentListener, so be careful there

Java drawing with delay

I'm trying to visualize various graph-algorithms. I want to make it so, that after every 2 seconds the graph get updated and gets repainted. I have tried using the Thread.sleep() method but it just freezes the GUI and then after a while is done with the complete algorithm.
(I am fairly new to Java so don't be to harsh with the code)
The Code in question:
else if(ae.getSource() == fordFulkersonButton){
dinicButton.setEnabled(false);
edmondsKarpButton.setEnabled(false);
gtButton.setEnabled(false);
if(checkbox.isEnabled()){
fordFulkersonButton.setEnabled(false);
while(!fordFulkerson.getIsDone()){
flowNetwork = fordFulkerson.algoFF(flowNetwork);
popupText.setVisible(true);
Integer i = new Integer(flowNetwork.getCurrentFlow());
String s = i.toString();
popupText.setText("Aktueller Fluß: "+s);
graphDrawer.setFlowNetwork(flowNetwork);
this.showFrame();
try {
Thread.sleep(2 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Integer in = new Integer(flowNetwork.getCurrentFlow());
String st = in.toString();
popupText.setText("Algorithmus is beendet mit Fluss: "+st);
}
flowNetwork = fordFulkerson.algoFF(flowNetwork);
popupText.setVisible(true);
Integer i = new Integer(flowNetwork.getCurrentFlow());
String s = i.toString();
if(fordFulkerson.getIsDone()){
popupText.setText("Algorithmuss beednet mit maximalen Fluß: "+s);
}else{
popupText.setText("Aktueller Fluß: "+s);
}
graphDrawer.setFlowNetwork(flowNetwork);
this.showFrame();
}
Doing huge amounts of work in a UI thread freezes the UI. If you want to do animations or complex work, use a worker thread or a Swing timer.
You must not call Thread.sleep() in Swing UI code. Instead, you need to think like an animator: Show one frame of the animation at a time. Some external source will call your code to show the next frame. The external source is the Swing timer. Your code draws the next frame and returns. That way, you never block the UI thread for long.
Google for "swing animation". Interesting results are:
http://www.java2s.com/Tutorial/Java/0240__Swing/Timerbasedanimation.htm
http://zetcode.com/tutorials/javagamestutorial/animation/

Categories

Resources