Stop the thread and make it run on button click; - java

Good day every one, i have such situation :
SomeDocument doc = DocumentsContainner.getDocument(doc);
try {
DocumentUtitlites.parseDocument(doc);
} catch (DocumentParseException e) {
ManualParsingFrame frame = new ManualParsingFrame(doc);
frame.show();
}
NextStageOfUsingDoc(doc);
ManualParsingFrame is frame where user can see doc text and parsing in manually by selecting text .It's appear as u can see only when parseDocument(SomeDocument doc) throw exception. When user ends manually parsing text he click ok button wich is on frame.
And start NextStageOfUsingDoc - some other staff that can be processed only if doc was parse by parseDocument or by user ManualParsingFrame. The question is How to make invoke NextStageOfUsingDoc when user click ok button. Now if i have exception i see frame, but process is continue execution and in result i have visible frame and NextStageOfUsingDoc invoked with non parsed doc object. Thank u for your time.

Don't use a JFrame for this. Show your manual parsing info in a modal JDialog. This will stop program flow in the calling program until the modal dialog has been dealt with.

Related

ActionListener Loops back on itself

Well, I actually feel stupid for even asking this question but: Is it possible for an ActionListener to loop back on it self? The situation is as follows (kind shorthandish because it is a lot of in itself sound code that does nothing to the problem)
JMenuItem Menu=new JMenuItem();
Menu.addActionListener(e -> {
JDialog Dialog=new JDialog();
JTextField Name= new JTextField("",30);
JFormattedTextField ID =new JFormattedTextField(NumberFormat.getIntegerInstance());
ID.setColumns(8);
JButton Enter=new JButton();
\\GUI building stuff
Enter.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
Integer ImportID=((Number) ID.getValue()).intValue();
String ImportName= Name.getText();
System.out.println("Eingaben\n"+ImportID);
System.out.println(ImportName);
//loads of different stuff
Dialog.dispose();
System.out.println(ImportID);
System.out.println(ImportName);
//ID.setValue(null);
//Name.setText(null);
//ImportID=null;
//ImportID=null;
System.out.println("Fertig!");
}
});
});
Now this menu leads to a dialog intended as an import dialog. What happens now is that the first time any user input data is used this data is propagated correctly. But if the user attempts make a input a second time the first and the second values are handed through - even with the disposing of the Dialog the data of the first go through shouldn't even be accessible, right?
I tried replacing the inner ActionListener with an e.getSource, which didn't work. Setting the variables or the Field to null doesn't help either.
I am aware that placing an ActionListener within an ActionListener is propably bad form.
Edit: I should explain how this works: The MenuItem (which sits inside the menubar of a proper GUI) is selected and calls forth a Dialog where the user enters two pieces of data and selects some files. Selected files are copied into a new directory and the entered data is processed into two text files. After that happened the Dialog is set to invisible and some different and to the data unrelated processing occurs. This processign being finished things are supposed to be wrapped up so that the dialog can be called upon again. If however I close the application this error does not occur.

Unable to change button text to icon immediate after click button in java swing

I have written following code.I have not shown full source but psudo code.
class UI extends JFrame
{
//created UI with one Button
onButtonclick()
{
//did some operation before set icon to button
//say opened fileopen dialog and get file
button.setText("");
ImageIcon progressbar = new
ImageIcon(DatasetExporterUI.class.getResource("/progreassbar.gif"));
buttonExport.setIcon(progressbar);
// did some database operations
//again removed icon from button
button.setIcon(null);
button.setText("click");
}
}
When I click on button It opens file open dialog and and button text get set to empty.
But It doesn't set Icon to button.When all Database operation are done which are performed after Icon set to button that time Icon is appeared on button.
Why this behavior is?
How to set Icon to button and do some Database operations and again remove it?
Thank you. :)
The GUI system can only do one thing at a time, like most code (except for code that uses threads). Calling your listener is a thing. The GUI system cannot do anything else while your listener is running.
Your database operation needs to run on another thread (which you can create) and then update the GUI when it's done. Something like this:
void onButtonPressed() {
// The code to open the file dialog goes here
button.setText("");
ImageIcon progressbar = new
ImageIcon(DatasetExporterUI.class.getResource("/progreassbar.gif"));
buttonExport.setIcon(progressbar);
new Thread() {
#Override
public void run() {
// do some database operations here
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
//again remove icon from button
button.setIcon(null);
button.setText("click");
}
});
}
}.start();
}
Code in different threads runs at the same time. This is convenient but dangerous. Be extremely careful when accessing data from the new thread - if one thread changes a field and the other thread reads it, the results might not be what you expect. The simplest thing to do is to make sure the main thread doesn't change any variables used by the new thread while it's running.
When your database operations are finished, you can't set the button back to normal by just calling setText. Only the main thread is allowed to affect the GUI - what if the main thread was drawing the button on the screen at the same time the database operation thread was changing the text? The button might be drawn incorrectly. So you need to call EventQueue.invokeLater which tells the GUI system to run your code in the near future when it's not busy. The code inside new Runnable() {} is like the code in the button listener - no other GUI-related code will run while it does.
This should work:
Image progressbar= ImageIO.read(DatasetExporterUI.class.getResource("/progreassbar.gif"));
buttonExport.setIcon(new ImageIcon(progressbar));

