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

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();

Related

Why do i never enter in specific callback functions in native interface?

I'm making an application which has to detect a bluetooth card reader and if a card is inserted or removed from this one.
I'm using an API for the android part in my native interface so I implement two callback functions from an interface which concerns the bluetooth card reader detection and two other callback functions which concerns the detection of cards in the bluetooth card reader.
Two callback functions which are called when the bluetooth card reader is detected and the two others which are called when a card is inserted or removed from the device.
I have no problem with the callback which are called when the bluetooth card reader is detected but the application never calls the functions which must be called when the card are inserted or removed.
public class FtReaderNativeImpl implements BluetoothRead.CardListener,BluetoothRead.ReaderListener{
private BluetoothRead btRead;
ArrayList<BluetoothDevice> listRead;
public String scanBluetooth(){
String chaine ="";
if (Looper.myLooper() == null)
{
Looper.prepare();
}
Log.p("btread avant init:"+btRead);
btRead = new
BluetoothRead(com.codename1.impl.android.AndroidNativeUtil.getContext());
btRead.setCardListener(this);
btRead.setReaderListener(this);
ReturnCode rc = btRead.btInitLib();
Log.p("btread après init:"+btRead);
Log.p("rc:"+rc);
return chaine;
}
#Override
public void CardInserted()
{
//showMessage("onCardInserted");
String chaine="";
//Toast.makeText(com.codename1.impl.android.AndroidNativeUtil.getActivity(), "INSERTED", Toast.LENGTH_SHORT).show();
chaine+=btRead.getName();
chaine+=btRead.getFirstName();
eidReader.showDialog("INSERTED "+chaine);
Log.p("btInsertOK");
}
#Override
public void CardRemoved()
{
String chaine="";
//Toast.makeText(com.codename1.impl.android.AndroidNativeUtil.getActivity(), "REMOVED", Toast.LENGTH_SHORT).show();
EidReader.showDialog("REMOVED "+chaine);
Log.p("btRemoveNOK");
}
#Override
public void ReaderConnected(BluetoothDevice bluetoothDevice)
{
/*Toast.makeText(com.codename1.impl.android.AndroidNativeUtil.getActivity(), "CONNECTED", Toast.LENGTH_SHORT).show();*/
EidReader.showDialog("CONNECTED");
Log.p("onReaderConnected: " + bluetoothDevice.getName());
if (btRead.btOpen(bluetoothDevice) == ReturnCode.OK) {
Log.p("btOpen OK");
} else {
Log.p("btOpen NOK");
}
Log.p("btread après listener:"+btRead);
}
#Override
public void ReaderDisconnected(BluetoothDevice bluetoothDevice)
{
//Toast.makeText(com.codename1.impl.android.AndroidNativeUtil.getActivity(), "DISCONNECTED", Toast.LENGTH_SHORT).show();
EidReader.showDialog("DISCONNECTED");
}}
ScanBluetooth is just a initialization method which is called in the beginning of the form:
public class EidReader extends Form implements HasLogger {
Container loggatt = new Container();
private Bluetooth bt;
private static Container devicesCnt;
private Map devices = new HashMap();
Form main = this;
FtReaderNative frn;
public EidReader(Form parent)
{
this.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
Display dis = Display.getInstance();
frn = (FtReaderNative)NativeLookup.create(FtReaderNative.class);
if(dis.getPlatformName().compareTo("and")==0){
LocationManager lm = LocationManager.getLocationManager();
}
bt = new Bluetooth();
frn.scanBluetooth();
//combo.setRenderer(new GenericListCellRenderer<>(new MultiButton(),new MultiButton()));
this.add(new Button(new Command("enable bluetooth")
{
#Override
public void actionPerformed(ActionEvent evt){
try {
if (!bt.isEnabled()) {
bt.enable();
}
if (!bt.hasPermission()) {
bt.requestPermission();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}));
this.add(new Button(new Command("initialize")
{
#Override
public void actionPerformed(ActionEvent evt)
{
try {
bt.initialize(true, false, "bluetoothleplugin");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}));
Button bttest = new Button("DISPLAY READER");
bttest.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ev)
{
DeleteUI();
StringTokenizer st = new StringTokenizer(frn.infoDevices());
while (st.hasMoreTokens()) {
MultiButton mb = new MultiButton(st.nextToken());
mb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
devicesCnt.add(new SpanLabel(frn.readerStatus( mb.getTextLine1())));
}});
devicesCnt.add(mb);
}
}
});
this.add(bttest);
devicesCnt = new Container(new BoxLayout(BoxLayout.Y_AXIS));
devicesCnt.setScrollableY(true);
this.add(devicesCnt);
this.show();
}
private void DeleteUI()
{
devicesCnt.removeAll();
devicesCnt.revalidate();
}
#Override
public String getLogName()
{
// TODO Auto-generated method stub
return null;
}
public static void showDialog(String txt)
{
//Display.getInstance().callSerially(()->
//{
devicesCnt.add(new SpanLabel(txt));
devicesCnt.forceRevalidate();
//});
}
}

Push notification not reaching when app in foreground

