how to popup javafx application? - java

I have a javafx application which represents for the user the rates of currencies.
I want to be able to pop up the application when some trigger happen, even if the user has the application minimized.
For example: suppose the $ currency is hitting a target of 1$ = 0.86€, I want to alert the user, even if he has the application minimized on his screen, and bring it to the front.
Is that possible?

I think you should use setIconified, setX and setY methods from Stage and put it into a thread. Check this:
while(alive){
if(##YOUR STATEMENT##){
Rectangle2D screenBounds = Screen.getPrimary().getBounds();
primaryStage.setX((screenBounds.getMaxX() - primaryStage.getWidth()) / 2);
primaryStage.setY((screenBounds.getMaxY() - primaryStage.getHeight()) / 2);
primaryStage.setIconified(false);
primaryStage.setAlwaysOnTop(true);
}
try {
Thread.sleep(CHECK_INTERVAL);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
This will show your window exactly at the center of the screen.

Related

Java application - swing - pop up on right click changes background colour

I am having issues with my java application and I can't find a suitable reply.
In summary a right click triggered default pop up menu changes my chart's background color behind the pop up.
You can find images below. I am happy to keep the default popup without the "buggy" behaviour or develop my own if required.
A click of a button starts a stream of data and adds a chart to a JInternalFrame component:
If I right click on the image a default pop up comes up:
If I then click away the rectangle area covered by the popup will overlay the chart like this:
TimeseriesMonitorModel model = new DefaultTweetMonitorModel();
jif.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
try {
jif.setContentPane(new TweetSeriesChartPane(model, TweetMonitor.keywords, tkc));
jif.setSize(jif.getWidth(), jif.getHeight());
} catch (InterruptedException ex) {
Logger.getLogger(TweetMonitor.class.getName()).log(Level.SEVERE, null, ex);
}
jif.setVisible(true);
where jif is the Jinternalframe and
public TweetSeriesChartPane(TimeseriesMonitorModel model, String[] seriesNames, TweetKeywordCount tkc) throws InterruptedException {
this.seriesNames = seriesNames;
this.tkc = tkc;
this.model = model;
XYChartTimeseries myRealTimeChart = new XYChartTimeseries();
chart = myRealTimeChart.getChartWithTitle();
List[] tweetData = model.getFrequencyCount(new AtomicIntegerArray(seriesNames.length)); // we are starting from 0
int i = 0;
for (String keyword : seriesNames) {
List<Integer> yData = (List<Integer>) tweetData[1].get(i);
chart.addSeries(keyword, tweetData[0], yData); // adding first value
i++;
}
setLayout(new BorderLayout());
XChartPanel<XYChart> chartPane = new XChartPanel<>(chart);
add(chartPane);
UpdateWorker worker = new UpdateWorker(this, seriesNames, this.tkc);
worker.execute();
}
I've managed to temporary solve the above.
I've checked specifically this line of code
XChartPanel<XYChart> chartPane = new XChartPanel<>(chart);
which extends Chart and Jpanel. The code is from the knowm-chart dependency https://github.com/knowm/XChart/blob/develop/xchart/src/main/java/org/knowm/xchart/XChartPanel.java)
Apparently it adds a listener and the customized PopUpMenu. After reviewing it, it looks like it didn't do any repainting when the mouse was clicked outside the PopUpMenu area.
So I created a new class and tried to customise it. However, the repaint was flickering the screen and I couldn't get it to work only in the PopUpMenu area.
I ended up disabling the .addMouseListener call so now I don't get any popUpMenu. I sad compromise, but oh well.
BTW:
Thanks to both, regardless of the last unneeded comment which didn't add any value.
I did read the link and I though I provided enough information.
In any case, posting to code helped me troubleshoot it

Making a program wait until a button is clicked

I have a problem that probably has a simple fix but I can't seem to get it to work.
I need my program to pause or wait until the user selects either the skip button, or the positive/negative feedback button, before moving on.
I assume this is going to require basic threading, but I'm not sure how to implement it. Any help will be appreacited.
The gui is displayed in a separate class(GUI) and the rest is another class.
The code is sort of messy as it was coded for a Hackfest in 12 hours.
EDIT: Solved it on my own by removing button listeneers and making the variables static.
public void onStatus(Status status) {
//this is a listener from the Twitter4J class. Every time new Tweet comes in it updates.
for (int i = 0; i <= posWords.length; i++) {
if (status.getText().toLowerCase().contains(gui.sCrit.getText())
&& (status.getText().toLowerCase().contains(posWords[i].toLowerCase()))) {
//If the tweet matches this criteria do the following:
String tweet;
Status tempStoreP;
System.out.println("Flagged positive because of " +posWords[i].toLowerCase()+" " + i);
tempStoreP = status;
tweet = tempStoreP.getUser().getName() + ":" + tempStoreP.getText() + " | Flagged as positive \n\r";
gui.cTweet.setText(tweet);
//Write to log
try {
wPLog.append("~" + tweet);
} catch (IOException e) {
}
//Add action listeneer to gTweet.
//here is my problem. I want it to wait until a user has clicked one of these buttons before moving on and getting the next Tweet. It has to pause the thread until a button is clicked then it can only move on to getting another Tweet.
//the problem is that the button listener uses local variables to work.
gui.gTweet.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (gui.pTweet.getText().equalsIgnoreCase("")) {
gui.pTweet.setText("Please type a response");
} else if (gui.pTweet.getText().equalsIgnoreCase("Please type a response")) {
gui.pTweet.setText("Please type a response");
} else {
try {
Status sendPTweet = twitter
.updateStatus("#" + tempStoreP.getUser().getScreenName() + " "
+ gui.pTweet.getText());
} catch (TwitterException e1) {
}
}
gui.gTweet.removeActionListener(this);
}
});
//add Aaction listert to sTweet
gui.sTweet.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
wPLog.append("Skipped \n\r");
} catch (IOException e1) {
}
gui.sTweet.removeActionListener(this);
}
});
}
Thank you for any help. On a side note, if anyone can tell me why when the button is clicked, it loops and spams people with the same message, it will be helpful. Thank you.
I thought about the multithreading thing and i think it isn't easy enough.
If i were you i would disable all controls except the button that is to click.
Example:
JButton button = new JButton( "Test );
button.setEnabled( false );
The user won't be able to click the button until you use button.setEnabled( true );, if you just disable all controls but the button that should be fine.
In my understand of your problem you can use Multithreading like this:
try{
while(!isSkipClicked){
//your multithreading code
}
//code to move...
}
or
you can use dispose method if you have 2 JFrame.
or
you can use multiple JPanel like while skip button clicked hide pnl1 and show pnl2 using method
pnl1.setvisible(false);
pbl2.setVisible(true);
I assume this is going to require basic threading,
Not true at all.
You say you want your program to "wait." That word doesn't actually mean much to a Swing application. A Swing application is event driven. That is to say, your program mostly consists of event handlers that are called by Swing's top-level loop (a.k.a., the Event Dispatch Thread or EDT) in response to various things happening such as mouse clicks, keyboard events, timers, ...
In an event driven program, "Wait until X" mostly means to disable something, and then re-enable it in the X handler.
Of course, Swing programs sometimes create other threads to handle input from sources that the GUI framework does not know about and, to perform "background" calculations. In that case, "Wait until X" might mean to signal some thread to pause, and then signal it to continue its work in the X handler.

java - Detect Mouse Clicks Anywhere On Screen

I want my app to detect mouse clicks anywhere on the screen without having to have the app focused. I want it to detect mouse events universally even if its minimized. So far I've only been able to detect mouse events within a swing gui.
Autohotkey can detect mouse clicks and get the mouse's position at any time, how can I do this with java?
It is possible with a little trick. Should be 100% cross-platform (tested on Linux & Windows). Basically, you create a small JWindow, make it "alwaysOnTop" and move it around with the mouse using a timer.
Then, you can record the click, dismiss the window and forward the click to the actual receiver using the Robot class.
Short left and right clicks work completely fine in my tests.
You could also simulate dragging and click-and-hold, just forwarding that seems harder.
I have code for this, but it is in my Java extension (JavaX). JavaX does translate into Java source code, so you can check out the example here.
The code in JavaX:
static int windowSize = 11; // odd should look nice. Set to 1 for an invisible window
static int clickDelay = 0; // Delay in ms between closing window and forwarding click. 0 seems to work fine.
static int trackingSpeed = 10; // How often to move the window (ms)
p {
final new JWindow window;
window.setSize(windowSize, windowSize);
window.setVisible(true);
window.setAlwaysOnTop(true);
JPanel panel = singleColorPanel(Color.red);
window.setContentPane(panel);
revalidate(window);
final new Robot robot;
panel.addMouseListener(new MouseAdapter {
// public void mousePressed(final MouseEvent e) {}
public void mouseReleased(final MouseEvent e) {
print("release! " + e);
window.setVisible(false);
int b = e.getButton();
final int mod =
b == 1 ? InputEvent.BUTTON1_DOWN_MASK
: b == 2 ? InputEvent.BUTTON2_DOWN_MASK
: InputEvent.BUTTON3_DOWN_MASK;
swingLater(clickDelay, r {
print("clicking " + mod);
robot.mousePress(mod);
robot.mouseRelease(mod);
});
}
});
swingEvery(window, trackingSpeed, r {
Point p = getMouseLocation();
window.setLocation(p.x-windowSize/2, p.y-windowSize/2);
//print("moving");
});
}

Simulate a MouseEvent

I'd like to simulate a Mouse click on a Graphic. I added a Mouselistener, and some action when the mouseclick is done, but I really need to simulate that the user clicked on my Graphic in my programm... How can I say something like "" MouseEvent e is performed!"" ?
Actually I'd like to clean a "Graphics 2D canvas" when you click on a Jbutton called "Clean". But the thing is that the cleaning action would be done only if the user click on my "Graphics 2D canvas". I'd like to make the illusion that the "Graphics 2D canvas" was cleaned by clicking on the JButton..
Thanks.
addMouseListener(this);
addMouseMotionListener(this);
public void mousePressed(MouseEvent e) {
e.consume();
x1=e.getX();
y1=e.getY();
if(figure==1 || figure==3 ) {x2=x1; y2=y1;}
; }
PS : I can't use robot because I have to run my programm on every OS, and someone told me I can't run this on every programm :
Robot robot = null;
try {
robot = new Robot();
} catch (AWTException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// SET THE MOUSE X Y POSITION
robot.mouseMove(65*Fond_noir.pourcent_largeur, 16*Fond_noir.pourcent_hauteur);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
}
Well, you're right about Robot. It's platform dependent, and there are no guarantees that it will support all features on all platforms, from the JavaDoc:
Note that some platforms require special privileges or extensions to
access low-level input control. If the current platform configuration
does not allow input control, an AWTException will be thrown when
trying to construct Robot objects. For example, X-Window systems will
throw the exception if the XTEST 2.2 standard extension is not
supported (or not enabled) by the X server.
To simulate the click, you can simply do this:
JButton buttonToSimulateClicking = new JButton(...);
buttonToSimulateClicking.doClick(); // As simple as that !
If you have to simulate the click "the hard way", i.e. to simulate a mouse click, you can always do the following:
MouseEvent clickEvent = new MouseEvent(buttonToSimulateClicking, MouseEvent.MOUSE_CLICKED, ...);
EventQueue eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue();
eventQueue.dispatchEvent(clickEvent);

How do I set the position of the mouse in Java?

I'm doing some Swing GUI work with Java, and I think my question is fairly straightforward; How does one set the position of the mouse?
As others have said, this can be achieved using Robot.mouseMove(x,y). However this solution has a downfall when working in a multi-monitor situation, as the robot works with the coordinate system of the primary screen, unless you specify otherwise.
Here is a solution that allows you to pass any point based global screen coordinates:
public void moveMouse(Point p) {
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
// Search the devices for the one that draws the specified point.
for (GraphicsDevice device: gs) {
GraphicsConfiguration[] configurations =
device.getConfigurations();
for (GraphicsConfiguration config: configurations) {
Rectangle bounds = config.getBounds();
if(bounds.contains(p)) {
// Set point to screen coordinates.
Point b = bounds.getLocation();
Point s = new Point(p.x - b.x, p.y - b.y);
try {
Robot r = new Robot(device);
r.mouseMove(s.x, s.y);
} catch (AWTException e) {
e.printStackTrace();
}
return;
}
}
}
// Couldn't move to the point, it may be off screen.
return;
}
You need to use Robot
This class is used to generate native system input events for the purposes of test automation, self-running demos, and other applications where control of the mouse and keyboard is needed. The primary purpose of Robot is to facilitate automated testing of Java platform implementations.
Using the class to generate input events differs from posting events to the AWT event queue or AWT components in that the events are generated in the platform's native input queue. For example, Robot.mouseMove will actually move the mouse cursor instead of just generating mouse move events...
Robot.mouseMove(x,y)
Check out the Robot class.
The code itself is the following:
char escCode = 0x1B;
System.out.print(String.format("%c[%d;%df",escCode,row,column));
This code is incomplete by itself, so I recommend placing it in a method and calling it something like 'positionCursor(int row, int column)'.
Here is the code in full (method and code):
void positionCursor(int row, int column) {
char escCode = 0x1B;
System.out.print(String.format("%c[%d;%df",escCode,row,column));
}

Categories

Resources