How to Hide a Java application in Mac programatically? - java

i'm making a java application for mac. the application must have the hability of "Auto Hide" equals to "Command+H" shortcut. i'm trying to do it using setVisible(False) in the JFrame. but it doesn't work. how can i do it?
this is may code:
void hide(){
setNormalScreen(); //disable fullscreen mode
//this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setVisible(false);
this.setState(JFrame.ICONIFIED);
}
and this is what i'm getting:

See the below example. You can hide it via Java code using setVisible(false) as you suggested, then appReOpened() event will be called when the user clicks the app in the dock. When this happens, you can just call setVisible(true). This should mimic the Command-H behavior.
See the commented code below also for an uglier solution.
public class Test extends JFrame implements ActionListener, com.apple.eawt.AppReOpenedListener {
public static void main(String[] args) {
Test frame = new Test();
JButton test = new JButton("test");
test.addActionListener(frame);
com.apple.eawt.Application app = com.apple.eawt.Application.getApplication();
app.addAppEventListener(frame);
frame.getContentPane().add(test);
frame.pack();
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent arg0) {
setVisible(false);
// try {
// Robot robot = new Robot();
// robot.keyPress(KeyEvent.VK_META);
// robot.keyPress(KeyEvent.VK_H);
// robot.keyRelease(KeyEvent.VK_H);
// robot.keyRelease(KeyEvent.VK_META);
// } catch (AWTException ex) {
// // TODO Auto-generated catch block
// ex.printStackTrace();
// }
}
#Override
public void appReOpened(AppReOpenedEvent arg0) {
setVisible(true);
}
}

Related

How can I insert a login JFrame into a test in Selenium?

When I call the JFrame from another class to test, the JFrame works, but when I insert it into my Selenium test, the JFrame and the browser open so quickly that there's no time to input anything and the test appears like passed.
Sample of the elements that I mention:
#Test
public void Run() throws InterruptedException{
Keys.loginFrame(); //This method is static in another class named 'Keys'
...
}
Is there any way to say to Selenium the following?:
Execute first ONLY Keys.loginFrame();, then wait till the JFrame is closed. Finally execute the rest of the test code.
Thank you for your answers!
remake your loginFrame() method to return JFrame object
add this method:
public static void startFrameThread(JFrame frame) {
Thread thread = new Thread() {
public void run() {
while (frame.isVisible()) {
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
}
}
}
};
thread.start();
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent arg0) {
frame.setVisible(false);
}
});
try {
thread.join();
} catch (InterruptedException e) {
}
}
apply new usage:
JFrame loginFrame = Keys.loginFrame();
loginFrame.setVisible(true); // if not setting visible in loginFrame() method
startFrameThread(loginFrame);

Restoring JFrame blinks, and set it on top of everything using WindowListener

