Disable Ctrl-alt-delete, alt-tab - java

I am creating a LOGIN form that will automatically show up whenever the computer starts up.
I got it right though. My problem is, I have to disable the ALT+TAB and CTRL+ALT+DEL keystrokes when my program is already running. But the thing is, whenever I test my program, my computer gets lag. Especially when I include the method of disabling ALT+TAB.
Somebody HELP!
public void altTab ()
{
try{
Robot robot = new Robot();
while(true){
robot.keyRelease(KeyEvent.VK_ALT);
robot.keyRelease(KeyEvent.VK_TAB);
this.requestFocus(true);
}
}catch(Exception e){
}

You get lag because of having an endless loop running again and again. Try putting an event on Key down and cancel it?(or release it)

You cant disable Alt+Ctrl+Del nor can you call it via your Robot class (using keypress or keyrelease - you can try it). And I don't think the code inside your while loop will run always- you are just releasing the key pressed. I am not sure about this, but you might try event handlers...

Inside that loop, you should call Thread.sleep(). Take a look at this answer, which shares much of the same code you used:
https://stackoverflow.com/a/6128105/2579661

Related

How can you keep a JPanel from closing on System.exit(0)

I have a program that I am terminating with the System.exit(0); command.
When this happens the JPanel closes. I would like it to rename open so I can view the state at termination. Is there a way of keeping the Jpanel open or is there a better command than System.exit()?
not sure why a down vote I asked a simple question and someone answered it. I can't do it that way so try something else. Going to use a true false to test where to enter the simulation loop.
regarding:
Is there a way of keeping the Jpanel open or is there a better command than System.exit()?
The best solution: Don't call System.exit(...). Why? Because System.exit(0) closes the JVM, and so all Java processes running on that JVM will shut down when System.exit(0) is called.
As for "better command", that all depends on your need. If you just want to close a window such as a JDialog, then call myWindow.setVisible(false);. If you want to close it and release resources, then myWindow.dispose();.
Note: I suspect that you might have multiple windows open, perhaps multiple JFrames. If so, I strongly urge you to read: The Use of Multiple JFrames, Good/Bad Practice?
You also posted in comments:
I would like to keep the Jpanel open, but stop the simulation from running. I need to stop the Sim when certain conditions are met. so I wrote a stop()
So your question is in fact an XY Problem where you ask how to solve a specific code problem (keep a JPanel open after calling System.exit(0)) when the best solution is to use a completely different approach. Better that you tell us the overall problem that you're trying to solve rather than how you're currently trying to solve it, because System.exit isn't going to be part of the best solution.
Likely the best solution is to well separate your simulation model from its view (the GUI), to be able to give the model functionality that allows it to stop without closing down the JVM -- impossible for me to say how given our current level of knowledge about your problem -- and then reflect the stopping of the model in the view, again without shutting down the system.
The key to all of this will lie in the details of your current program, including the logic that underpins your simulation, and if you need more specific and likely more helpful answers, you're again going to want to improve your question, providing us with much more specific information about your code, your problem and with posting of pertinent code, preferably as a minimal example program.
Have you tried an approach similar to:
Do something when the close button is clicked on a JFrame
Basically, you're grabbing the Window closing event by setting a listener on the frame
You can then .dispose() the appropriate jpanel/frame if you want
JFrame is window and JPanel is a container. The moment the JPanel instance loses its reference, it will be garbage collected
How can JPanel be disposed after the panel has been removed from the JFrame
Disposing JFrame by clicking from an inner JPanel
import javax.swing.JOptionPane;
/*Some piece of code*/
frame.addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
//delete this code if you want and replace with .dispose() or anything
if (JOptionPane.showConfirmDialog(frame,
"Are you sure to close this window?", "Really Closing?",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION){
//choose to close JVM here if you want
System.exit(0);
}
}
});
Here's a way, by overriding the SecurityManager for the JVM:
//set your security manager
static{
SecurityManager s = new DontCloseOnExitSecurityManager();
System.setSecurityManager(s);
}
static class DontCloseOnExitSecurityManager extends SecurityManager{
public void checkExit(int code){
//here you can put a check to see if you really do want to close - like if the JFrame is still open.
if(/*do some check*/ 13 == code)
super.checkExit(code);
throw new SecurityException("13 is unlucky, you shouldn't system exit on it.");
}
}
}
You'll need to find an appropriate place to put it in, and also how to do your checks (in checkExit).
Apologies for inaccuracies, I'm not in front of an IDE to test this right now.

How to detect the JFrame is closed?

I tried a addWindowListener and implement the windowClosing, it works, when I press the close button, but when I use Cmd+Q to close, the windowClosing is not being called, how can I solve it? Do I need to detect Cmd+Q on mac, Alt + F4 on windows via key listener? Is that a general listener for closing window, whatever via the close button or keyboard, or event Ctrl+Alt+Delete or Cmd+Option+Esc to focus kill? Thanks.
I'm not sure what the situation is on Macs, but on Windows you get the windowClosing() callback from the close button; Alt-F4; and if you close the app via task manager. You don't get the callback if you use task manager to kill the process, but I wouldn't expect that anyway.
You have remembered to call setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); on your JFrame instance, haven't you?
there is one more method windowClosed()
try overriding thing method. hope it will work for you.
You can use this osx library:
com.apple.eawt.ApplicationListener
handleQuit(ApplicationEvent event)
Will probably do the trick.
Information from the docs:
Called when the application is sent the Quit event. This event is generated when the user selects Quit from the application menu, when the user types Command-Q, or when the user control clicks on your application icon in the Dock and chooses Quit. You can either accept or reject the request to quit.
Of course this solution will not work on Windows. As far as I know there is however no universal solution, so this is probably the best way to go.
Sounds like you need to add some KeyListeners and a factory to detect the one you want for a particular operating system.
Check Out
As you said windowClosing is called when you click the (x) button. I am also on a mac and the way I get the CMD+Q to send a signal to the application is using Runtime.addShutDownHook
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
// code to run when CMD+Q is pressed
}
}