Display alert and then jump to another form in j2me

I am working on J2ME application. I want to show alert in Form and display another Form from another class. I have tried the following method to show alert.
public void showMsg()
{
Alert success = new Alert("Data Not found.");
//success.setImage(img2);
success.addCommand(new Command("Ok", Command.OK, 0));
success.addCommand(new Command("Cancel", Command.CANCEL, 0));
success.setCommandListener(this);
success.setTimeout(Alert.FOREVER);
Display.getDisplay(parent).setCurrent(success, chapterForm);
}
After showing the alert I am jumping to another form as:
Display.getDisplay(parent).setCurrent(welcomeForm);
When I run this it don't show the alert but jump to the welComeForm. So, how can I show alert and then jump to another form.
The Alert won't advance automatically to chapterForm because you have replaced the default listener on the Alert with this. Use the commandAction() event in the CommandListener interface to get the OK or Cancel from the Alert. Then you can use Display.setCurrent(Displayable d) to show the Form you want to display.
Display.getDisplay(parent).setCurrent(welcomeForm) is most likely the reason why it don't show the alert but jump to the welComeForm. To be precise it (device) may show alert for a moment, but as soon as you invoke that setCurrent(welcomeForm), it gets momentarily overwritten by welcomeForm.
If you want welcomeForm to be dissplayed by command from alert, just
wipe out the code setCurrent(welcomeForm) from where it is now
insert that wiped-out code into this.commandAction method (this is command listener you use in your code exerpt)
A nifty solution is to start a new thread after setting the current display to the Alert, and in this new thread you can do a Thread.sleep(2000); in order to wait, and after that you display the new form.

JOptionPane.showMessageDialog Query?

This is the Scenario.
I have Code which intiates a Alram when an error is encountered.
AudioAlarm t = new AudioAlarm(song);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Awake");
t.start();
setRunnung(true);
JOptionPane.showMessageDialog(null, "Alarm ...", "Alarm", JOptionPane.OK_OPTION);
AudioAlarm.setLoop(false);
System.out.println("Alarm Acknowledged ...");
I would like to re-design this logic in this manner,
If the Alarm is unacknowledged by the user over a period of time say 2 min, it turn off and message msg dialog should disappear.
How can I Obtain this?
I am able to Stop the Alram, but unable to dispose the dialog without the user pressing "OK"
To do what you want, you should:
Create a JOptionPane instance using one of its constructors
Call createDialog on this option pane to get a dialog containing this option pane
Use a javax.swing.Timer instance in order to fire an action event after 2 minutes
add an action listener to this timer which would close the dialog containing the option pane
show the dialog containing the option pane.
I do not know if what you are after can be done, but can't you instead replicate the JOptionPane as a JFrame and dispose of that one? You can find how to close a JFrame on this Previous SO Post:
If you want the GUI to behave as if
you clicked the "X" then you need to
dispatch a windowClosing Event to the
Window. The "ExitAction" from Closing
An Application allows you to add this
functionality to a menu item or any
component that uses Actions easily.

Bridge between the Java applet and the text input controls on the web page

