I'm making a simple "paint" application in JAVA. I would have wanted that when the person clicks the canvas, and make a drag and drop, a listener get the drop cursor location, but I don't find how make a drop listener. How can I find the location of the cursor when the user stop his click?
I have the following code for the drag :
Canvas paintC = new Canvas(shell, SWT.NONE);
paintC.addDragDetectListener(new DragDetectListener() {
public void dragDetected(DragDetectEvent arg0) {
Point controlRelativePos = new Point(arg0.x, arg0.y);
displayRelativePos1 = paintC.toDisplay(controlRelativePos);
GC gc = new GC(paintC);
gc.setBackground(SWTResourceManager.getColor(SWT.COLOR_YELLOW));
gc.fillRectangle(arg0.x, arg0.y, 90, 60);
}
});
Should I a drag function in order to get the latest position?
Edit: I've tried this, but it didn't work :
dropTarget.addDropListener(new DropTargetAdapter() {
#Override
public void drop(DropTargetEvent event) {
displayRelativePos2 = dropTarget.getDisplay().getCursorLocation();
hauteur = displayRelativePos2.y - displayRelativePos1.y;
largeur = displayRelativePos2.x - displayRelativePos1.x;
GC gc = new GC(paintC);
gc.setBackground(SWTResourceManager.getColor(SWT.COLOR_RED));
gc.fillRectangle(displayRelativePos1.x, displayRelativePos1.y, largeur, hauteur);
nbFormesAff = nbFormes +1;
forme = "Rectangle" + nbFormesAff;
pos = displayRelativePos1.x + ", " + displayRelativePos1.y +"\nhauteur:" + hauteur +" largeur:"+ largeur;
}
DropTargetEvent has x and y fields which contain the Display relative location of the cursor.
Point displayRelativeDrop = new Point(event.x, event.y);
Your fillRectangle must use points which are relative to the Control (paintC) not the display. Use Control.toControl(point) to convert from display relative to control relative.
You should also not try to draw the control in the drop method. Just call redraw on the control and do the drawing in a paint listener.
Related
I am trying to show an object without tapping on the screen using ARCore. In the basic sample of ARCore Sceneform provided by Google, you need to tap on the screen after it detects the surface.
I want to implement that, AR shows the object without tapping on the screen.
Anchor newAnchor;
for (Plane plane : mSession.getAllTrackables(Plane.class)) {
if (plane.getType() == Plane.Type.HORIZONTAL_UPWARD_FACING
&& plane.getTrackingState() == TrackingState.TRACKING)
{
newAnchor = plane.createAnchor(plane.getCenterPose());
break;
}
}
I tried this for displaying without tapping on the screen.
if Anyone know how to do this please help me. Thanks in Advance
Although I suggest you place the object when a user taps & where s/he taps on the screen, what you're asking can be achieved like so. (this example is in Kotlin)
Before you begin placing an object, you need to create a ModelRenderable. Declare one #Nullable globally.
private var modelRenderable: ModelRenderable? = null
//Create the football renderable
ModelRenderable.builder()
//get the context of the ARFragment and pass the name of your .sfb file
.setSource(fragment.context, Uri.parse("FootBall.sfb"))
.build()
//I accepted the CompletableFuture using Async since I created my model on creation of the activity. You could simply use .thenAccept too.
//Use the returned modelRenderable and save it to a global variable of the same name
.thenAcceptAsync { modelRenderable -> this#MainActivity.modelRenderable = modelRenderable }
The major chunk of the programming has to be done on the frame's onUpdate method. So you attach a listener for frame updates like so
fragment.arSceneView.scene.addOnUpdateListener(this#MainActivity) //You can do this anywhere. I do it on activity creation post inflating the fragment
now you handle adding an object on the listener.
override fun onUpdate(frameTime: FrameTime?) {
//get the frame from the scene for shorthand
val frame = fragment.arSceneView.arFrame
if (frame != null) {
//get the trackables to ensure planes are detected
val var3 = frame.getUpdatedTrackables(Plane::class.java).iterator()
while(var3.hasNext()) {
val plane = var3.next() as Plane
//If a plane has been detected & is being tracked by ARCore
if (plane.trackingState == TrackingState.TRACKING) {
//Hide the plane discovery helper animation
fragment.planeDiscoveryController.hide()
//Get all added anchors to the frame
val iterableAnchor = frame.updatedAnchors.iterator()
//place the first object only if no previous anchors were added
if(!iterableAnchor.hasNext()) {
//Perform a hit test at the center of the screen to place an object without tapping
val hitTest = frame.hitTest(frame.screenCenter().x, frame.screenCenter().y)
//iterate through all hits
val hitTestIterator = hitTest.iterator()
while(hitTestIterator.hasNext()) {
val hitResult = hitTestIterator.next()
//Create an anchor at the plane hit
val modelAnchor = plane.createAnchor(hitResult.hitPose)
//Attach a node to this anchor with the scene as the parent
val anchorNode = AnchorNode(modelAnchor)
anchorNode.setParent(fragment.arSceneView.scene)
//create a new TranformableNode that will carry our object
val transformableNode = TransformableNode(fragment.transformationSystem)
transformableNode.setParent(anchorNode)
transformableNode.renderable = this#MainActivity.modelRenderable
//Alter the real world position to ensure object renders on the table top. Not somewhere inside.
transformableNode.worldPosition = Vector3(modelAnchor.pose.tx(),
modelAnchor.pose.compose(Pose.makeTranslation(0f, 0.05f, 0f)).ty(),
modelAnchor.pose.tz())
}
}
}
}
}
}
I used one extension method
//A method to find the screen center. This is used while placing objects in the scene
private fun Frame.screenCenter(): Vector3 {
val vw = findViewById<View>(android.R.id.content)
return Vector3(vw.width / 2f, vw.height / 2f, 0f)
}
This is the end result
If you don't want to use hit-testing or button's action methods for placing an object in a real environment, you can use, for instance, a camera's Pose for auto-placement (remember, you have to add an ARAnchor, its corresponding Node and a Renderable in front of the ARCamera i.e. along -Z direction):
if (this.anchorNode == null) {
Session session = arFragment.getArSceneView().getSession();
float[] position = { 0, 0, -0.75 }; // 75 cm away from camera
float[] rotation = { 0, 0, 0, 1 };
Anchor anchor = session.createAnchor(new Pose(position, rotation));
anchorNode = new AnchorNode(anchor);
anchorNode.setRenderable(yourModelRenderable);
anchorNode.setParent(arFragment.getArSceneView().getScene());
}
Hope this helps.
Here is the code snippet if you want to place only one object.. Thanks #clinkz
override fun onUpdate(frameTime: FrameTime?) {
arFragment?.let { fragment ->
fragment.arSceneView?.let { sceneView ->
sceneView.arFrame?.let { frame ->
if (!placed) {
val trackable = frame.getUpdatedTrackables(Plane::class.java).iterator()
if (trackable.hasNext()) {
val plane = trackable.next() as Plane
if (plane.trackingState == TrackingState.TRACKING) {
fragment.planeDiscoveryController?.hide()
val hitTest =
frame.hitTest(frame.screenCenter().x, frame.screenCenter().y)
val hitTestIterator = hitTest.iterator()
if (hitTestIterator.hasNext()) {
val hitResult = hitTestIterator.next()
val modelAnchor = plane.createAnchor(hitResult.hitPose)
val anchorNode = AnchorNode(modelAnchor)
anchorNode.setParent(sceneView.scene)
val transformableNode =
TransformableNode(fragment.transformationSystem)
transformableNode.setParent(anchorNode)
transformableNode.renderable = this#ARActivity.modelRenderable
transformableNode.worldPosition = Vector3(
modelAnchor.pose.tx(),
modelAnchor.pose.compose(
Pose.makeTranslation(
0f,
0.05f,
0f
)
).ty(),
modelAnchor.pose.tz()
)
placed = true
}
}
}
}
}
}
}
}
private fun Frame.screenCenter(): Vector3 {
val vw = findViewById<View>(android.R.id.content)
return Vector3(vw.width / 2f, vw.height / 2f, 0f)
}
#FXML
Private void handleItemBackAction(ActionEvent eve)
{
java.awt.Color color=JColorChooser.showDialog(null,"Select a color",java.awt.Color.CYAN);
String hex = Integer.toHexString(color.getRGB() & 0xffffff);
hex="#"+hex;
Text.setText(hex);
ShortcutButton.setStyle("-fx-background-color: " + hex + ";");
}
When I run this window and click on button at first time color chooser goes behind my actual pane.
When I click on button second time while running it shows at top of all other pane which is correct and so on it works properly.
Then why color chooser not shows in front first time on button click?
The first argument to JColorChooser.showDialog is the parent component of the dialog. You told that method to show the dialog with no parent, so it doesn't know about your other windows.
Instead of using JColorChooser.showDialog, you'll need to embed a JColorChooser instance inside a JavaFX dialog or window:
JColorChooser colorChooser = new JColorChooser(java.awt.Color.CYAN);
SwingNode colorChooserNode = new SwingNode();
colorChooserNode.setContent(colorChooser);
Alert dialog = new Alert(Alert.AlertType.NONE);
// Guarantees dialog will be above (and will block input to) mainStage.
dialog.initOwner(mainStage);
dialog.setTitle("Select a color");
dialog.getDialogPane().setContent(colorChooserNode);
dialog.getDialogPane().getButtonTypes().setAll(
ButtonType.OK, ButtonType.CANCEL);
Optional<ButtonType> response = dialog.showAndWait();
if (response.filter(r -> r == ButtonType.OK).isPresent()) {
int rgb = colorChooser.getColor().getRGB();
String hex = String.format("#%06x", rgb & 0xffffff);
Text.setText(hex);
ShortcutButton.setBackground(new Background(
new BackgroundFill(Color.valueOf(hex), null, null)));
} else {
System.out.println("User canceled");
}
Of course, you're probably better off using ColorPicker in your main window, so you don't have to create an explicit dialog at all:
final ColorPicker colorPicker = new ColorPicker(Color.CYAN);
colorPicker.setOnAction(e -> {
Color color = colorPicker.getValue();
String hex = String.format("#%02x02x02x",
(int) (color.getRed() * 255),
(int) (color.getGreen() * 255),
(int) (color.getBlue() * 255));
Text.setText(hex);
ShortcutButton.setBackground(
new Background(new BackgroundFill(color, null, null)));
});
myLayoutPane.getChildren().add(colorPicker);
As an aside, Java variable names should always start with a lowercase letter, to make them easy to distinguish from class names. Consider changing Text to text, and ShortcutButton to shortcutButton.
I am having an issue with using a scrollpane in libgdx. It is going to be used for a chatwindow class. When you press enter the message will be added to the window and you will scroll to the latest posted message..However it doesn't. It misses one message and scrolls to the one before the latest message. Below I've posted the chatwindow class and the method that adds input to it. The textAreaholder is a table that holds everything. The chatField is where you input what you want to post to the chat. The chatarea is the textfield that then becomes added to the table. But as stated..it doesn't scroll properly, the error properly lies somewhere in the keyTyped method.
public ChatWindow(final Pipe<String> chatPipe) {
this.chatPipe = chatPipe;
messageFieldCounter = 0;
white = new BitmapFont(Gdx.files.internal("fonts/ChatWindowText.fnt"), false);
fontSize = white.getLineHeight();
white.scale(TEXT_SCALE);
final TextFilter filter = new TextFilter();
/* Making a textfield style */
textFieldStyle = new TextFieldStyle();
textFieldStyle.fontColor = Color.WHITE;
textFieldStyle.font = white;
textFieldStyle.focusedFontColor = Color.CYAN;
/*Area where all chat appears*/
textAreaHolder = new Table();
textAreaHolder.debug();
/*Applies the scrollpane to the chat area*/
scrollPane = new ScrollPane(textAreaHolder);
scrollPane.setForceScroll(false, true);
scrollPane.setFlickScroll(true);
scrollPane.setOverscroll(false, false);
/*Input chat*/
chatField = new TextField("", textFieldStyle);
chatField.setTextFieldFilter(filter);
/*Tries to make the textField react on enter?*/
chatField.setTextFieldListener(new TextFieldListener() {
#Override
public void keyTyped(final TextField textField, final char key) {
if (key == '\n' || key == '\r') {
if (messageFieldCounter <= 50) {
textAreaHolder.row();
StringBuilder message = new StringBuilder(); //Creates the message
message.append(chatField.getText()); //Appends the chatfield entry
TextArea chatArea = new TextArea(message.toString(), textFieldStyle); //Creates a chatArea with the message
chatArea.setHeight(fontSize + 1);
chatArea.setDisabled(true);
chatArea.setTextFieldFilter(filter);
textAreaHolder.add(chatArea).height(CHAT_INPUT_HEIGHT).width(CHAT_WIDTH);
scrollPane.scrollToCenter(0, 0, 0, 0);
//Scrolls to latest input
chatField.setText("");
//InputDecider.inputDecision(message.toString(), chatPipe); //TODO: Change the filter
//chatPipe.put(message.toString()); //TODO: testing
}
}
}
});
Problems could occur, because you're using scrollPane.scrollToCenter(float x, float y, float width, float height) with zero parameters:
scrollPane.scrollToCenter(0, 0, 0, 0);
scrollToCenter method requires that parameters to be correctly supplied. So, try to supply message bounds.
The second reason could be because you call scrollToCenter before table do layout itself. So, try overwrite table's layout method and call scrollToCenter after:
#Override
public void layout()
{
super.layout();
if (new_messages_added)
{
scrollPane.scrollToCenter(...)
}
}
I have made a Xcode project for a tabbed application that displays images of color swatches in a Scrollview. How do I link One of the images in my scrollview to go to the next View Controller? Below is my code and pictures. So when you click on one of the images or swatch color in the scrollview it links to the New Controller.
I have multiple images that scroll down the page of the iPhone, Do I have to loop the images cause there are 24 images. I was able to make one button and link it to the next scene with the interface builder, But I can fit 5 images on the screen..
DecorsViewController_iPhone.h
#import <UIKit/UIKit.h>
#interface DecorsViewController_iPhone : UIViewController
{
IBOutlet UIScrollView *scrollViewDecors;
}
#property (nonatomic, retain) UIView *scrollViewDecors;
#end
DecorsViewController_iPhone.m
#import "DecorsViewController_iPhone.h"
#interface DecorsViewController_iPhone ()
#end
#implementation DecorsViewController_iPhone
#synthesize scrollViewDecors;
const CGFloat kScrollObjHeight = 81.5;
const CGFloat kScrollObjWidth = 320.0;
const NSUInteger kNumImages = 24;
- (void)layoutScrollImages
{
UIImageView *view = nil;
NSArray *subviews = [scrollViewDecors subviews];
// reposition all image subviews in a horizontal serial fashion
CGFloat curXLoc = 0;
CGFloat curYLoc = 0;
CGFloat curYSpace = 1;
for (view in subviews)
{
if ([view isKindOfClass:[UIImageView class]] && view.tag > 0)
{
CGRect frame = view.frame;
frame.origin = CGPointMake(curXLoc, curYLoc);
view.frame = frame;
curYLoc += (curYSpace + kScrollObjHeight);
}
}
// set the content size so it can be scrollable
[scrollViewDecors setContentSize:CGSizeMake(([scrollViewDecors bounds].size.width), (kNumImages * kScrollObjHeight))]; // Vertical Option
}
- (void)viewDidLoad
{
self.view.backgroundColor = [UIColor viewFlipsideBackgroundColor];
// 1. setup the scrollview for multiple images and add it to the view controller
//
// note: the following can be done in Interface Builder, but we show this in code for clarity
[scrollViewDecors setBackgroundColor:[UIColor blackColor]];
[scrollViewDecors setCanCancelContentTouches:NO];
scrollViewDecors.indicatorStyle = UIScrollViewIndicatorStyleWhite;
scrollViewDecors.clipsToBounds = YES; // default is NO, we want to restrict drawing within our scrollview
scrollViewDecors.scrollEnabled = YES;
// pagingEnabled property default is NO, if set the scroller will stop or snap at each photo
// if you want free-flowing scroll, don't set this property.
// scrollView1.pagingEnabled = YES;
// load all the images from our bundle and add them to the scroll view
NSUInteger i;
for (i = 1; i <= kNumImages; i++)
{
NSString *imageName = [NSString stringWithFormat:#"Artwork_iPhone_Decors_Scrollview_%d.png", i];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
// setup each frame to a default height and width, it will be properly placed when we call "updateScrollList"
CGRect rect = imageView.frame;
rect.size.height = kScrollObjHeight;
rect.size.width = kScrollObjWidth;
imageView.frame = rect;
imageView.tag = i; // tag our images for later use when we place them in serial fashion
[scrollViewDecors addSubview:imageView];
//[imageView release];
}
[self layoutScrollImages]; // now place the photos in serial layout within the scrollview
}
//- (void)dealloc
//{
// [scrollViewDecors release];
//
// [super dealloc];
//}
//- (void)viewDidLoad
//{
// [super viewDidLoad];
// // Do any additional setup after loading the view, typically from a nib.
//}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} else {
return YES;
}
}
#end
Firstly, you need to add a gesture recogniser to your view with something like:
UITapGestureRecognizer *singleTapGestureRecognizer = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:#selector(flipView:)];
[singleTapGestureRecognizer setNumberOfTapsRequired:1];
[self.view addGestureRecognizer:singleTapGestureRecognizer];
You then need to implement the 'flipView' method:
- (void)flipView:(UIPanGestureRecognizer *)recognizer {
[self performSegueWithIdentifier:#"textView" sender:self];
}
As you can see in my case, when the method is triggered I perform a segue (see below):
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"textView"])
{
//---Pass text to view
CGRect visibleRect;
visibleRect.origin = scrollView.contentOffset;
visibleRect.size = scrollView.bounds.size;
int number;
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
number = visibleRect.origin.x / 768;
}
else {
number = visibleRect.origin.x / 320;
}
TextViewController *textViewController = segue.destinationViewController;
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
textViewController.text = [appDelegate.textArray objectAtIndex:number];
}
}
The 'number' variable is used to decide which image has been clicked, I divide the visible rects origin by the width of the screen in pixels to calculate which image has been pressed and therefore what data to send to my new view.
In your case, you would use the Y coordinate to perform a calculation to decide which colour has been pressed, possibly something like:
int number;
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
number = visibleRect.origin.y / <height of each image on iPad in pixels>;
}
else {
number = visibleRect.origin.y / <height of each image on iPhone in pixels>;
}
Alternatively, you could use a UITableView and just populate the cells with the appropriate colour and then display the new view based on which cell was pressed.
EDIT
Use a UITableView, and populate each cell with your image using custom tableview cells. This is a much easier approach than what you are suggesting.
See these links:
adding images to UItableView
If using iOS 5 -
http://kurrytran.blogspot.co.uk/2011/10/ios-5-storyboard-uitableview-tutorial.html
if not -
http://www.iosdevnotes.com/2011/10/uitableview-tutorial/
You are overcomplicating this task massively, follow the above tutorials and you'll be done in no time. If this answer helped you, please mark it as correct.
You can customize your UIImageView. For example, MyImageView. Set its delegate to your main ScrollView and add UITapGestureRecognizer and TapDetecting Delegate methods.
You can implement in the MyImageView:
- (void)handleSingleTap:(UIGestureRecognizer *)gestureRecognizer {
// single tap
if ([_delegate respondsToSelector:#selector(myImageViewWasSingleTapped:)])
[_delegate myImageViewWasSingleTapped:self];
}
then in your main ScrollView(delegate of MyImageView):
- (void)myImageViewWasSingleTapped:(MyImageView *)miv {
AnotherViewController *asv = [[AnotherViewController alloc] initWithImage: miv];
[self.navigationController pushViewController: asv animated:YES];
[asv release];
}
You can use a button instead of a UIImageView, and set the button's image to your image. Your loop in viewDidLoad would be like this:
// load all the images from our bundle and add them to the scroll view
NSUInteger i;
for (i = 1; i <= kNumImages; i++)
{
NSString *imageName = [NSString stringWithFormat:#"Artwork_iPhone_Decors_Scrollview_%d.png", i];
UIImage *image = [UIImage imageNamed:imageName];
UIButton *imageButton = [[UIButton alloc] init];
[imageButton setImage:image forState:UIControlStateNormal];
[imageButton addTarget:self action:#selector(pushNextViewController:) forControlEvents:UIControlEventTouchUpInside];
// setup each frame to a default height and width, it will be properly placed when we call "updateScrollList"
CGRect rect = CGRectMake(0, 0, kScrollObjWidth, kScrollObjHeight);
imageButton.frame = rect;
imageButton.tag = i; // tag our images for later use when we place them in serial fashion
[scrollViewDecors addSubview:imageButton];
// Release imageButton unless you're using ARC
}
And then you'd need to define an action for imageButton, in this case I called it pushNextViewController:
- (void)pushNextViewController:(id)sender
{
UIViewController *yourNextViewController = // initialise your next view controller here
[self.navigationController pushViewController:yourNextViewController animated:YES];
}
My program will alert users when data (stock name & price) in the database matches with the data (stock name and price) from Yahoo Finance. With the help of HarryJoy i'm able to implement a pop up notification.
Problem is the pop up location on the screen is based on the database loop (int db). The frame will pop even if data doesn't match.
How can I set a counter or some method to pop up the frame only when database data = Yahoo Finance data? Also, my notification panels appears to be behind the main frame. How can make the panels appear on top of my main frame?
I hope I've given enough information, please ask if still unclear. Any guidance will be appreciated! Thanks!
In the database (using code sample only to display my explanation in order, source code below).
Object 1 = match
Object 2 = doesn't match (hence there's a gap)
Object 3 = match
Object 4 = match
Screenshot:
Code:
for (int db=0; db<= rowCount; db++)
{
Object popSymbol = table.getModel().getValueAt(db, 0);
String popupSymbol = popSymbol.toString();
Object popValue = table.getModel().getValueAt(db, 1);
String str = popValue.toString();
double popStockValue = Double.valueOf(str).doubleValue();
String stockNameDB = popupSymbol;
StockPara stock = YahooStock.getInstance().getStockPrice(stockNameDB);
double stockPriceDB = Math.round(stock.getPrice());
final JFrame popUpFrame;
final JPanel popupPanel;
if (stockPriceDB == popStockValue)
{
String header = "Stock: " + stock.getTicker() + " is now # " + stock.getPrice();
String message = "";
popUpFrame = new JFrame();
popUpFrame.setSize(320,90);
popUpFrame.setUndecorated(true);
popUpFrame.getContentPane().setLayout(null);
popupPanel = new JPanel();
popupPanel.setBorder(new LineBorder(new Color(0, 0, 0)));
popupPanel.setBounds(0, 0, 320, 90);
getContentPane().add(popupPanel);
popupPanel.setBackground(new Color(255, 255, 224));
popupPanel.setLayout(null);
popUpFrame.add(popupPanel);
// Other labels, images, etc.
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Insets toolHeight = Toolkit.getDefaultToolkit().getScreenInsets(popUpFrame.getGraphicsConfiguration());
popUpFrame.setLocation(screenSize.width - popUpFrame.getWidth(), screenSize.height - toolHeight.bottom - (popUpFrame.getHeight() * (db+1)));
}
}
To solve your issue quickly, simply create an additional counter (int counter = 0;). Then use that counter instead of db to position your popUpFrame and right after that increment counter.
int counter = 0; // Initiate outside de loop
...
for(int db=0; db<= rowCount; db++) {
...
if (stockPriceDB == popStockValue) {
...
popUpFrame.setLocation(screenSize.width - popUpFrame.getWidth(),
screenSize.height - toolHeight.bottom - (popUpFrame.getHeight() * (counter+1)));
counter++;
}
}
To bring your frame to the front use:
popUpFrame.toFront()
and to force it to be always on top (although I would really not recommend that because it is more annoying for the user than anything else):
popUpFrame.setAlwaysOnTop(true);
This is not necessarily supported by all platforms.
for on top issue, use
notificationPanel.requestFocus();