I am writing a very simple full screen GUI, but I keep receiving an error. Here is the code:
package me.Kenny.GUI_WINDOW_INITILIZATION;
import java.awt.*;
import javax.swing.*;
public class Main extends JFrame {
public static void main(String[] args) {
DisplayMode dm = new DisplayMode(1200,800,32,DisplayMode.REFRESH_RATE_UNKNOWN);
Main m = new Main();
m.run(dm);
}
public void run(DisplayMode dm1) {
setBackground(Color.PINK);
setForeground(Color.WHITE);
setFont(new Font("Arial", Font.PLAIN, 24));
Screen s = new Screen();
try {
s.setFullScreen(dm1, this);
try {
Thread.sleep(5000);
} catch(Exception e){}
} finally {
s.restoreScreen();
}
}
public void paint(Graphics g) {
g.drawString("This is gonna be awesome", 300, 300);
}
}
That was the main program. The Screen class is here:
package me.Kenny.GUI_WINDOW_INITILIZATION;
import java.awt.*;
import javax.swing.*;
public class Screen {
private GraphicsDevice vc;
public Screen() {
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
vc = env.getDefaultScreenDevice();
}
public void setFullScreen(DisplayMode dm, JFrame window) {
window.setUndecorated(true);
window.setResizable(false);
vc.setFullScreenWindow(window);
if(dm != null && vc.isDisplayChangeSupported()) {
try {
vc.setDisplayMode(dm);
System.out.println("is in try");
} catch(IllegalArgumentException ex) {
System.out.println("Unable to set Display mode");
}
}
}
public Window getFullScreenWindow() {
return vc.getFullScreenWindow();
}
public void restoreScreen() {
Window w = vc.getFullScreenWindow();
if (w != null) {
w.dispose();
}
vc.setFullScreenWindow(null); //closes window
}
}
In the try/catch statement of setFullScreen, I keep getting an IllegalArgument exception whenever I try to set vc to the parameters of dm. I checked both if statement conditions to ensure they were true, and my initilization of dm appears to have the proper parameters. Every time I try running the
program hoever, I activate the catch statement, which prints "unable to set Display Mode" on the console. Is there something I am missing in my code?
Thanks
Related
I have written this code for a simple music player, the problem is that when I click openLabel and open a song and then when I pause it by clicking playLabel the program stops execution (program hangs).
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.util.Random;
import javax.sound.sampled.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.filechooser.FileNameExtensionFilter;
public class A extends MouseAdapter implements ChangeListener, Runnable {
private ImageIcon playImage = new ImageIcon(getClass().getResource("Images/play.png"));
private ImageIcon pauseImage = new ImageIcon(getClass().getResource("Images/pause.png"));
private ImageIcon openImage = new ImageIcon(getClass().getResource("Images/open.png"));
private JLabel playLabel = new JLabel(playImage);
private JLabel openLabel = new JLabel(openImage);
public JFrame frame = new JFrame();
public JPanel colorPanel = new JPanel();
private enum Status {ON,OFF,PAUSE,END};
private Status playStatus=Status.OFF;
private JSlider slider = new JSlider();
public Clip songClip;
Thread screenThread = new Thread(this);
public static void main(String arg[]) throws Exception {
new A();
}
public A() throws Exception {
setFrame();
setComponents();
}
public void setFrame() {
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setUndecorated(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setCursor(new Cursor(Cursor.HAND_CURSOR));
frame.getContentPane().setBackground(Color.BLACK);
frame.setVisible(true);
}
public void setComponents() {
slider.setBounds(0,640,1000,15);
slider.setBackground(Color.BLACK);
slider.addChangeListener(this);
slider.setValue(0);
playLabel.setBounds(450,665,100,100);
playLabel.addMouseListener(this);
openLabel.setBounds(540,690,60,60);
openLabel.addMouseListener(this);
colorPanel.setBackground(Color.BLACK);
colorPanel.setBounds(0,100,1500,500);
frame.add(openLabel);
frame.add(playLabel);
frame.add(colorPanel);
frame.add(slider);
}
public void mouseClicked(MouseEvent clicked) {
if (clicked.getSource() == openLabel) {
openLabel.setIcon(openImage);
open();
}
else if (clicked.getSource()==playLabel && playStatus != Status.OFF) {
if (playStatus == Status.PAUSE) {
songClip.start();
screenThread.resume();
playStatus=Status.ON;
playLabel.setIcon(pauseImage);
}
else if (playStatus == Status.ON) {
songClip.stop();
screenThread.suspend();
playStatus=Status.PAUSE;
playLabel.setIcon(playImage);
}
else if (playStatus==Status.END) {
songClip.setMicrosecondPosition(0);
slider.setValue(0);
songClip.start();
screenThread.resume();
playStatus = Status.ON;
playLabel.setIcon(pauseImage);
}
}
}
public void stateChanged(ChangeEvent e) {
if (playStatus != Status.OFF) {
JSlider jslider = (JSlider)e.getSource();
int position = jslider.getValue();
songClip.setMicrosecondPosition(position * 1000000);
}
}
public void open() {
JFileChooser chooseSong = new JFileChooser();
chooseSong.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooseSong.setFileFilter(new FileNameExtensionFilter(null, "wav"));
int chooseButton = chooseSong.showOpenDialog(null);
File songPath = chooseSong.getSelectedFile();
if ( (chooseButton!=JFileChooser.CANCEL_OPTION) && (songPath!=null) && (songPath.getName() != null) ) {
try {
playLabel.setIcon(pauseImage);
if (playStatus != Status.OFF)
songClip.close();
AudioInputStream songFile = AudioSystem.getAudioInputStream(songPath);
songClip = AudioSystem.getClip();
songClip.open(songFile);
int clipLength = (int)(songClip.getMicrosecondLength() / 1000000);
slider.setMinimum(0);
slider.setMaximum(clipLength);
songClip.start();
if (playStatus == Status.OFF)
screenThread.start();
else if (playStatus != Status.OFF)
screenThread.resume();
playStatus=Status.ON;
}
catch(Exception exp) {
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(null, String.format("ERROR = %s",exp.getClass()));
System.exit(0);
}
}
}
public void run() {
while (true) {
colorPanel.setBackground(new Color(new Random().nextInt(256), new Random().nextInt(256), new Random().nextInt(256)));
if (songClip.getMicrosecondPosition() == songClip.getMicrosecondLength()) {
screenThread.suspend();
playStatus=Status.END;
playLabel.setIcon(playImage);
}
}
}
}
This method has been deprecated, as it is inherently deadlock-prone.
This is the reason that is given for the deprecation of Thread.stop(), .suspend() and .resume(). As you are using these in your code it could be the problem.
You are calling screenThread.suspend(); in the block that responds to clicking the play/pause button. Thread methods suspend() and resume() are deadlock prone - that is, using them often causes hard-to-diagnose issues like the one you're having.
You need to remove the use of these methods by instead polling a variable, as described on this page.
I am trying to implement splash screen followed my main activity. Code below is what I have manged to do so far. And I am not able to get my splash screen working. Please help.
On running the the file its showing SplashScreen.getSplashScreen() returned null.What to do ?
SplashDemo.java
public class SplashDemo extends Frame implements ActionListener {
static void renderSplashFrame(Graphics2D g, int frame) {
final String[] comps = {"foo", "bar", "baz"};
g.setComposite(AlphaComposite.Clear);
g.fillRect(120,140,200,40);
g.setPaintMode();
g.setColor(Color.BLACK);
g.drawString("Loading "+comps[(frame/5)%3]+"...", 120, 150);
}
public SplashDemo() {
super("SplashScreen demo");
setSize(300, 200);
setLayout(new BorderLayout());
Menu m1 = new Menu("File");
MenuItem mi1 = new MenuItem("Exit");
m1.add(mi1);
mi1.addActionListener(this);
this.addWindowListener(closeWindow);
MenuBar mb = new MenuBar();
setMenuBar(mb);
mb.add(m1);
final SplashScreen splash = SplashScreen.getSplashScreen();
if (splash == null) {
System.out.println("SplashScreen.getSplashScreen() returned null");
return;
}
Graphics2D g = splash.createGraphics();
if (g == null) {
System.out.println("g is null");
return;
}
for(int i=0; i<100; i++) {
renderSplashFrame(g, i);
splash.update();
try {
Thread.sleep(90);
}
catch(InterruptedException e) {
}
}
splash.close();
setVisible(true);
toFront();
}
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
private static WindowListener closeWindow = new WindowAdapter(){
public void windowClosing(WindowEvent e){
e.getWindow().dispose();
}
};
public static void main (String args[]) {
SplashDemo test = new SplashDemo();
}
}
Create your splash screen image, say MySplashyScreen.gif, and put it in a directory called images (or wherever you like).
Then on startup use this command line:
java -splash:images/MySplashyScreen.gif SplashDemo
Is it possible to disable the drop shadow of a Java AWT application on OS X?
I want to create a transparent window, which works fine, but I cannot get rid of the drop shadow.
If I was using a JFrame this could be done using:
JRootPane root = frame.getRootPane();
root.putClientProperty( "Window.shadow", Boolean.FALSE );
Any similar possibility for an AWT Frame?
I' using the Framework Processing and my code there looks like this:
void setup(){
frame.removeNotify();
frame.setUndecorated(true);
}
Processing itself does the main Frame creation, here is the source.
This is a simple application that uses a transparent window running on Max OS X 10.7.5 under Java 7 (has run under Java 6) which has no problems...
Share some code so we can replicate the issue
Updated from feedback
I have tested this on Mac OS 10.7.5 & 10.8.2, using JDK 1.7.0_07 & 1.6.0_37
Without and with Window.shadow property...
Without going into a lot of tests and without further information, I would suggest you want to make this call as early as you can. If that doesn't work, make it the last call before you make the window visible.
This may be related to how Java/AWT connects to it's native peer, presumably, once the connection is made, you will no longer be able to effect these kinds of properties...
public class TransparentFrame {
public static void main(String[] args) {
new TransparentFrame();
}
public TransparentFrame() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
// Use this to test the transparentancy API
//doTransparentFrame();
doDropShadow();
}
});
}
protected void doDropShadow() {
String version = System.getProperty("java.version");
System.out.println(version);
JFrame frame = new JFrame("Testing");
JRootPane root = frame.getRootPane();
root.putClientProperty("Window.shadow", root);
frame.setUndecorated(true);
frame.setContentPane(new ContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ImagePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
protected void doTransparentFrame() {
JFrame frame = new JFrame("Testing");
frame.setUndecorated(true);
frame.setContentPane(new ContentPane());
String version = System.getProperty("java.version");
System.out.println(version);
if (version.startsWith("1.7")) {
frame.setBackground(new Color(0, 0, 0, 0));
} else if (version.startsWith("1.6")) {
if (supportsPerAlphaPixel()) {
setOpaque(frame, false);
} else {
System.out.println("Per Pixel Alphering is not support with Java " + version);
System.exit(1);
}
} else {
System.out.println("Per Pixel Alphering is not support with Java " + version);
System.exit(1);
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ImagePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static boolean supportsPerAlphaPixel() {
boolean support = false;
try {
Class<?> awtUtilsClass = Class.forName("com.sun.awt.AWTUtilities");
support = true;
} catch (Exception exp) {
}
return support;
}
public static void setOpaque(Window window, boolean opaque) {
try {
Class<?> awtUtilsClass = Class.forName("com.sun.awt.AWTUtilities");
if (awtUtilsClass != null) {
Method method = awtUtilsClass.getMethod("setWindowOpaque", Window.class, boolean.class);
method.invoke(null, window, opaque);
}
} catch (Exception exp) {
}
}
public class ContentPane extends JPanel {
public ContentPane() {
setOpaque(false);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
}
}
public class ImagePane extends JPanel {
private BufferedImage background;
private BufferedImage offImage;
private Ellipse2D offButton;
private boolean mouseIn;
public ImagePane() {
setOpaque(false);
try {
background = ImageIO.read(new File("tamagotchi400.png"));
offImage = ImageIO.read(new File("powerSmall.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
offButton = new Ellipse2D.Float(212, 330, 25, 25);
MouseAdapter handler = new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 1 && e.getButton() == MouseEvent.BUTTON1) {
if (offButton.contains(e.getPoint())) {
Window window = SwingUtilities.getWindowAncestor(ImagePane.this);
if (window != null) {
window.dispose();
}
}
}
}
#Override
public void mouseMoved(MouseEvent e) {
Cursor cursor = Cursor.getDefaultCursor();
if (offButton.contains(e.getPoint())) {
cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
}
setCursor(cursor);
}
#Override
public void mouseEntered(MouseEvent e) {
mouseIn = true;
repaint();
}
#Override
public void mouseExited(MouseEvent e) {
mouseIn = false;
repaint();
}
};
addMouseListener(handler);
addMouseMotionListener(handler);
}
#Override
public Dimension getPreferredSize() {
return background == null ? new Dimension(400, 400) : new Dimension(background.getWidth(), background.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (background != null) {
Graphics2D g2d = (Graphics2D) g.create();
int x = (getWidth() - background.getWidth()) / 2;
int y = (getHeight() - background.getHeight()) / 2;
g2d.drawImage(background, x, y, this);
if (mouseIn && offImage != null) {
g2d.drawImage(offImage, (int) offButton.getX(), (int) offButton.getY(), this);
}
g2d.dispose();
}
}
}
}
The code also includes transparency test code to test the transparency API now available in Java 1.7 and Java 1.6_10+. I've used this code successfully in a number of projects, its less cumbersome then the AWT Robot "hack" and provides a live back ground, but that's a choice you need to make.
Updated
Demonstration using java.awt.Frame
public class TestTransparentFrame {
public static void main(String[] args) {
new TestTransparentFrame();
}
public TestTransparentFrame() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception exp) {
}
Frame frame = new Frame("Test");
frame.setUndecorated(true);
setOpaque(frame, false);
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setLayout(new BorderLayout());
frame.add(new ContentPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ContentPane extends JPanel {
private BufferedImage background;
public ContentPane() {
try {
background = ImageIO.read(new File("duke.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
setOpaque(false);
JButton close = new JButton("Close");
close.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.getWindowAncestor(ContentPane.this).dispose();
}
});
setBorder(new LineBorder(Color.RED));
setLayout(new GridBagLayout());
add(close);
}
#Override
public Dimension getPreferredSize() {
return background == null ? new Dimension(200, 200) : new Dimension(background.getWidth(), background.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (background != null) {
g.drawImage(background, 0, 0, this);
}
}
}
public static boolean supportsPerAlphaPixel() {
boolean support = false;
String version = System.getProperty("java.version");
if (version.startsWith("1.6")) {
try {
Class<?> awtUtilsClass = Class.forName("com.sun.awt.AWTUtilities");
support = true;
} catch (Exception exp) {
}
} else if (version.startsWith("1.7")) {
try {
Class<?> winTransClass = Class.forName("java.awt.GraphicsDevice$WindowTranslucency");
Field field = winTransClass.getField("TRANSLUCENT");
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
gd.isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency.TRANSLUCENT);
Method isWindowTranslucencySupported = GraphicsDevice.class.getMethod("isWindowTranslucencySupported", winTransClass);
System.out.println(isWindowTranslucencySupported);
Object value = isWindowTranslucencySupported.invoke(gd, field.get(null));
if (value instanceof Boolean) {
support = ((Boolean) value).booleanValue();
}
} catch (Exception exp) {
}
}
return support;
}
public static void setOpaque(Window window, boolean opaque) {
String version = System.getProperty("java.version");
if (version.startsWith("1.6")) {
try {
Class<?> awtUtilsClass = Class.forName("com.sun.awt.AWTUtilities");
if (awtUtilsClass != null) {
Method method = awtUtilsClass.getMethod("setWindowOpaque", Window.class, boolean.class);
method.invoke(null, window, opaque);
}
} catch (Exception exp) {
}
} else if (version.startsWith("1.7")) {
Color color = UIManager.getColor("Panel.background");
if (opaque) {
color = new Color(color.getRed(), color.getGreen(), color.getBlue());
} else {
color = new Color(color.getRed(), color.getGreen(), color.getBlue(), 0);
}
window.setBackground(color);
}
}
}
Tested on Windows 7 Java 1.6 & 1.7, Mac OS 10.7.5 & 10.8.2, using JDK 1.7.0_07 & 1.6.0_37
It appears that you don't understand the window hierarchy in Java
All "windows" in Java derive from java.awt.Window.
JFrame extends Frame which extends Window.
Using this line, it works:
AWTUtilities.setWindowOpaque(frame, false);
Eclipse prints out a warning on this and I had to change some settings to comile it, so I guess there may be better ways.
I read here, that this is supported since OS X 10.6 (Lion).
It seems that when your frame is not focus, the shadow effect will be triggered. Try adding this code so your frame will disabled being focus.
frame.setFocusableWindowState(false);
I came across a shadow problem with JInternalFrame on OSX today, and I found this solution for another forum (verified on Java 11, Catalina 10.15)
internalFrame.putClientProperty("JInternalFrame.frameType", "normal");
im using
getContentPane().setBackground(Color.PINK);
to set the background of a JFrame to the color pink. this JFrame is being fullscreened using a GraphicsDevice. the color of the background is not changing. any help?
fullscreen code:
public static void main(String... args) {
DisplayMode dMode = new DisplayMode(800, 600, 16, DisplayMode.REFRESH_RATE_UNKNOWN);
GameMain game = new GameMain();
game.run(dMode);
}
public void run(DisplayMode dMode) {
getContentPane().setBackground(Color.PINK);
setForeground(Color.WHITE);
setFont(new Font("Arial", Font.PLAIN, 24));
Screen s = new Screen();
try {
s.setFullScreen(dMode, this);
try {
Thread.sleep(5000);
} catch(Exception e) { }
} finally {
s.restoreScreen();
}
}
public void setFullScreen(DisplayMode dMode, JFrame window) {
window.setUndecorated(true);
window.setResizable(false);
gDevice.setFullScreenWindow(window);
if(dMode != null && gDevice.isDisplayChangeSupported()) {
try {
gDevice.setDisplayMode(dMode);
} catch(Exception e) { }
}
}
This works fine for me...
public class TestFullScreen {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
FullFrame frame = new FullFrame();
frame.setUndecorated(true);
frame.getContentPane().setBackground(Color.PINK);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
gs[0].setFullScreenWindow(frame);
}
});
}
public static class FullFrame extends JFrame {
public FullFrame() {
super();
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
System.exit(0);
}
});
}
}
}
I even set moved the setBackground call after the setFullScreenWindow call.
Make sure you don't have anything on the content pane that might be taking up the full space and that the content pane hasn't been changed.
I'm using NetBeans 6.1 as my primary IDE, in there I can't run this splash screen example which have given by the Sun (It throws an nullpointerExeption). But I can run this on command line using this arguments.
java -splash:filename.gif SplashDemo
I dont know how to inject command line arguments in NetBeans. Please someone help.
import java.awt.*;
import java.awt.event.*;
public class SplashDemo extends Frame implements ActionListener {
static void renderSplashFrame(Graphics2D g, int frame) {
final String[] comps = {"foo", "bar", "baz"};
g.setComposite(AlphaComposite.Clear);
g.fillRect(120, 140, 200, 40);
g.setPaintMode();
g.setColor(Color.BLACK);
g.drawString("Loading " + comps[(frame / 5) % 3] + "...", 120, 150);
}
public SplashDemo() {
super("SplashScreen demo");
setSize(300, 200);
setLayout(new BorderLayout());
Menu m1 = new Menu("File");
MenuItem mi1 = new MenuItem("Exit");
m1.add(mi1);
mi1.addActionListener(this);
this.addWindowListener(closeWindow);
MenuBar mb = new MenuBar();
setMenuBar(mb);
mb.add(m1);
final SplashScreen splash = SplashScreen.getSplashScreen();
if (splash == null) {
System.out.println("SplashScreen.getSplashScreen() returned null");
return;
}
Graphics2D g = splash.createGraphics();
if (g == null) {
System.out.println("g is null");
return;
}
for (int i = 0; i < 100; i++) {
renderSplashFrame(g, i);
splash.update();
try {
Thread.sleep(90);
} catch (InterruptedException e) {
}
}
splash.close();
setVisible(true);
toFront();
}
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
private static WindowListener closeWindow = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
e.getWindow().dispose();
}
};
public static void main(String args[]) {
SplashDemo test = new SplashDemo();
}
}
Go to project properties (right click on a project, and choose properties).
Choose "run" item from the Categories list.
There you can setup the arguments, VM options etc.