Timer in Console based program [duplicate] - timer

I am trying to make a game where you can only enter words for 10 seconds. I tried to create a multithread solution but it doesn't work properly.
class timer extends Thread{//thread
public void run(){
for(int i=10;i>=0;i--){
System.out.print(i+" ");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Main method:
timer t=new timer();
t.start();
while () {//not sure what to put in my while statement
System.out.print("Guess a word on the board! ");
if(test.CheckGame(scan.next())==true){
System.out.print("Good job! ");
}
else
System.out.print("Guess again! ");
}
essentially, after the thread goes for 10 seconds and terminates,I want it to return a break statement so the program leaves the while loop. Any suggestions?

Change your code to this
timer t=new timer();
t.start();
while (t.isAlive()) {//not sure what to put in my while statement
System.out.print("Guess a word on the board! ");
if(test.CheckGame(scan.next())==true){
System.out.print("Good job! ");
}
else
System.out.print("Guess again! ");
}
Once the run function exits, t.isAlive will be false. You may also need to pass the timer object around and check the isAlive() of the object, depending on how CheckGame works. This is so that the input cannot be put in after the 10 seconds for an indefinite period of time.

Here is a simple Demo that would let you to know how to use java.util.Timer .
import java.util.Timer;
import java.util.TimerTask;
import java.util.Scanner;
class Tester
{
static long i = 0;
public static void main(String[] args) throws Exception
{
Scanner scanner = new Scanner(System.in);
System.out.println("You have only 10 seconds to find the result");
System.out.println("What is the value of : 111111 X 111111 ");
Timer timer = new Timer("Timer");
timer.schedule(new TimerTask()
{
public void run()
{
if (i == 12345654321L)
{
System.out.println("Congrats!! you guessed the write answer :)");
}
else
{
System.out.println("Sorry Time is over. You couldn't guess the correct answer.");
}
System.exit(0);
}
},10 * 1000 , 1);
while (true)
{
i = scanner.nextLong();
if ( i == 12345654321L)
{
System.out.println("Congrats!! you guessed the write answer :)");
System.exit(0);
}
else
{
System.out.println("Try next guess :");
}
}
}
}
EDIT
Since I don't have your all code so I am posting here the solution for your answer on my basic assumption. Don't use Thread. Instead use java.util.Timer. Your code would look as follows:
static String input=" ";//created a static variable input to take input
public static void main(String st[])
{
Timer timer = new Timer("Timer");
timer.schedule(new TimerTask()
{
public void run()
{
if (test.CheckGame(input))
{
System.out.println("Congrats!! you guessed the write answer :)");
}
else
{
System.out.println("Sorry Time is over. You couldn't guess the correct answer.");
}
System.exit(0);
}
},10 * 1000 , 1);//waits for 10 seconds
while (true)
{
System.out.print("Guess a word on the board! ");
input = scan.next();
if(test.CheckGame(input))
{
System.out.print("Good job! ");
System.exit(0);
}
else
{
System.out.println("Bad Guess. Try again ");
}
}
}

You could have a shared boolean where your thread and main share in a synchronized fashion.
The timer could be as follows;
class timer extends Thread{//thread
private Object lock = new Object(); // a lock used by both your thread and main to access stop boolean
private boolean stop = false;
public void setStop() // your thread calls this method in order to set stop
{
synchronized(lock) {
stop = true;
}
}
public boolean getStop() // main calls this to see if thread told main to stop.
{
boolean _stop;
synchronized(lock) {
_stop = stop;
}
return _stop;
}
public void run(){
for(int i=10;i>=0;i--){
System.out.print(i+" ");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
setStop();
}
}
}
Your main could be as follows:
timer t=new timer();
t.start();
while (!t.getStop()) {// calls getStop to see if other thread told main to stop
System.out.print("Guess a word on the board! ");
if(test.CheckGame(scan.next())==true){
System.out.print("Good job! ");
}
else
System.out.print("Guess again! ");
}
t.join(); // to make sure main terminates after the termination of other thread

Related

stop java Timers in a loop to execute simultaneously

Need help a bit, please. How to make it work in the following order: check value of an i, run Timer for it, ONLY when that timer is finished, do i++? For now two timers run at the same time. Tried to declare boolean isRunning, but did not help.
for(int i=0;i<pcArray.length;i++){
if(pcArray[i]==1){
blinkGreen.start(); }
else if(pcArray[i]==2){
blinkRed.start();
}
}
First add a boolean variable in blinkGreen and also in blinkRed Timer like this,
In BlinkGreen:
boolean isRunningGreen = false;
Timer blinkGreen = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
// do stuff
isRunningGreen = true;//This statement must be placed at the end/bottom of this method
}
};
In BlinkRed:
boolean isRunningRed = false;
Timer blinkRed = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
// do stuff
isRunningRed = true;//This statement must be placed at the end/bottom of this method
}
};
Now try this:
for(int i=0;i<pcArray.length;i++){
if(pcArray[i]==1){
blinkGreen.start();
while(!isRunningGreen){}//waiting until the task is completed
} else if(pcArray[i]==2){
blinkRed.start();
while(!isRunningRed){}//waiting until the task is completed
}
}