I have been working with a Java applet which is an applet that helps to write using only a mouse. For my case, I am trying to incorporate this into my webiste project as follows:
When the user clicks on any input element (textbox/textarea) on the page, this JAVA applet loads on the webpage itself. In the screenshot of the JAVA applet seen below, the user points to an alphabet to and the corresponding text gets written in the text box of the applet.
Now what I am trying to do is to get this text from the TextBox of the applet to the input element on the webpage. I know that this needs an interaction between the Java and JavaScript, but not being a pro, I really do not have the catch. Here's the Java applet and the code I have written.
Java applet and jQuery code (298kB): http://bit.ly/jItN9m
Please could somebdoy help for extending this code.
Thanks a lot!
Update
I searched somewhere and found this -> To get the text inside of Java text box, a getter method in the Applet to retrieve the text:
public class MyApplet extends JApplet {
// ...
public String getTextBoxText() { return myTextBox.getText(); }
}
In the JQuery code, the following lines are to be added I think:
var textBoxText = $("#applet-id")[0].getTextBoxText();
//Now do something with the text
For the code of the applet, I saw a GNOME git page here. The getText call already exists -- look at the bottom of this file: http://git.gnome.org/browse/dasher/tree/java/dasher/applet/JDasherApplet.java
I'd need to call 'getCurrentEditBoxText' but when should this method 'getCurrentEditBoxText' be called?
In my case, I would probably have to do it when the user clicks in a new input control etc.
You can have full communication between your Applet and any javascript method on the page. Kyle has a good post demonstrating how the Javascript can call the applet and request the text value. However, I presume you want the HTML Textfield to update with each mouse click, meaning the applet needs to communicate with the page. I would modify your javascript to something like this:
var activeTextArea = null;
$('textarea, input').click(function() {
$(this).dasher();
activeTextArea = this;
});
function updateText(text) {
// Careful: I think textarea and input have different
// methods for setting the value. Check the
// jQuery documentation
$(activeTextArea).val(text);
}
Assuming you have the source for the applet, you can have it communicate with the above javascript function. Add this import:
import netscape.javascript.JSObject;
And then, in whatever onClick handler you have for the mouse clicks, add:
// After the Applet Text has been updated
JSObject win = null;
try {
win = (JSObject) JSObject.getWindow(Applet.this);
win.call("updateText", new Object[] { textBox.getText() });
} catch (Exception ex) {
// oops
}
That will update the text each time that chunk of code is called. If you do NOT have access to the applet source, things get trickier. You'd need to set some manner of javascript timeout that constantly reads the value from the applet, but this assumes the applet has such a method that returns the value of the textbox.
See Also: http://java.sun.com/products/plugin/1.3/docs/jsobject.html
Update Modifying the applet is your best shot since that is where any event would be triggered. For example, if you want the HTML TextField to change on every click, the click happens in the applet which would need to be modified to trigger the update, as described above. Without modifying the applet, I see two options. Option #1 uses a timer:
var timer;
var activeTextArea;
$('textarea, input').click(function() {
$(this).dasher();
activeTextArea = this;
updateText();
}
function updateText() {
// Same warnings about textarea vs. input
$(activeTextArea).val($('#appletId')[0].getCurrentEditBoxText());
timer = setTimeout("updateText()", 50);
}
function stopUpdating() {
clearTimeout(timer);
}
This is similar to the code above except clicking on a text area triggers the looping function updateText() which will set the value of the HTML text field to the value of the Applet text field every 50ms. This will potentially introduce a minor delay between click and update, but it'll be small. You can increase the timer frequency, but that will add a performance drain. I don't see where you've 'hidden' the applet, but that same function should call stopUpdating so that we are no longer trying to contact a hidden applet.
Option #2 (not coded)
I would be to try and capture the click in the Applet as it bubbles through the HTML Dom. Then, you could skip the timer and put a click() behavior on the Applet container to do the same update. I'm not sure if such events bubble, though, so not sure if this would work. Even if it did, I'm not sure how compatible it would be across browsers.
Option #3
Third option is to not update the HTML text field on every click. This would simply be a combination of Kyle's and my posts above to set the value of the text field whenever you 'finish' with the applet.
Here's a possible solution. To get the text inside of your Java text box, write a getter method in the Applet to retrieve the text:
public class MyApplet extends JApplet {
// ...
public String getTextBoxText() { return myTextBox.getText(); }
}
In your JQuery code, add the following lines:
var textBoxText = $("#applet-id")[0].getTextBoxText();
//Now do something with the text
I found most of what I posted above here. Hope this helps.
This page explains how to manipulate DOM from a Java applet. To find the input element, simply call the document.getElementById(id) function with id of an id attribute of the text input box.

Categories