I know there are already lot of thread available for this topic. I have already visited almost all of em, this one, this one, this one, also this one and this one.But didn't solve my issue.
My problem is different over here when I try to restore the JFrame it blinks, and didn't come on top of everything. I have already run this code in Ubuntu and it worked like a charm on ubuntu. frame.setAlwaysOnTop(true); works absolutely fine on ubuntu.
To solve this issue in windows I tried to use WindowsListener,
But in windows 7 it blinks and didn't come on top of every windows. What I think is that it's trying to come on top of everything but may be other application has higher priority than this it goes away. How can I resolve this issue ?
EDIT :
I have two thread over here one thread is authenticating and if it's authenticated it minimized. If not authenticated it should always be on top for authenticating. Even if user switches window by pressing Alt key tab it should again come on top after 2 seconds.
Code for authentication :
public class ScreenLockAndUnlock implements Runnable{
public static JFrame frame;
public static boolean working = false;
private JTextField punch;
public void stop(){
working = false;
}
public void run(){
try{
frame = new JFrame("Protected");
frame.setContentPane(new JLabel(new ImageIcon("C:\\Users\\four.four-PC\\eclipse-workspace\\optimization\\src\\main\\java\\com\\greycode\\optimization\\finger_PNG6297.png")));
frame.setVisible(true);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gs = ge.getDefaultScreenDevice();
gs.setFullScreenWindow(frame);
frame.validate();
frame.setLayout(new BorderLayout());
punch = new JTextField();
frame.add(punch,BorderLayout.SOUTH);
punch.requestFocus();
punch.addActionListener(action);
}finally{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
private void onTop() throws AWTException{
// TODO Auto-generated method stub
AlwaysOnTop top = new AlwaysOnTop();
new Thread(top).start();
while(true){
try{
frame.setState(Frame.NORMAL);
if(punch.getText().trim()!= null && punch.getText().trim().toLowerCase().equals("true")){
working = true;
top.cancel();
frame.setState(JFrame.ICONIFIED);
Thread.sleep(10000);
top.star();
top = new AlwaysOnTop();
new Thread(top).start();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
#SuppressWarnings("serial")
Action action = new AbstractAction(){
public void actionPerformed(ActionEvent e){
try{
onTop();
} catch (AWTException e1){
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
};
}
This code always look for whether JFrame is on top or not if not authenticated
public class AlwaysOnTop implements Runnable{
boolean cancelled = false;
public void run(){
while(!cancelled){
try{
lookForMinimised();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void cancel(){
this.cancelled = true;
}
public void star(){
this.cancelled = false;
}
public void lookForMinimised() throws InterruptedException{
// TODO Auto-generated method stub
ScreenLockAndUnlock.frame.addWindowStateListener(new WindowStateListener(){
public void windowStateChanged(WindowEvent e){
// TODO Auto-generated method stub
int newState = e.getNewState();
if((newState & Frame.ICONIFIED) == Frame.ICONIFIED){
System.out.println("Frame is minimised");
ScreenLockAndUnlock.frame.setAlwaysOnTop(false);
ScreenLockAndUnlock.frame.setAlwaysOnTop(true);
ScreenLockAndUnlock.frame.setVisible(true);
ScreenLockAndUnlock.frame.toFront();
ScreenLockAndUnlock.frame.requestFocus();
ScreenLockAndUnlock.frame.validate();
ScreenLockAndUnlock.frame.setState(Frame.NORMAL);
}
else if ((newState & Frame.NORMAL) == Frame.NORMAL){
System.out.println("Waiting for authentication ...");
}
}
});
Thread.sleep(2000);
}
}
Main method:
public class Authenticate{
public static void main(String[] args){
Thread displayScreen = new Thread(new ScreenLockAndUnlock());
displayScreen.start();
}
}
Please find a code which depicts the logical functionality that you want.
Also note that this code just depicts the functionality only which are frame restore-minimize, thread and their inter-working.
At the end, it will be you, who have to use the same at appropriate locations as per your need.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Frame;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowStateListener;
public class TestClass2 extends JFrame {
private JPanel contentPane;
private JTextField textField;
static boolean isAuthenticationStarted = false;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestClass2 frame = new TestClass2();
frame.setVisible(true);
frame.addWindowStateListener(new WindowStateListener() {
public void windowStateChanged(WindowEvent e) {
// minimized
if ((e.getNewState() & Frame.ICONIFIED) == Frame.ICONIFIED){
if (!isAuthenticationStarted)
{
// Authentication not started yet and window minimized
frame.setState(Frame.NORMAL);
}
}
// // maximized
// else if ((e.getNewState() & Frame.MAXIMIZED_BOTH) == Frame.MAXIMIZED_BOTH){
//
// }
}
});
frame.setAlwaysOnTop(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TestClass2() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
textField = new JTextField();
textField.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER)
{
new Thread()
{
public void run()
{
// Start authentication here
isAuthenticationStarted = true;
// if authentication is success show next jframe
// else restore window
// reset the flag only when authentication is successful
// isAuthenticationStarted = false;
// Minimizing frame
setState(Frame.ICONIFIED);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// restoring frame
setState(Frame.NORMAL);
}
}.start();
}
}
});// End listener
contentPane.add(textField, BorderLayout.CENTER);
textField.setColumns(10);
}
}
Hope this will help you. :-)

Gui JCombobox Text gets blurred

Recently I have been getting into some Gui programming in Java. I noticed that when I created a JComboBox and tried to display in my gui that the text doesn't come in full. Alot of the time it is blurred, as shown as below. I have tried increasing the size of the GridBagConstraint but it still occurs. This would also happen to the button once I press it as well.
Class 1:
public class load {
private JFrame frame;
public static void main(String args[]) throws InvocationTargetException,
InterruptedException {
EventQueue.invokeAndWait(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(UIManager
.getSystemLookAndFeelClassName());
} catch (Exception ex) {
ex.printStackTrace();
}
// Create the UI here
load window = new load();
window.frame.setVisible(true);
}
});
}
private void loadGui() {
JButton create = new JButton();
create.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
SelectionView a = new SelectionView();
// VVPRIMARY ERROR CURRENTLY VV
// unable to setvisible false without the nextframe losing pixel
frame.setVisible(false);
frame.dispose();
}
});
frame.setSize(400, 400);
frame.add(create);
}
}
Class 2:
public class SelectionView extends JFrame {
public SelectionView() {
// intialize frame
JFrame selection = new JFrame("Sport Selection");
JPanel a = new JPanel();
a.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
selection.setSize(300, 500);
final JComboBox box = createDropdown();
JButton load = new JButton("Load");
load.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
int value = box.getSelectedIndex();
switch (value) {
case 0:
TableTennisView a = new TableTennisView();
break;
case 1:
BasketBallView b = new BasketBallView();
break;
default:
System.out.println("Nothing");
break;
}
}
});
// create comboBox
a.add(box, c);
a.add(load, c);
selection.add(a);
selection.setVisible(true);
}
/**
* Method CreateDropDown
*
* Creates the dropdown menu for the selection view
*
* #return the dropdown menu used in the view
*/
public JComboBox createDropdown() {
String[] sport = { "Table Tennis", "BasketBall" };
JComboBox cb = new JComboBox(sport);
return cb;
}
}
Make sure you are initialise (and updating) the UI from within the context of the Event Dispatching Thread.
See Initial Threads for more details.
EventQueue.invokeAndWait(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
// Create the UI here
}
});
Also, if possible, call setVisible on the window last, after you have established the basic UI. If the UI is dynamic, you will need to call revalidate and repaint on the parent container that you are adding your components to or consider using a CardLayout
Some video drivers can cause problems on some platforms, if problems persist, consider providing a runnable example which demonstrates your problem. This will result in less confusion and better responses

