performing a thread using jcomponets - java

am back again!. i have a probrem here. am making uneditable jcombobox. i have a list of items in it("crus","davy","shawn") and i want if someone clicks on crus, a thread of images with a Thread.sleep of 2 seconds will appear at a jlabel called picturelabel. when i try to put method run() inside method actionperformed, i get "illegal start of expression". i also get an error "not a statement" when i try to create an array of imageicon.
public class Myjcombobox extends JFrame implements ActionListener,Runnable {
JComboBox job;
String[] items={"crus","shawn","davy","others"};
JLabel picturelabel;
public Myjcombobox(){
super("oh mymy");
setSize(1000,1000);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BorderLayout border=new BorderLayout();
setLayout(border);
job=new JComboBox(items);
job.addActionListener(this);
}
public void actionPerformed(ActionEvent event){
JComboBox combo=(JComboBox)event.getSource();
String name=(String)combo.getSelectedItem();
if(name=="crus"){
public void run(){//i get an error illegal start of expression//
JImageIcon[] crusimages= new JImageIcon{"crus reading.jpg","crus playing.jpg","crus in class.jpg"}; //i get an error "not a statement","( or[ expected"//
}
}
}
public static void main(String[] args) {
Myjcombobox jcomb=new Myjcombobox();
}

if(name=="crus"){
{//i get an error illegal start of expression//
public void run()
//i get an error "not a statement","( or[ expected"//
JImageIcon[] crusimages= new JImageIcon{"crus reading.jpg","crus playing.jpg","crus in class.jpg"};
}
Every statement in the above code has a problem:
if(name=="crus"){
Don't use "==" to compare strings. Instead you should be using the equals(...) method:
if ("crus".equals(name));
Next, you can't just define a run() method in the middle of your code.
public void run()
The run() method belongs to a Thread, so you need to create a Thread and override the run() method. Something like:
Thread thread = new Thread()
{
#override
public void run()
{
System.out.println("I'm a Thread");
}
};
thread.start();
Finallay you can't create an Array of Image Icons in one step like this:
JImageIcon[] crusimages= new JImageIcon{"crus reading.jpg","crus playing.jpg","crus in class.jpg"};
You need to create an empty Array and then add the Icons one at a time:
ImageIcon[] crusImages = new new ImageIcon[3];
crusImage[0] = new ImageIcon( "crus reading.jpg" );

You can't just run() the thread, if you want to start it for the first time, you must use the method start(), witch starts a thread and runs the run() method. If you use just the run(), you won't be creating a thread, for it will run on the current thread.
Java Concurrency tutorial from Oracle: http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html.
Java Swing Components from Oracle: http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html.
I hop I could help.
Saclyr.

Related

JFrame ActionPerformed on a button takes full time until it finishes the code

It's my first time making GUI on java, and I have a small issue that is pretty annoying.
My code looks something like this.
private void RunButtonActionPerformed(java.awt.event.ActionEvent evt){
richText.append("Starting...");
try{ something happens here }
richText.append("Done...");
}
The problem is that when I click run button, it waits until it finishes the task and print "Starting..." and "Done..." at the same time. How do I make it print "Starting" first before and print "Done" after?
This code is executed in EDT, so any UI changes (richText.append in your case) will be repainted after it. You should execute your heavy task in new thread.
private void RunButtonActionPerformed(java.awt.event.ActionEvent evt){
richText.append("Starting...");
new Thread() {
public void run() {
try{ something happens here }
SwingUtilities.invokeLater(new Runnable() {
richText.append("Done...");
});
}
}.start();
}
Or use SwingWorker to get extra functionality such as reporting progress of task completion
I followed the tutorial for SwingWorker as suggested on the comment, and it worked! It looks something like this.
`private class Worker extends SwingWorker<Void, Void>{
protected Void doInBackground() throws Exception{
try{ things happen here }
return null;
}
#Override
protected void done(){
try{ get (); } catch (){}
}
}
And to call this, RunButtonActionPerformed just needs new Worker().execute().

Java Swing GUI updating/changing from method - freezing in loop

basically, I have this code which was initially working with console i/o now I have to connect it to UI. It may be completely wrong, I've tried multiple things although it still ends up with freezing the GUI.
I've tried to redirect console I/O to GUI scrollpane, but the GUI freezes anyway. Probably it has to do something with threads, but I have limited knowledge on it so I need the deeper explanation how to implement it in this current situation.
This is the button on GUI class containing the method that needs to change this GUI.
public class GUI {
...
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
controller.startTest(index, idUser);
}
});
}
This is the method startTest from another class which contains instance of Question class.
public int startTest() {
for (int i = 0; i < this.numberofQuestions; i++) {
Question qt = this.q[i];
qt.askQuestion(); <--- This needs to change Label in GUI
if(!qt.userAnswer()) <--- This needs to get string from TextField
decreaseScore(1);
}
return actScore();
}
askQuestion method:
public void askQuestion() {
System.out.println(getQuestion());
/* I've tried to change staticaly declared frame in GUI from there */
}
userAnswer method:
public boolean userAnswer() {
#SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
if( Objects.equals(getAnswer(),userInput) ) {
System.out.println("Correct");
return true;
}
System.out.println("False");
return false;
}
Thanks for help.
You're correct in thinking that it related to threads.
When you try executing code that will take a long time to process (eg. downloading a large file) in the swing thread, the swing thread will pause to complete execution and cause the GUI to freeze. This is solved by executing the long running code in a separate thread.
As Sergiy Medvynskyy pointed out in his comment, you need to implement the long running code in the SwingWorker class.
A good way to implement it would be this:
public class TestWorker extends SwingWorker<Integer, String> {
#Override
protected Integer doInBackground() throws Exception {
//This is where you execute the long running
//code
controller.startTest(index, idUser);
publish("Finish");
}
#Override
protected void process(List<String> chunks) {
//Called when the task has finished executing.
//This is where you can update your GUI when
//the task is complete or when you want to
//notify the user of a change.
}
}
Use TestWorker.execute() to start the worker.
This website provides a good example on how to use
the SwingWorker class.
As other answers pointed out, doing heavy work on the GUI thread will freeze the GUI. You can use a SwingWorker for that, but in many cases a simple Thread does the job:
Thread t = new Thread(){
#Override
public void run(){
// do stuff
}
};
t.start();
Or if you use Java 8+:
Thread t = new Thread(() -> {
// do stuff
});
t.start();

Communication between GUI and persistent backend (running in separate thread)

Hello I know there is many questions about it and some relevant answers. Like for returning response into GUI JTextArea from backend use SwingUtilities.invokeLater and for passing messages to backend using blocking queue. This I can work with.
But I would like to skip implementing queue's message parser. I would like to know if there is possible to directly call methods from another thread. Good partial answer is to call method using class implements runnable but it is only able to start a single task thread. What I'm looking for is a persistent object accepting more methods to be called from another thread and performing serialization.
So to say it more concretely:
1st thread is GUI having multiple button like "open device", "set reg A to user input", "set reg B to user input", "enable feature X", "flash FW"...
2nd is a working thread - it is already done consisting of multiple class. And having methods which needs to be called from GUI.
I need following properties
- working thread is only 1 and persistent through all GUI calls
- all GUI calls shall be serialized (another call is started only after first call is fully processed and returns)
- working thread shall be able to send some "log messages" into GUI (for example % of flashed FW) (this probably can be done easily by SwingUtilities.invokeLater)
Is there a better way to call methods than implement queue parser? If there is can you provide some link to good example? Or is the queue correct approach to this task? If the Queue is the correct approach how to best encode different parameters? Eg "flash firmware" button would need to pass "File", "set reg A to value XY" button would need to pass Byte...
You can use Executors.newSingleThreadExecutor() to create an Executor to run tasks. Once you have the Executor instance you can send Runnable objects to it. The tasks will be queued and each task will run to completion before the next task is begun, all using the same worker thread.
For instance, in your UI thread you can send a task to the executor like this:
ExecutorService executor = Executors.newSingleThreadExecutor();
...
JButton b1 = new JButton("doTask1");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
executor.execute(yourRunnable1);
});
});
JButton b2 = new JButton("doTask2");
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
executor.execute(yourRunnable2);
});
});
Based on user "mevqz" answer I made a example code. It is fully working and seems to be the good answer to my question. I'm providing this example code as elaborated answer - as it still was quite a effort for me to put it together. Also as a newbie I would like to ask if I got mevqz hint correctly and my code is truly thread safe?
Here is basically just an original Backend, where I have implemented possibility to call method log() which shall write back into GUI JTextArea in thread safe manner.
import javax.swing.*;
public class Backend {
private int handle=0;
private int regA=0;
Main guiLogger;
Backend(Main guiLog){ // interface having log() would be enough
guiLogger = guiLog;
}
public void log(final String txt){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
guiLogger.log(txt);
}
});
}
public void open(){
log("openning\n");
// some code that work longer time...
try{
Thread.sleep(1000);
}catch(Exception e){}
handle++;
log("opened: "+handle+"\n");
}
public void setRegA(int val){
log("using handle:"+handle+" set reg A val: "+val+"\n");
regA = val;
}
}
Here is wrapper which which holds executorService and Backend reference. Here it seems not so nice as Backend is actually stored in wrong thread and always passing into Runnable.run(). Is there better way to hide Backend reference directly into ExecutorService?
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class BackendRunWrapper{
private Backend backend; // never call it from this thread
private ExecutorService executor;
public BackendRunWrapper(Main logger){
backend = new Backend(logger);
executor = Executors.newSingleThreadExecutor();
}
public void executorShutdown(){
executor.shutdown();
}
public void open(){
executor.execute(new Runnable(){
public void run(){
BackendRunWrapper.this.backend.open();
}
});
}
public void setRegA(final int val){
executor.execute(new Runnable(){
public void run(){
BackendRunWrapper.this.backend.setRegA(val);
}
});
}
}
Here is just a main gui with 2 buttons "Open" and "SetRegA" and JTextArea for logging. This only calls function from BackendRunWrapper. The only question here is wether executorShutdown() is called correctly?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Main{
BackendRunWrapper backendWrapper;
StringBuilder sb;
JTextArea jta;
public void log(String txt){
sb.append(txt);
jta.setText(sb.toString());
}
public Main(){
backendWrapper = new BackendRunWrapper(this);
sb = new StringBuilder();
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = frame.getContentPane();
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
JButton b1 = new JButton("open");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
backendWrapper.open();
}});
pane.add(b1);
JButton b2 = new JButton("setRegA");
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
backendWrapper.setRegA(42);
}});
pane.add(b2);
jta = new JTextArea(20, 80);
pane.add(jta);
frame.pack();
frame.setVisible(true);
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
Main.this.backendWrapper.executorShutdown();
}}));
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Main();
}});
}
}

User input when SwingWorker doInBackground is executing

I am using a SwingWorker to execute something in the background. During the execution I have a condition where I need to ask the user something by throwing up a JoptionPane.showOptionDialog().
I don't want to do this in my model class and dont want to do this when SwingWorker.doInBackground is executing.
I am sure many people have faced this.
So I have to return back from the call to doInBackground and then ask for the user input in done(). I then need to start another SwingWorker and execute a doInBackground() from the done method?
Is there another neater/simpler way of doing this?
Update (for mkorbel's question)
The class design is like this:
public class OptionInSwingWorker {
public static void main(String[] args) {
JFrame frame=new JFrame();
JButton test = new JButton("Test");
frame.add(test);
test.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new SwingWorker<Void,Void>(){
#Override
protected Void doInBackground() throws Exception {
// check for a value in the database
// if value is something.. throw up an OptionPane
// and ask the user a question..
// then do something...
return null;
}
#Override
protected void done() {
// open some other dialog
}
}.execute();
}
});
}
}
Make a SwingUtilities.invokeLater call that does a prompt and returns the result back to the SwingWorker. If possible have the SwingWorker move on, otherwise just have it loop and wait while it checks for a response.
This will allow you not have to return and start a new SwingWorker later. Although, depending on what you are doing, starting a new SwingerWorker might actually be cleaner and clearer.

Wait for Swing Interface to close before proceeding

I've been searching near and far for a solution to my question but I am having difficulty even defining my search terms.
I have a method that creates a Swing GUI using invokeLater where the user completes some task. Once the task is completed, the window closes and the initial calling thread (e.g. the method) should resume execution. To be more specific, here is a summary of the method:
public class dfTestCase extends JFrame{
public dfTestCase{
... //GUI code here
}
public String run()
{
CountDownLatch c = new CountDownLatch(1);
Runnable r = new Runnable()
{
public void run()
{
setVisible(true); //make GUI visible
}
};
javax.swing.SwingUtilities.invokeLater(r);
//now wait for the GUI to finish
try
{
testFinished.await();
} catch (InterruptedException e)
{
e.printStackTrace();
}
return "method finished";
}
public static void main(String args[]){
dfTestCase test = new dfTestCase();
System.out.println(test.run());
}
}
Within the GUI, I have actionListeners for buttons that will close and countDown the CountDownLatch.
While the CountDownLatch works, it is not suitable for my purposes because I need to run this GUI several times and there is no way to increment the latch. I'm looking for a more elegant solution - it is my best guess that I would need to make use of threads but am unsure how to go about this.
Any help would be much appreciated!
Update
Some clarification: What is happening is that an external class is calling the dfTestCase.run() function and expects a String to be returned. Essentially, the flow is linear with the external class calling dfTestCase.run()-->the GUI being invoked-->the user makes a decision and clicks a button-->control to the initial calling thread is returned and run() is completed.
For now my dirty solution is to just put a while loop with a flag to continuously poll the status of the GUI. I hope someone else can suggest a more elegant solution eventually.
public class dfTestCase extends JFrame{
public dfTestCase{
... //GUI code here
JButton button = new JButton();
button.addActionListener{
public void actionPerformed(ActionEvent e){
flag = true;
}
}
}
public String run()
{
Runnable r = new Runnable()
{
public void run(){
setVisible(true); //make GUI visible
};
javax.swing.SwingUtilities.invokeLater(r);
//now wait for the GUI to finish
while (!flag){
sleep(1000);
}
return "method finished";
}
public static void main(String args[]){
dfTestCase test = new dfTestCase();
System.out.println(test.run());
}
}
Modal dialogs and SwingUtilities#invokeAndWait iso invokeLater should allow you to capture user input and only continue the calling thread when the UI is disposed
For an example of using model dialogs you can check out the ParamDialog class I wrote. In particular, check out ParamDialog.getProperties(Properties);
http://tus.svn.sourceforge.net/viewvc/tus/tjacobs/ui/dialogs/

Categories

Resources