Implementing 'waitForNewWindow' in selenium webdriver

I am trying to implement a method 'waitForNewWindow' in Java using selenium WebDriver. This method is all about waiting to check if a new window is opened. If a new window is opened in the specified time, i need to return true, else return false.
public boolean waitForNewWindow(String target) {
try {
Thread.sleep(30000);
if(driver.switchTo().window(target)!=null) {
log.info("New window is opened");
return true;
}
}catch(Exception e) {
log.debug(e);
return false;
}
return true;
}
But here, I don't want to use thread.sleep(time). The waiting time needs to be specified as below:
WebDriverWait wait = new WebDriverWait(driver, TIMEOUT);
Moreover, in the above code, the control is switching to the new window, which is not expected. Can someone please provide your answers on how to implement my requirement?
the below mentioned code checks for the number of windows to appear with time out
public void waitForNumberOfWindows(final int length){
new WebDriverWait(driver, 30) {
}.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return driver.getWindowHandle().length()==length;
}
});
}
it will check for the expected number of windows to be present at that instance and will return true if the count matches with in the specified timeout(30 in above code)
You can not specify a timeout like you want. You have to use Thread.sleep().
Regarding your control moving to new window because of your below line the control is moving to new tab
driver.switchTo().window(target)
If you want to simply check if there is two windows open or not, you can write something like below
while( driver.getWindowHandle().length() != 2){
Thread.sleep(2000);
}
Finally got the implementation of waitForNewWindow method, using the WebDriverWait object as below:
try {
ExpectedCondition<Boolean> e = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver wd) {
if (wd.switchTo().window(newTarget) != null) {
log.info("New window is opened with the window id : "
+ newTarget);
driver.switchTo().window(parentHandle);
return true;
} else {
return false;
}
}
};
WebDriverWait wait = new WebDriverWait(driver, TIMEOUT);
if (wait.until(e)) {
log.info("the wait for the expected condition is successful");
return true;
}
} catch (Exception e1) {
log.debug(e1);
return false;
}
Tested the same and its working fine.

MediaRecorder-recording video using mediarecorder