Java - Is it possible to detect when Mouse Button Four or KeyPress anytime?

So I have been trying to figure out some things with Java. I have the click event trigger and print "SUPSUP" in the program when the JFrame window pops up. But I was wondering is there a way to set up the app where if I press button 4 outside the JFrame window the "SUPSUP" will still be printed? I mean I want to have a listener in java in general not tied to the JFrame Components, I wouldn't mind if I needed to use a key listener either. I'm trying to build a program that will do certain things on the screen every time I click on button 4, but I can't be able to click on the blue JFrame thanks.
So Far I have this code.
public class CriticalMassWizard implements MouseListener
{
private static CriticalMassWizard instance = null;
private static Robot robot;
private static boolean triggerSpam;
private static JFrame frame = new JFrame("Tester");
// Singleton
public static CriticalMassWizard getInstance()
{
if(instance == null) {
instance = new CriticalMassWizard();
instance.setUpFrame();
try {
robot = new Robot();
} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return instance;
}
private void setUpFrame()
{
frame.setResizable(true);
frame.setSize(300, 300);
frame.getContentPane().setBackground(Color.BLUE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.addMouseListener(this);
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
if(e.getButton() == 4)
{
System.out.println("SUPSUP");
}
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
Now this is related to FocusListeners and the focus that is set at a point in time at whatever JFrame you are on. It might be possible if you have multiple JFrame's and you click on one of them to output something on another, but if you click on your desktop,for eg, then this cannot be accomplished through native Java Libraries.

Image is not displaying in JFrame

My image was displaying properly before I had a JButton on top of it. Now that I have added a JButton to my code, my image does not display. In the ActionPerformed method I am telling the button to setVisbible(false). When I click the button, it disapears and all that is behind it is the background.
public class Main extends JFrame implements ActionListener {
public static void main(String[] args) {
Main main = new Main();
}
ImageIcon GIF = new ImageIcon("src/Zombie Steve gif.gif");
JButton button = new JButton("Click me!");
JLabel Label = new JLabel(GIF);
public Main() {
button.addActionListener(this);
Label.setHorizontalAlignment(0);
JFrame Frame = new JFrame("zombieSteveGIF");
Frame.setSize(650, 650);
Frame.setVisible(true);
Frame.add(Label);
Frame.add(button);
Frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
while (true) {
Frame.getContentPane().setBackground(Color.BLUE);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Frame.getContentPane().setBackground(Color.GREEN);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Frame.getContentPane().setBackground(Color.RED);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void actionPerformed(ActionEvent e) {
button.setVisible(false);
}
}
Your problem is that you have a BorderLayout (the default for JFrames), and you are adding two components in the same position. The default is BorderLayout.CENTER, and by adding two components with just the default constraints, the first one is removed and the second put in its place.
As for fixing your problem, what do you want to achieve? If you want the components to show on top of one another, you can use the OverlayLayout. If you don't want this, try some other layout manager.

Categories