Programmatically close Java Tray Balloon

I am using java.awt.SystemTray to create and manage the tray icon and balloon messages. Everything works fine.
But I would like to know whether it is possible to close or fade the message after it is displayed.
Right now, the user needs to click the balloon or close it, otherwise the message will not go away.
I'm not sure about other platforms, but on Windows, the message will only disappear if the machine is in use - i.e. if the user is typing something or moving the mouse. If you don't move the mouse or type anything, the message will stay where it is.
The following code shows a message for me. If I move the mouse, it disappears about 5 seconds later. If I don't, it stays around until such time as I move the mouse or type something, at which point it disappears.
final TrayIcon ti = new TrayIcon(XTPSkin.getInstance().getAppIcon().getImage());
final SystemTray st = SystemTray.getSystemTray();
st.add(ti);
ti.displayMessage("foo", "bar", MessageType.INFO);
There's no direct way to remove the message before its time is up - however, you can remove the TrayIcon (and if necessary immediately re-add it, although this really isn't recommended). Removing the TrayIcon causes the message to also be removed.
The following code, added to the above, causes the TrayIcon and the message to both be removed:
SwingUtilities.invokeLater(new Runnable(){
public void run() {
try {
Thread.sleep(1000); // Don't do this
st.remove(ti);
} catch (InterruptedException ie) {
// You won't need this when the sleep is removed
}
}
});
Notes:
You need to wrap the first block of code above with some exception handling for AWTException
The Thread.sleep in the second block is strictly for demonstration purposes. Since this code will execute on the AWT thread, you should not include that sleep in actual code.
Continually removing and re-adding the TrayIcon in this way is probably a bad idea. Since the message does disappear if the user is using the machine, it's probably wisest not to do this.

Pause execution in Java GUI

I am writing a quiz program for the Android (written in Java). When the user answers a question (by clicking a button), I want to flash a message on the screen saying whether they were correct or not, followed by a 5 second pause before moving on to the next question.
However, when an answer button is clicked, the program pauses, but does not display the message of correct/incorrect. The message only comes up once the sleep method has finished.
if (correct)
Answer.setText("CORRECT!");
else
Answer.setText("WRONG!");
try { Thread.sleep(5000); }
catch(InterruptedException e) {}
As a bonus, I'd like the answer buttons to be disabled during the pause.
You'll need an AsyncTask for that. Google gives you an intro to it here.
When you Thread.sleep() on the main Activity, you are putting the application to sleep. The AsyncTask will allow you to pause for the 5 seconds, maybe show a little In Progress bar and then pick up from there, without freezing the screen.
Imo AsyncTask is too much for this usecase.
Don't use sleep.
Instead set your correct/incorrect message and than do this:
new Handler().postDelayed(new Runnable(){
public void run()
{
goToNextScreen();
}
}
, 5000);
Use a Handler: you can send a message with a 5000 millisecond delay, disable the buttons and when the message arrives you can re-enable the buttons. See http://www.tutorialforandroid.com/2009/01/using-handler-in-android.html for more info.
You should look into using timers for this. I don't think using threads are sensible for this. Using a timer to move onto the next question would work.
Look at timers here
Hope this helps.
Disclaimer: I have only used timers in Java to do something similar but i'm sure it would work in Android.

Running logic in separate thread still locks UI - Java

I have developed a simple MIDI application that allows me to play MIDI notes, in order for the user to be able to interact with the UI whilst the MIDI sounds are playing I have put the logic necessary in an anonymous subclass like so:
public static void Play()
{
new Thread(new Runnable()
{
public void run()
{
if (!_sequencer.isRunning())
{
try
{
_sequencer.setSequence(_sequence);
_sequencer.start();
}
catch (Exception e)
{
Logger.Add(e.getMessage());
}
}
}
}).start();
}
Although the music begins to play the UI still fails to respond when I click on a ComboBox for example, I have something similar working fine in C#.
Is there some sort of caveat to thread in Java that would explain the behaviour i'm seeing?
(The Java API I'm using if it helps - javax.sound.midi)
Thanks for your time.
Edit:
Click around the UI a little more and noticed something interesting; everything seems to work fine with exception to two ComboBoxes in the top left most corner, I've tried deleting them and replacing them but makes no difference. The boxes change to blue when clicked (as it would normally) but the drop down box does not appear below it and the colour does not return to it's default when focus is on another UI component. Could it be a bug introduced by NetBeans perhaps?
Example:
Edit 2:
Well after much trial and error I have finally found the cause of the problem, the threading works great. The problem was that NetBeans has somehow realigned my UI components which causes the Window to fill the screen, manually resizing and testing the ComboBoxes showed that they actually worked fine.
Thanks for everybodys feedback!
What does the combo box do when it's clicked? Does it interact with the _sequencer? Furthermore, was your sequencer created on the UI thread? I would suspect that while you're invoking the start method on a separate thread, the sequencer still runs on the context where it was created (i.e. UI thread).
Try creating the sequencer on the playing thread (i.e. NOT the UI thread) and see if that frees up your UI.
Well after much trial and error I have finally found the cause of the problem, the threading works great. The problem was that NetBeans has somehow realigned my UI components which causes the Window to fill the screen, manually resizing and testing the ComboBoxes showed that they actually worked fine.

Categories