I've been trying and failing to use the java full screen mode on the primary display of an OSX system. Whatever I've tried I can't seem to get rid of the 'apple' menu bar from the top of the display. I really need to paint over the entire screen. Can anyone tell me how to get rid of the menu?
I've attached an example class which exhibits the problem - on my system the menu is still visible where I would expect to see a completely blank screen.
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
public class FullScreenFrame extends JFrame implements KeyListener {
public FullScreenFrame () {
addKeyListener(this);
setUndecorated(true);
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
if (gd.isFullScreenSupported()) {
try {
gd.setFullScreenWindow(this);
}
finally {
gd.setFullScreenWindow(null);
}
}
else {
System.err.println("Full screen not supported");
}
setVisible(true);
}
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e) {}
public void keyReleased(KeyEvent e) {
setVisible(false);
dispose();
}
public static void main (String [] args) {
new FullScreenFrame();
}
}
I think your problem is here:
try {
gd.setFullScreenWindow(this);
}
finally {
gd.setFullScreenWindow(null);
}
finally blocks are always executed, so what happens here is that you window becomes full screen for a brief instant (if that) and then relinquishes the screen immediately.
Also, setVisible(true) is not necessary when you have previously called setFullScreenWindow(this), according to the Javadocs.
So I would change the constructor to this:
public FullScreenFrame() {
addKeyListener(this);
GraphicsDevice gd =
GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
if (gd.isFullScreenSupported()) {
setUndecorated(true);
gd.setFullScreenWindow(this);
} else {
System.err.println("Full screen not supported");
setSize(100, 100); // just something to let you see the window
setVisible(true);
}
}
On OS X (10.7 and higher), it is better to use the native fullscreen mode available. You should use:
com.apple.eawt.FullScreenUtilities.setWindowCanFullScreen(window,true);
com.apple.eawt.Application.getApplication().requestToggleFullScreen(window);
where window is the window (JFrame, etc) that you want to take fullscreen
Thats a bit pedantic, the answer is to follow the tutorial completely, which has the essentials and is somewhat more expansive than would fit in a post. The above sample does not work because it is missing a validate(); and some content. I suspect the Java Tutorial will not disappear any time soon. Below is a modified version
package test;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class FullScreenFrame extends JFrame implements KeyListener {
public FullScreenFrame () {
addKeyListener(this);
setUndecorated(true);
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
if (gd.isFullScreenSupported()) {
try {
this.getContentPane().addKeyListener(this);
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add("Center", new JLabel("Full Screen, back to normal in 10 seconds"));
gd.setFullScreenWindow(this);
validate();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} finally {
gd.setFullScreenWindow(null);
}
} else {
System.err.println("Full screen not supported");
}
}
public void keyTyped(KeyEvent e) {
System.out.println("keyTyped:" + e.getKeyChar() + "source:" + e.getSource() );
}
public void keyPressed(KeyEvent e) {
System.out.println("keyPressed:" + e.getKeyChar() + "source:" + e.getSource() );
}
public void keyReleased(KeyEvent e) {
System.out.println("keyReleased:" + e.getKeyChar() + "source:" + e.getSource() );
setVisible(false);
dispose();
}
public static void main (String [] args) {
new FullScreenFrame();
}
}
Related
So, I'm fairly new to programming and I like to fiddle with it and one day my friend asked me to make a program where when you click, "ctrl" and "s" would be "pressed". I looked at lots of forums trying to make a functional code but, since I'm new to Java, I only got separate pieces of codes and threw it all together.
My code looks like this:
import java.awt.event.MouseEvent;
import java.awt.*;
import java.awt.event.*;
import java.awt.Robot;
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
System.out.println("press any key to exit.");
keyboard.next();
System.exit(0);
}
public void mouseClicked(MouseEvent evt) {
try {
Robot robot = new Robot();
// Simulate a key press
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_CONTROL);
} catch (AWTException e) {
}
}
}
Your program has no GUI and, therefore, nothing to invoke your mouse listener. The code within the listener appears correct, all you need to do is search for how to create a basic GUI and add the mouse listener to it so you get the results you want.
The following code may help you to handle Ctrl + S
public class SwingApp1 extends JFrame implements KeyListener {
public SwingApp1() {
setSize(500, 500);
setLocationRelativeTo(null);
setBackground(Color.blue);
addKeyListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingApp1 main = new SwingApp1();
main.setVisible(true);
}
#Override
public void keyTyped(KeyEvent evt) {
}
#Override
public void keyPressed(KeyEvent e) {
System.out.println("Pressed=>" + e.getKeyCode());
if (e.getKeyCode() == 83) {
System.out.println("Pressed Ctrl + S");
} // Ctrl + S
}
#Override
public void keyReleased(KeyEvent e) {
}}
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. :-)
When opening a file in a JTree, the tree's preferred size changes but his propertyChangeListener doesn't detect it (but if you change it calling setPreferredSize is able to detect it). Is it my code that is wrong or is javax.swing bugged? If this isn't the way of doing this how should I do it. I tested the code with maximumSize as well.
Here is my code, you shouldn't need any external resources:
import javax.swing.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
public class MyJFrame extends JFrame
{
public MyJFrame()
{
add(new JTree()
{
{
addPropertyChangeListener("preferredSize",
new PropertyChangeListener()
{
public void propertyChange(PropertyChangeEvent evt)
{
System.out.println("preferred size changed");
}
});
new Thread()
{
public void run()
{
while(true)
{
System.out.println("preferred size = "+getPreferredSize());
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
}
}
}.start();
}
});
pack();
setVisible(true);
}
public static void main(String[] args)
{
new MyJFrame();
}
}
I need to take a screenshot of an area of my screen, to make that i use "Robot" in Java. But if the user place the windows in the area, the windows will be on the screenshot instead of the background.
I tried to solve my problem by placing a :
myframe.setVisible(false);
But when i look the screenshot the windows appear on it. I thought it was because the windows didn't have enough time to disappear or because the render of the screen wasn't updated yet, so i tried different things like using:
repaint();
Or by placing a
try{}finally{}
block to be sure that the actions in the try block have been finished.
But no one of these solution works. These is other ways in my mind but they looks globally bad because they use functions to wait.
So is there a good solution to my problem?
You could use window listener to fire the screen shot when window is closing:
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class MainFrame extends JFrame implements WindowListener {
public MainFrame() {
super("Test Frame");
JLabel displayMsg = new JLabel(" Close window");
getContentPane().add(displayMsg);
addWindowListener(this);
setSize(400, 300);
setVisible(true);
}
#Override
public void windowClosing(WindowEvent e) {
System.out.println("WindowListener method called: windowClosing.");
//add you screen capture code here
}
//--Not used
#Override
public void windowClosed(WindowEvent e) {
//do nothing
}
#Override
public void windowOpened(WindowEvent e) {
//do nothing
}
#Override
public void windowIconified(WindowEvent e) {
//do nothing
}
#Override
public void windowDeiconified(WindowEvent e) {
//do nothing
}
#Override
public void windowActivated(WindowEvent e) {
//do nothing
}
#Override
public void windowDeactivated(WindowEvent e) {
//do nothing
}
public void windowGainedFocus(WindowEvent e) {
//do nothing
}
public void windowLostFocus(WindowEvent e) {
//do nothing
}
public static void main(String[] args) {
new MainFrame();
}
}
Use SwingUtilities.invokeLater() to take the actual screenshot. Not 100% sure, but I think that myframe.setVisible(false); doesn't become effective till the program flow goes back to the event dispatching loop.
EDIT:
instead of
useRobotToMakeScreenshot();
write
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
useRobotToMakeScreenshot();
}
}
(of course, you have to replace useRobotToMakeScreenshot() with the actual call to the method that does the screenshooting thing)
I had posted this in a wrong place (GameDev) and got no response there. So I'm posting it again here.
I'm making an applet game and it is rendering, the game loop is running, the animations are updating, but the keyboard input is not working. Here's an SSCCE.
public class Game extends JApplet implements Runnable {
public void init(){
// Initialize the game when called by browser
setFocusable(true);
requestFocus();
requestFocusInWindow(); // Always returning false
GInput.install(this); // Install the input manager for this class
new Thread(this).start();
}
public void run(){
startGameLoop();
}
}
And Here's the GInput class.
public class GInput implements KeyListener {
public static void install(Component c){
new GInput(c);
}
public GInput(Component c){
c.addKeyListener(this);
}
public void keyPressed(KeyEvent e){
System.out.println("A key has been pressed");
}
......
}
This is my GInput class. When run as an applet, it doesn't work and when I add the Game class to a frame, it works properly.
Thanks
Solved now. See my solution
One possible solution is to use the JApplet's contentPane, to set the focus on it rather than on the JApplet itself. But my preference is to use Key Bindings instead. You may need to use a Swing Timer for this to work:
My SSCCE:
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.InvocationTargetException;
import javax.swing.*;
#SuppressWarnings("serial")
public class AppletKeyListen extends JApplet {
#Override
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
setFocusable(true);
int timerDelay = 100;
Timer myTimer = new Timer(timerDelay , new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
boolean focusObtained = requestFocusInWindow();
System.out.println("focusObtained for JApplet: " + focusObtained);
Container contentPane = getContentPane();
contentPane.setFocusable(true);
focusObtained = contentPane.requestFocusInWindow();
System.out.println("focusObtained for contentPane: " + focusObtained);
}
});
myTimer.setRepeats(false);
myTimer.start();
// boolean focusObtained = requestFocusInWindow();
// System.out.println("focusObtained: " + focusObtained);
//
// Container contentPane = getContentPane();
// contentPane.setFocusable(true);
//
// focusObtained = contentPane.requestFocusInWindow();
// System.out.println("focusObtained: " + focusObtained);
}
});
} catch (InvocationTargetException | InterruptedException e) {
e.printStackTrace();
}
}
}
If you're running in a browser, you probably need to click on the applet to give it focus. For security reasons most browsers won't let an applet just grab the keyboard focus without the user clicking it.
So, I would add a mouse listener instead of doing the focus grabbing directly in init():
addMouseListener(new MouseAdapter() {
public void onMousePress(MouseEvent e) {
requestFocus();
}
});
Now that I have two options,
Use JWS
Don't make an applet mode
Now I had tried to make a new class called GApplet. It loads a game into a new JFrame which worked from the applet. Now I can access the fullscreen mode from web too. Here's a link to the class.
The GApplet class
And now it's working like the webstart and is actually an applet.