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.
Related
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
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");
import java.awt.Graphics;
import javax.swing.*;
public class Demo
{
JFrame jf;
JLabel[] labels;
JPanel panel;
public Demo()
{
jf = new JFrame();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
labels = new JLabel[10];
Box vbox = Box.createVerticalBox();
for (int i = 0; i < 10; i++)
{
labels[i] = new JLabel();
vbox.add(labels[i]);
}
panel = new JPanel();
panel.add(vbox);
jf.add(panel);
jf.setSize(300, 250);
jf.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new DemoRunnable());
}
public void updateState()
{
for (JLabel l : labels)
{
if (Math.random() > 0.5)
l.setText("777777777777777777777777777777777777");
else
l.setText("10000000000000000000000000000000000000");
}
}
}
class DemoRunnable implements Runnable
{
Demo demo;
DemoRunnable()
{
this.demo = new Demo();
}
#Override
public void run()
{
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
while (true)
{
try
{
Thread.sleep(0);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
demo.updateState();
}
}
});
t.start();
}
}
I see such effect when this program is perfomed. Is it possible to eliminate it(zeroes must be instead dots)?
Instead of setSize() use pack() to take advantage of the component's carefully calculated preferred size. You'll also need to initialize your label:
labels[i] = new JLabel("10000000000000000000000000000000000000");
Also consider javax.swing.Timer instead of a separate thread.
Addendum: Conveniently, each Swing Timer shares a common background thread, and the actionPerformed() is called on the event dispatch thread. An alternative is SwingWorker, illustrated here.
my code in answer is example only,
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.*;
public class Demo {
private JFrame jf;
private JLabel[] labels;
private JPanel panel;
public Demo() {
labels = new JLabel[10];
Box vbox = Box.createVerticalBox();
for (int i = 0; i < 10; i++) {
labels[i] = new JLabel();
labels[i].setText("10000000000000000000000000000000000000");
vbox.add(labels[i]);
}
panel = new JPanel();
panel.setLayout(new GridLayout());
panel.add(vbox);
jf = new JFrame();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(panel);
jf.pack();
jf.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new DemoRunnable());
}
public void updateState() {
for (final JLabel l : labels) {
if (Math.random() > 0.5) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
l.setText("777777777777777777777777777777777777");
}
});
} else {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
l.setText("10000000000000000000000000000000000000");
}
});
}
}
}
}
class DemoRunnable implements Runnable {
private Demo demo;
DemoRunnable() {
this.demo = new Demo();
}
#Override
public void run() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
try {
Thread.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
demo.updateState();
}
}
});
t.start();
}
}
I'm trying to capture the screen without including my application's window. To do this I first call setVisible(false), then I call the createScreenCapture method, and finally I call setVisible(true). This isn't working however and I'm still getting my applications window in the screen capture. If I add a call to sleep this seems to resolve the issue, but I know this is bad practice. What is the right way to do this?
Code:
setVisible(false);
BufferedImage screen = robot.createScreenCapture(rectScreenSize);
setVisible(true);
Have you tried to use SwingUtilities.invokeLater() and run the capture inside of the runnable passed as an argument? My guess is that the repaint performed to remove your application is performed right after the end of the current event in the AWT-EventQueue and thus invoking the call immediately still captures your window. Invoking the createCapture in a delayed event through invokeLater should fix this.
you have to delay this action by implements Swing Timer, for example
import javax.imageio.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
public class CaptureScreen implements ActionListener {
private JFrame f = new JFrame("Screen Capture");
private JPanel pane = new JPanel();
private JButton capture = new JButton("Capture");
private JDialog d = new JDialog();
private JScrollPane scrollPane = new JScrollPane();
private JLabel l = new JLabel();
private Point location;
private Timer timer1;
public CaptureScreen() {
capture.setActionCommand("CaptureScreen");
capture.setFocusPainted(false);
capture.addActionListener(this);
capture.setPreferredSize(new Dimension(300, 50));
pane.add(capture);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(pane);
f.setLocation(100, 100);
f.pack();
f.setVisible(true);
createPicContainer();
startTimer();
}
private void createPicContainer() {
l.setPreferredSize(new Dimension(700, 500));
scrollPane = new JScrollPane(l,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setBackground(Color.white);
scrollPane.getViewport().setBackground(Color.white);
d.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
d.add(scrollPane);
d.pack();
d.setVisible(false);
d.addWindowListener(new WindowListener() {
public void windowOpened(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
f.setVisible(true);
}
public void windowClosed(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
});
}
private void startTimer() {
timer1 = new Timer(1000, new AbstractAction() {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
capture.doClick();
f.setVisible(false);
}
});
}
});
timer1.setDelay(500);
timer1.setRepeats(false);
timer1.start();
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("CaptureScreen")) {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); // gets the screen size
Robot r;
BufferedImage bI;
try {
r = new Robot(); // creates robot not sure exactly how it works
Thread.sleep(1000); // waits 1 second before capture
bI = r.createScreenCapture(new Rectangle(dim)); // tells robot to capture the screen
showPic(bI);
saveImage(bI);
} catch (AWTException e1) {
e1.printStackTrace();
} catch (InterruptedException e2) {
e2.printStackTrace();
}
}
}
private void saveImage(BufferedImage bI) {
try {
ImageIO.write(bI, "JPG", new File("screenShot.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
}
private void showPic(BufferedImage bI) {
ImageIcon pic = new ImageIcon(bI);
l.setIcon(pic);
l.revalidate();
l.repaint();
d.setVisible(false);
//location = f.getLocationOnScreen();
//int x = location.x;
//int y = location.y;
//d.setLocation(x, y + f.getHeight());
d.setLocation(150, 150);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
d.setVisible(true);
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
CaptureScreen cs = new CaptureScreen();
}
});
}
}