iam using mediarecorder to record video in android application. I will start and stop recording video multiple times i will start recording on Action_down and stop on Action_up this is going on well and iam able to store and play video file in mobile .
my problem is that since i have to start and stop recording video multiple times i can't use single output file becuase everytime it will get over written so everytime iam passing new file name and iam appending that to one outputfile everytime.iam getting every individual file and final outputfile in mobile but final file is having only what i have recorded for the first time because from second tab if see the file.mp4.length()is zero why it is ? anyone please try to help me. my code is as follows
package com.example.longtouch;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.net.rtp.AudioGroup;
import android.net.rtp.AudioStream;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Handler.Callback;
import android.provider.MediaStore.Audio;
import android.provider.MediaStore.Files;
import android.provider.MediaStore.Video;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity implements OnTouchListener{
int i=1;
File outputFile;
File f1;
File f2;
MediaRecorder mediaRecorder;
ThreadProgress mThreadProgress;
ThreadProgress2 mThreadProgress2;
public int eventAction;
Handler handler;
Handler mHandler;
Button myButton;
FrameLayout myCameraPreview;
Button submit;
Button submit1;
LinearLayout ll;
ProgressBar progressBar;
int progressStatus=0;
MyCameraSurfaceView myCameraSurfaceView;
Camera myCamera;
boolean recording;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recording=false;
myButton=(Button)findViewById(R.id.button_capture);
submit=(Button)findViewById(R.id.submit);
submit1=(Button)findViewById(R.id.submit1);
progressBar=(ProgressBar)findViewById(R.id.progress_bar);
progressBar.setMax(10000);
myCamera = getCameraInstance();
if(myCamera == null){
Toast.makeText(MainActivity.this,
"Fail to get Camera",
Toast.LENGTH_LONG).show();
}
// else
// myCamera.unlock();
myCameraSurfaceView = new MyCameraSurfaceView(this, myCamera);
myCameraPreview=(FrameLayout)findViewById(R.id.camera_preview);
myCameraPreview.addView(myCameraSurfaceView);
ll=(LinearLayout)findViewById(R.id.ll);
myCameraPreview.setOnTouchListener(this);
outputFile=new File("/sdcard/myvideo.mp4");
if(outputFile.exists()){
outputFile.delete();
outputFile=new File("/sdcard/myvideo.mp4");
try {
outputFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
try {
outputFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
f1=new File("/sdcard/myvideo1.mp4");
if(f1.exists()){
f1.delete();
f1=new File("/sdcard/myvideo1.mp4");
try{
f1.createNewFile();
}
catch(Exception e){
e.printStackTrace();
}
}
else{
try{
f1.createNewFile();
}
catch(Exception e){
e.printStackTrace();
}
}
f2=new File("/sdcard/myvideo2.mp4");
if(f2.exists()){
f2.delete();
f2=new File("/sdcard/myvideo2.mp4");
try{
f2.createNewFile();
}
catch(Exception e){
e.printStackTrace();
}
}
else{
try{
f2.createNewFile();
}
catch(Exception e){
e.printStackTrace();
}
}
}
/* public int getFrontCameraId() {
CameraInfo ci = new CameraInfo();
for (int i = 0 ; i < Camera.getNumberOfCameras(); i++) {
Camera.getCameraInfo(i, ci);
if (ci.facing == CameraInfo.CAMERA_FACING_FRONT) return i;
}
return -1; // No front-facing camera found
}*/
private Camera getCameraInstance(){
// TODO Auto-generated method stub
Camera c = null;
try {
/* int index = getFrontCameraId();
if (index != -1)
c = Camera.open(index);*/
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
public void submit(View v){
// stop recording and release camera
// mediaRecorder.stop(); // stop the recording
// releaseMediaRecorder(); // release the MediaRecorder object
Log.d("outputFile",""+f1.length());
progressStatus=progressBar.getProgress();
//Exit after saved
// finish();
myButton.setText("capture");
recording=false;
submit.setVisibility(View.GONE);
}
public void submit1(View v){
// stop recording and release camera
// mediaRecorder.stop(); // stop the recording
// releaseMediaRecorder(); // release the MediaRecorder object
progressBar.setProgress(0);
progressStatus=0;
//Exit after saved
// finish();
myButton.setText("capture");
recording=false;
submit1.setVisibility(View.GONE);
}
public void display(View v){
Intent i=new Intent(this,VideoPlayer.class);
startActivity(i);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public boolean onTouch(View arg0, final MotionEvent event) {
// TODO Auto-generated method stub
eventAction=event.getAction();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
{
i=i+1;
Toast.makeText(getApplicationContext(),"action_down",Toast.LENGTH_SHORT).show();
//releaseCamera();
if(!prepareMediaRecorder()){
Toast.makeText(MainActivity.this,
"Fail in prepareMediaRecorder()!\n - Ended -",Toast.LENGTH_LONG).show();
finish();
}
progressBar.setProgress(progressStatus);
myButton.setText("STOP");
try{
mediaRecorder.start();
}
catch(Exception e){
e.printStackTrace();
Log.d("vd","exception at start method");
}
if(f1.exists()){
long l=f1.length();
Log.d("start","started"+l);
}
if(f2.exists()){
long m=f2.length();
Log.d("start","started"+m);
}
recording = true;
if(progressBar.getProgress()>=5000){
mThreadProgress2=new ThreadProgress2();
mThreadProgress2.start();
}
mHandler = new Handler(new Callback() {
public boolean handleMessage(final Message msg) {
runOnUiThread(new Runnable() {
public void run() {
if( event.getAction()!=MotionEvent.ACTION_UP){
progressBar.setProgress(msg.arg1);
}
if(progressBar.getProgress()==10000){
Log.d("unicorn","1000");
submit1.setVisibility(View.VISIBLE);
}
}
});
return false;
}
});
mThreadProgress=new ThreadProgress();
mThreadProgress.start();
handler = new Handler(new Callback() {
public boolean handleMessage(final Message msg) {
runOnUiThread(new Runnable() {
public void run() {
if( event.getAction()!=MotionEvent.ACTION_UP)
progressBar.setProgress(msg.arg1);
if(progressBar.getProgress()==5000){
submit.setVisibility(View.VISIBLE);
}
}
});
return false;
}
});
return true;
}
case MotionEvent.ACTION_UP:
{ // nothing to do
Toast.makeText(getApplicationContext(),"action_up",Toast.LENGTH_SHORT).show();
myButton.setText("capture");
mediaRecorder.stop(); // stop the recording
releaseMediaRecorder(); // release the MediaRecorder object
try {
myCamera.reconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Exit after saved
// finish();
recording=false;
progressStatus=progressBar.getProgress();
if(i%2==0){
long len=f1.length();
Log.d("length",""+f1.getPath()+len);
Combine1 c1=new Combine1();
c1.start();
}
else{
long len=f2.length();
Log.d("length",""+f2.getPath()+len);
Combine2 c2=new Combine2();
c2.start();
}
break;
}
default:
return false;
}
return true;
}
private boolean prepareMediaRecorder(){
// myCamera = getCameraInstance();
mediaRecorder = new MediaRecorder();
myCamera.stopPreview();
myCamera.unlock();
mediaRecorder.setCamera(myCamera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
// mediaRecorder.setVideoSize(400,400);
if(i%2==0){
Log.d("outputfile",""+f1.getPath()+f1.length());
mediaRecorder.setOutputFile(f1.getPath());
Log.d("outputfile",""+f1.getPath()+f1.length());
}
else{
Log.d("outputfile",""+f2.getPath()+f2.length());
mediaRecorder.setOutputFile(f2.getPath());
Log.d("outputfile",""+f2.getPath()+f2.length());
}
mediaRecorder.setMaxDuration(10000); // Set max duration 10 sec.
mediaRecorder.setMaxFileSize(5000000); // Set max file size 5M
// mediaRecorder.setOnInfoListener(this);
mediaRecorder.setPreviewDisplay(myCameraSurfaceView.getHolder().getSurface());
try {
mediaRecorder.prepare();
} catch (IllegalStateException e) {
Log.d("prepare","illegalstateexception");
e.printStackTrace();
releaseMediaRecorder();
Toast.makeText(getApplicationContext(),"illegal state exception",Toast.LENGTH_SHORT).show();
return false;
} catch (IOException e) {
Log.d("prepare","ioexception");
e.printStackTrace();
releaseMediaRecorder();
Toast.makeText(getApplicationContext(),"IOexception",Toast.LENGTH_SHORT).show();
return false;
}
Log.d("after prepare","after prepare f1"+f1.length());
Log.d("after prepare","after prepare f2"+f2.length());
return true;
}
public void combine(String file){
Log.d("combine","combining"+file);
try{
File inputFile=new File(file);
FileInputStream fis=new FileInputStream(inputFile);
long inputlen=inputFile.length();
Log.d("combine","lengthbefore write"+inputlen);
File outputFile = new File("/sdcard/myvideo.mp4");
FileOutputStream fos = new FileOutputStream(outputFile,true);
byte fileContent[]= new byte[(int)inputFile.length()];
fis.read(fileContent);
long len=outputFile.length();
Log.d("combine","lenth"+len);
fos.write(fileContent);
fis.close();
fos.close();
inputlen=inputFile.length();
len=outputFile.length();
Log.d("combine","inputlength"+inputlen);
Log.d("combine","lenth"+len);
/* File f= new File(file);
boolean deleted = f.delete();
if(deleted){
Log.d("combine","deleted"+file);
} */
}
catch(Exception e){
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
releaseMediaRecorder(); // if you are using MediaRecorder, release it first
releaseCamera(); // release the camera immediately on pause event
}
private void releaseMediaRecorder(){
if (mediaRecorder != null) {
mediaRecorder.reset(); // clear recorder configuration
mediaRecorder.release(); // release the recorder object
mediaRecorder = null;
// myCamera.lock(); // lock camera for later use
}
}
private void releaseCamera(){
if (myCamera != null){
myCamera.release(); // release the camera for other applications
myCamera = null;
}
}
public class MyCameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback{
private SurfaceHolder mHolder;
private Camera mCamera;
public MyCameraSurfaceView(Context context, Camera camera) {
super(context);
mCamera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceChanged(SurfaceHolder holder, int format, int weight,
int height) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (mHolder.getSurface() == null){
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
}
// make any resize, rotate or reformatting changes here
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
}
}
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
// The Surface has been created, now tell the camera where to draw the preview.
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
public class ThreadProgress extends Thread implements Runnable {
int progressValue=progressStatus;
public void run() {
while( progressBar.getProgress()<5000 && eventAction!=MotionEvent.ACTION_UP ) {
Log.d("unicorn","in while loop"+progressValue);
progressValue++;
Message message = new Message();
message.arg1 = progressValue;
if(progressValue<=5000 && eventAction!=MotionEvent.ACTION_UP)
handler.sendMessage(message);
}
}
}
public class ThreadProgress2 extends Thread implements Runnable {
int progressValue=progressStatus;
#Override
public void run() {
while( progressBar.getProgress()<10000 && eventAction!=MotionEvent.ACTION_UP ) {
// try{
Log.d("unicorn2","in while loop"+progressValue);
progressValue++;
Message message = new Message();
message.arg1 = progressValue;
if(progressValue<=10000 && eventAction!=MotionEvent.ACTION_UP)
mHandler.sendMessage(message);
//Thread.sleep(1000);
//} catch (InterruptedException e){
// e.printStackTrace();
// break;
// }
}
}
}
public class Combine1 extends Thread implements Runnable{
public void run(){
try{
int c;
FileInputStream fin=new FileInputStream(f1);
FileOutputStream fout=new FileOutputStream(outputFile,true);
long len1=f1.length();
Log.d("length","myvideo1.mp4"+len1);
long len2=outputFile.length();
Log.d("length","myvideo.mp4"+len2);
while((c=fin.read())!=-1){
fout.write(c);
}
len2=outputFile.length();
Log.d("length","myvideo.mp4"+len2);
fin.close();
fout.flush();
fout.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
public class Combine2 extends Thread implements Runnable{
public void run(){
try{
int j=0;
FileInputStream fin=new FileInputStream(f2);
FileOutputStream fout=new FileOutputStream(outputFile,true);
long len1=f2.length();
Log.d("length","myvideo2.mp4"+len1);
long len2=outputFile.length();
Log.d("length","myvideo.mp4"+len2);
while((j=fin.read())!=-1){
fout.write(j);
}
len2=outputFile.length();
Log.d("length","myvideo.mp4"+len2);
fin.close();
fout.flush();
fout.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
In order to combine multiple video files you should use mp4parser library : https://mp4parser.googlecode.com/svn/trunk/examples/src/main/java/com/googlecode/mp4parser/AppendExample.java

is there any way call other JinternalFrame from an JinternalFrame but, in the desktopPane of of main Jframe.

The "code part 1" below is used for calling UcakListesi(JinternalFrame) from menuItem in MDI application without problem.
I would like to call same UcakListesi(JinternalFrame) from another JinternalFrame using same code however, I get error about "desktopPane.add(nw);" line see code part 2. Can't access main jframe desktopPane form JinternalFrame ..
is there any way call other JinternalFrame from an JinternalFrame but, in the desktopPane of of main Jframe.
sorry for my poor english.
Regards and thank you.
---code part 1---
private void UckListeMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
//Uçak listesi penceresi çağrılıyor
UcakListesi nw = UcakListesi.getInstance();
nw.pack();
if (nw.isVisible()) {
} else {
desktopPane.add(nw);
nw.setVisible(true);
}
try {
//açılan internal frame'in max size ile açılması için
nw.setMaximum(true);
} catch (PropertyVetoException ex) {
Logger.getLogger(AnaUygulama.class.getName()).log(Level.SEVERE, null, ex);
}
}
---code part 2---
class PopUpx extends JPopupMenu {
JMenuItem anItem1;
JMenuItem anItem2;
JMenuItem anItem3;
JMenuItem anItem4;
JMenuItem anItem5;
JSeparator anSeparator1;
JSeparator anSeparator2;
JSeparator anSeparator3;
JSeparator anSeparator4;
JMenu yeni;
ActionListener anListener2;
public PopUpx(final String x){
anItem1 = new JMenuItem(x+ " numaralı Uçak için");
anItem2 = new JMenuItem("Detay Bilgiler");
anItem3 = new JMenuItem("Arıza İş Emri Aç");
anItem4 = new JMenuItem("Uçuş Öncesi Servis");
anItem5 = new JMenuItem("Uçuş Sonrası Servis");
anSeparator1 = new JSeparator();
anSeparator2 = new JSeparator();
anSeparator3 = new JSeparator();
anSeparator4 = new JSeparator();
yeni = new JMenu ("Servis İşlemleri");
add(anItem1);
anItem1.setEnabled(false);
add(anSeparator1);
add(anItem2);
anItem2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
System.out.println(x+" nolu uçağın "+anItem2.getText()+" basıldı");
UcakListesi nw = UcakListesi.getInstance();
nw.pack();
if (nw.isVisible()) {
} else {
//problem is here
desktopPane.add(nw);
nw.setVisible(true);
}
try {
//açılan internal frame'in max size ile açılması için
nw.setMaximum(true);
} catch (PropertyVetoException ex) {
Logger.getLogger(AnaUygulama.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
anItem2.setToolTipText(x+ " numaralı Uçağın Detay Bilgilerine ulaşılır...");
add(anSeparator2);
add(anItem3);
add(anSeparator3);
yeni.add(anItem4);
add(anSeparator4);
add(yeni);
yeni.add(anItem4);
yeni.add(anSeparator4);
yeni.add(anItem5);
}}
I found the solution .
for the first class(MainApplication) where your Jframe and JDesktopPane inside place code below
public javax.swing.JDesktopPane getDesktopPane() {
return desktopPane;
}
then use in any JinternalFrame class file like this to call another one(YourJinternalFrame)
YourJinternalFrame nw = YourJinternalFrame.getInstance();
nw.pack();
if (nw.isVisible()) {
} else {
getDesktopPane().add(nw);
nw.setVisible(true);
}
try {
nw.setMaximum(true);
} catch (PropertyVetoException ex) {
Logger.getLogger(MainApplication.class.getName()).log(Level.SEVERE, null, ex);
}
to get only one instance of called JinternalFrame
place this code below in the called JinternalFrame(YourJinternalFrame)
private static YourJinternalFrame myInstance;
public static YourJinternalFrame getInstance() {
if (myInstance == null) {
myInstance = new YourJinternalFrame();
}
return myInstance;
Thank me:)
First create f1 frame object on f2 button action
F1 f1 = new F1();
Then create a JDesktopPane object like this
JDesktopPane desktopPane = getDesktopPane();
desktopPane.add(f1);//add f1 to desktop pane
f1.setVisible(true);// set the f1 frame visible
Finally if needed dispose the current frame
this.dispose();

The calling thread cannot access this object because a different thread owns it

I am getting the exception "The calling thread cannot access this object because a different thread owns it" inspite of using Dispatcher.Invoke.
Below is the code: _btnImage1 is an instance of ImageButton declared in xaml of LaneImageReview. Note that I used Dispatcher in the RefreshLiveVESImage method below.
public partial class LaneImageReview : Page
{
private void RefreshLiveVESImages(VESImagePackageInfo p_VesImageInfo)
{
this._btnImage1.RefreshLiveVESImage(p_VesImageInfo);
}
}
public class ImageButton : Button
{
public void RefreshLiveVESImage(VESImagePackageInfo p_VesImageInfo)
{
BitmapImage bitmap = null;
try
{
//load background if not photo available
//if (p_Image == null)
//{
// _imgPhoto.Source = null;
//}
//else
//{
foreach (VESCameraInfo camInfo in p_VesImageInfo.VESCameras)
{
if (camInfo.CameraImageSets[0].FullImage != null)
{
bitmap = DVASViewController.GetBitmapImageFromByteArray(camInfo.CameraImageSets[0].FullImage.VESImage);
this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action<BitmapImage>(SetImageSource), bitmap);
break;
}
}
//}
}
catch (Exception ex)
{
SecurityController.CatchException(ex);
}
finally
{
}
}
private void SetImageSource(BitmapImage p_Image)
{
this.imgFrontLeft.Source = p_Image;
}
}
Thanks.
you can try something like
Application.Current.Dispatcher.Invoke((ThreadStart)delegate
{
DoWork();
});

Resources