I'm having trouble getting Push Notifications when the app is in foreground in an Android device. As soon as I put the app in the background all goes well.
This is the java code I use to send de notifications:
HttpClient client = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(URL_SERVER);
List<NameValuePair> arguments = new ArrayList<>();
arguments.add(new BasicNameValuePair("token", TOKEN));
arguments.add(new BasicNameValuePair("device", codigoApp));
arguments.add(new BasicNameValuePair("type", "1"));
arguments.add(new BasicNameValuePair("body", ip));
arguments.add(new BasicNameValuePair("auth", GOOGLE_AUTH));
try {
httpPost.setEntity(new UrlEncodedFormEntity(arguments));
HttpResponse response = client.execute(httpPost);
String result = EntityUtils.toString(response.getEntity());
System.out.println(result);
} catch (IOException ex) {
Logger.getLogger(NotificaReview.class.getName()).log(Level.SEVERE, null, ex);
}
And this is the code in the app:
public void start() {
if(current != null){
current.show();
return;
}
if (Push.getPushKey() != null)
devicePush = Push.getPushKey();
else
Display.getInstance().registerPush();
Form inicioGUI = new InicioGUI(devicePush);
inicioGUI.show();
}
public void stop() {
current = getCurrentForm();
if(current instanceof Dialog) {
((Dialog)current).dispose();
current = getCurrentForm();
}
}
public void destroy() {
}
#Override
public void push(String value) {
ToastBar.showMessage("Archivo recibido correctamente con IP" + value, FontImage.MATERIAL_INFO);
}
#Override
public void registeredForPush(String deviceId) {
devicePush = deviceId;
}
#Override
public void pushRegistrationError(String error, int errorCode) {
}
The ToastBar only shows when I bring the app to foreground after receiving the push while in background. The Push callback is never called if the app is alive.
Any ideas?
I need answers to my comment in the question which might help explain the issue. I'll edit this answer based on the updates to the question.
In the meantime I see several issues in the code. See my highlighted comments/fixes below:
public void start() {
if(current != null){
current.show();
return;
}
// don't check the push key, always register the device and
// always do it in a callSerially as it might trigger a prompt
callSerially(() -> registerPush());
Form inicioGUI = new InicioGUI(Push.getPushKey());
inicioGUI.show();
}
#Override
public void push(String value) {
ToastBar.showMessage("Archivo recibido correctamente con IP" + value, FontImage.MATERIAL_INFO);
}
#Override
public void registeredForPush(String deviceId) {
// deviceId is the native push key you need to use the actual
// push key value never device ID
devicePush = Push.getPushKey();
}
#Override
public void pushRegistrationError(String error, int errorCode) {
// you might have gotten a push error which might have explained the
// cause of the problem
Log.p("Push error " + errorCode + ":" + error);
Log.sendLogAsync();
}

Thucyides Test cases Queuing

Implemented A Thucydides(SERENITY) BDD Environment for automated testing of version 0.9.269. I have seen that the runner of test cases picks up the random test stories. Is there any way so that the stories can be queued?
The code for PortalTestSuit is as
public class PortalTestSuite extends ThucydidesJUnitStories {
private static final Logger LOGGER = LoggerFactory.getLogger(PortalTestSuite.class.getName());
/**
* Instantiates a new Portal test suite.
*/
public PortalTestSuite() {
/*Some Code to check the server is working or not*/
/* Do all stories */
findStoriesCalled("*.story");
}}
Here, the findStories will pick up the random stories from the directory and executes relative code... but please let me know the way to queue the Stories. Thanks.
Yes, we can maintain the order of story by overriding storyPaths() method of ThucydidesJUnitStories class.
#Override
public List<String> storyPaths() {
try {
File file = new File(System.getProperty("user.dir").concat("/src/test/resources/StoryContextTest.script"));
try (FileReader reader = new FileReader(file)) {
char[] buffer = new char[(int) file.length()];
reader.read(buffer);
String[] lines = new String(buffer).split("\n");
List<String> storiesList = new ArrayList<>(lines.length);
StoryFinder storyFinder = new StoryFinder();
for (String line : lines) {
if (!line.equals("") && !line.startsWith("#")) {
if (line.endsWith("*")) {
for (URL classpathRootUrl : allClasspathRoots()) {
storiesList.addAll(storyFinder.findPaths(classpathRootUrl, line.concat("*/*.story"), ""));
}
} else {
storiesList.add(line);
}
}
}
return storiesList;
}
} catch (Throwable e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
private List<URL> allClasspathRoots() {
try {
return Collections.list(getClassLoader().getResources("."));
} catch (IOException e) {
throw new IllegalArgumentException("Could not load the classpath roots when looking for story files",e);
}
}
The stories are being loaded from StoryContextTest.script as
################# Stories goes here #################
stories/authentication/authentication/authentication.story
stories/authentication/authentication/authentication1.story
(Or)
*/authentication/* (will get stories randomly)
This way you can serialize your stories as in Thucydides.

VS debugger does not close

I have the following code. can anyone tell me what would happen to ut, c2 instances? Would they be hanging around without being garbage-collected for a long time? The reason I ask is that after I close all the windows including the one that execute this code Visual Studio debugger is still on (I am running it in debug mode).
If I don't raise exception in Initializer() method in Class2, the debugger will close after I close all the windows.
Below is by code
namespace Test
{
public class Class1
{
private ICommand testCommand;
public ICommand TestCommand
{
get
{
return updCommand ?? (updCommand = new DelegateCommand(() =>
{
int nStatus = 0;
Class2 c2 = new Class2();
nStatus = c2.InitStatus;
if (nStatus == 0)
{
c2.doSth()
}
System.Windows.MessageBox.Show("Return status = " + nStatus.ToString());
c2 = null;
}
));
}
}
}
public class Class2
{
Utilities ut = new Utilities();
public int InitStatus { get; set; }
public Dbupdate()
{
Initializer();
}
private void Initializer()
{
try
{
throw new Exception("just test");
}
catch (Exception ex) { ErrHandler("Initializer(): " + ex.Message); InitStatus = -100; }
}
private void doSth()
{
ut.doWhateve();
}
}
}
Figured it out. I instantiated a window but didn't close before throwing the exception.

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