Get the maximum screen size with JFrame - java

I have been working on making Pong in Java, but I can't seem to accurately set the size of the JFrame. Here is my main class:
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class Pong extends JFrame {
private final Game panel;
private final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
public Pong() {
setTitle("Pong");
setSize(screenSize);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new Game(this);
add(panel);
}
public static void main(String[] args) {
new Pong();
}
}
When I run my program, the window takes up the whole screen, but when I try to get the dimensions of the screen, they are larger than those of the window, causing anything set at the lower extents of the window to get cut off. The only way I have found to get the true dimensions is to call this.getHeight(), this.getWidth(), or this.getSize() within the panel class. How can I get the true dimensions right off the bat?

You could use JFrame#setExtendedState(JFrame.MAXIMIZED_BOTH)
f.setExtendedState(JFrame.MAXIMIZED_BOTH);
It has the same effect as when you enlarge a window in your OS
With this method, you can now have the "real" dimensions by calling the different methods mentionned above in the question.

Try to call method setExtendedState.
public class Pong extends JFrame {
private final Game panel;
public Pong() {
setTitle("Pong");
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new Game(this);
add(panel);
setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
//setVisible(true);
}
public static void main(String[] args) {
Pong pong = new Pong();
pong.setVisible(true);
}
}

import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class Pong extends JFrame {
private final Game panel;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();
public Pong() {
setTitle("Pong");
setSize((int)width,(int)height);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new Game(this);
add(panel);
}
public static void main(String[] args) {
new Pong();
}
}
check this question How can I get screen resolution in java?

Put in your code:
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
Details you can find in documentation.
Another questions on same subject is here.

Related

Background color not working JPanel inside JFrame

I am trying to do a very simple thing.. set the background color on the JPanel inside my JFrame. I have not used swing very much so I am still learning. However, I have read up on doing something as basic as setting the background color quite a bit, and I do not know why what I have is not working.
I have my JFrame set up in my Main class.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class Main extends JFrame {
private static Screen screen;
private static int WIDTH = 600;
private static int HEIGHT = 600;
public Main() {
screen = new Screen();
setTitle("Asteroid");
setSize(WIDTH, HEIGHT);
setLayout(new BorderLayout());
add(screen, BorderLayout.CENTER);
setBackground(Color.BLACK);
setResizable(false);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
#Override
public void paint(Graphics g) {
}
public static void main(String[] args) {
new Main();
}
}
And then I have my JPanel set up in a Screen class
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JPanel;
public class Screen extends JPanel {
private static int WIDTH = 600;
private static int HEIGHT = 600;
private Dimension screen = new Dimension(WIDTH, HEIGHT);
public Screen() {
setSize(screen);
setBackground(Color.BLACK);
setOpaque(true);
}
}
I am not sure why this is not working properly.
The problem is that you #Override paint method (you should not) of your JFrame. In addition you leave it empty, without calling the super paint method. So, if you simply add super.paint(g); to your #Override you will see that background is painted without problems.
However, when you want to do custom painting, you should #Override paintComponent(Graphics g) method, and again, start by calling super.paintComponent(g);.

Java JLabel background color not working?

I'm learning how to create application in Java.
I'm having trouble getting the JLabel to have a background color whilst the JPanel is white, behind it. Also, is there a way to resize the JPanel to half of what the JFrame is?
Any help would be very much appreciated. Thank you.
package PracticeOne;
import java.awt.BorderLayout;
public class PracticeOne {
public static void main(String[] args) {
Frame container = new Frame();
Panel box = new Panel();
Label txt = new Label();
box.add(txt);
container.add(box, BorderLayout.CENTER);
}
}
package PracticeOne;
import javax.swing.JFrame;
public class Frame extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
Frame(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500, 500);
this.setVisible(true);
this.setLocationRelativeTo(null);
this.setTitle("Testing this out");
}
}
package PracticeOne;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JPanel;
public class Panel extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
public Dimension d = new Dimension(100,100);
Panel(){
this.setSize(d);
this.setAlignmentX(CENTER_ALIGNMENT);
this.setBackground(Color.WHITE);
}
}
package PracticeOne;
import java.awt.Color;
import javax.swing.JLabel;
public class Label extends JLabel {
/**
*
*/
private static final long serialVersionUID = 1L;
Label(){
this.setSize(50, 50);
this.setText("ya boy is working here");
this.setForeground(Color.BLACK);
this.setBackground(Color.ORANGE);
}
}
I'm having trouble getting the JLabel to have a background color whilst the JPanel is white
You need to call setOpaque(true); in your JLabel
Also, is there a way to resize the JPanel to half of what the JFrame is?
You could use a GridLayout, and place 2 JPanels in it, that way, you're going to have 2 JPanels using half the size of your JFrame each.
Also, rename your classes, Panel belongs to the name of a class in AWT, same for Frame and Label, this might confuse your (and whoever reads your code).
Never extend JFrame, instead build your GUI based on JPanels. See extends JFrame vs creating it inside of class and The use of multiple JFrames, Good / Bad practice? The general consensus says it's bad.
Also you should also check Should I avoid the use of setPreferred|Maximum|MinimumSize() in Swing? Again, yes, you should and instead override the getPreferredSize() method.
Don't forget to place your program on the Event Dispatch Thread (EDT) by changing your main() method as follows:
public static void main(String[] args) {
//Java 8 with lambda expressions
SwingUtilities.invokeLater(() ->
//Your code here
);
//Java 7 and below (Or 8 without lambda expressions)
SwingUtilities.invokeLater(new Runnable() {
//Your code here
});
}
Now, with all the above recommendations, your code should now look like this:
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class HalfSizePanelWithLabelInDifferentColor {
private JFrame frame;
private Container contentPane;
private JPanel pane;
private JPanel pane2;
private JLabel label;
private static final Dimension dim = new Dimension(100, 100);
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new HalfSizePanelWithLabelInDifferentColor().createAndShowGui());
}
public void createAndShowGui() {
frame = new JFrame(getClass().getSimpleName());
contentPane = frame.getContentPane();
pane = new JPanel() {
#Override
public Dimension getPreferredSize() {
return dim;
}
};
pane2 = new JPanel();
pane.setOpaque(false);
pane2.setOpaque(false);
pane.setBorder(BorderFactory.createLineBorder(Color.RED));
pane2.setBorder(BorderFactory.createLineBorder(Color.BLUE));
label = new JLabel("Hello World!");
label.setBackground(Color.GREEN);
label.setOpaque(true);
contentPane.setLayout(new GridLayout(2, 1));
pane.add(label);
contentPane.add(pane);
contentPane.add(pane2);
contentPane.setBackground(Color.WHITE);
frame.setContentPane(contentPane);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
And your output would be like this:
Note that I added some colored borders to show where a pane starts and ends and where the other one starts and ends

How to implement Java Swing fullscreen mode for Java 7 on Mac? [duplicate]

In my Java application I try to make a JFrame really fullscreen by using this code:
public class MainFrame extends JFrame {
private static final long serialVersionUID = 1L;
public MainFrame() {
super();
this.setTitle();
this.setUndecorated(true);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.setVisible(true);
//this.pack();
}
}
But on my Mac I can still see the Dock and the top toolbar of the OSX. So how can I create a JFrame that really consumes my whole screen?
EDIT
I have to add that I want to call that JFrame from a eclipse plugin.
I haven't tried it yet, but Java has fullscreen API, which should meet your needs:
http://docs.oracle.com/javase/tutorial/extra/fullscreen/index.html
I know the answer. Firstly, I have to admit that the following trick won't work if you are making video or movie player or animation player. OK here is what i found after many tries:
Let's say that you want to make a JFrame (called frame) fullscreen when you press a button (called fullscreenButton).Then do the following :
import java.awt.*;
import javax.swing.*;
public class FullscreenJFrame extends JFrame{
private JPanel contentPane = new JPanel();
private JButton fullscreenButton = new JButton("Fullscreen Mode");
private boolean Am_I_In_FullScreen = false;
private int PrevX,PrevY,PrevWidth,PrevHeight;
public static void main(String[] args) {
FullscreenJFrame frame = new FullscreenJFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600,500);
frame.setVisible(true);
}
public FullscreenJFrame(){
super("My FullscreenJFrame");
setContentPane(contentPane);
//From Here starts the trick
FullScreenEffect effect = new FullScreenEffect();
fullscreenButton.addActionListener(effect);
contentPane.add(fullscreenButton);
fullscreenButton.setVisible(true);
}
private class FullScreenEffect implements ActionListener{
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
if(Am_I_In_FullScreen == false){
PrevX = getX();
PrevY = getY();
PrevWidth = getWidth();
PrevHeight = getHeight();
dispose(); //Destroys the whole JFrame but keeps organized every Component
//Needed if you want to use Undecorated JFrame
//dispose() is the reason that this trick doesn't work with videos
setUndecorated(true);
setBounds(0,0,getToolkit().getScreenSize().width,getToolkit().getScreenSize().height);
setVisible(true);
Am_I_In_FullScreen = true;
}
else{
setVisible(true);
setBounds(PrevX, PrevY, PrevWidth, PrevHeight);
dispose();
setUndecorated(false);
setVisible(true);
Am_I_In_FullScreen = false;
}
}
}
}
I hope you enjoyed it
An example:
import java.awt.FlowLayout;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class FullScreenJFrame extends JFrame{
private GraphicsDevice vc;
public FullScreenJFrame(){
super();
GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
vc= e.getDefaultScreenDevice();
JButton b = new JButton("exit");
b.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
dispose();
System.exit(0);
}
}
);
this.setLayout(new FlowLayout());
this.add(b);
setFullScreen(this);
}
public void setFullScreen(JFrame f){
f.setUndecorated(true);
f.setResizable(false);
vc.setFullScreenWindow(f);
}
public static void main(String[] args){
new FullScreenJFrame();
}
}
private Dimension screenSize; /* class level vars */
private swidth , sheight;
/*In GUI creating method:put this code: */
screenSize = Toolkit.getDefaultToolkit().getScreenSize();
sheight = screenSize.height;
swidth = screenSize.width;
setBounds(0, 0, swidth, sheight-40);
NB: using swidth, sheight vars give you the liberty to further adjust.
Best way is to use int vars in place of - 40 e.g sheight/swidth - margin etc.
Here margin should come from parameter table. Getting full control of situation.
Direct usage also possible as: setBounds(0,0,screenSize.width, screenSize.height);
Use com.apple.eawt.FullScreenUtilities. And make sure to test that the system is running Mac OS.
public void enableFullscreen(Window window, boolean bool) {
if (System.getProperty("os.name").startsWith("Mac OS")) {
com.apple.eawt.FullScreenUtilities.setWindowCanFullScreen(window, bool);
}
}

How to make a JFrame really fullscreen?

In my Java application I try to make a JFrame really fullscreen by using this code:
public class MainFrame extends JFrame {
private static final long serialVersionUID = 1L;
public MainFrame() {
super();
this.setTitle();
this.setUndecorated(true);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.setVisible(true);
//this.pack();
}
}
But on my Mac I can still see the Dock and the top toolbar of the OSX. So how can I create a JFrame that really consumes my whole screen?
EDIT
I have to add that I want to call that JFrame from a eclipse plugin.
I haven't tried it yet, but Java has fullscreen API, which should meet your needs:
http://docs.oracle.com/javase/tutorial/extra/fullscreen/index.html
I know the answer. Firstly, I have to admit that the following trick won't work if you are making video or movie player or animation player. OK here is what i found after many tries:
Let's say that you want to make a JFrame (called frame) fullscreen when you press a button (called fullscreenButton).Then do the following :
import java.awt.*;
import javax.swing.*;
public class FullscreenJFrame extends JFrame{
private JPanel contentPane = new JPanel();
private JButton fullscreenButton = new JButton("Fullscreen Mode");
private boolean Am_I_In_FullScreen = false;
private int PrevX,PrevY,PrevWidth,PrevHeight;
public static void main(String[] args) {
FullscreenJFrame frame = new FullscreenJFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600,500);
frame.setVisible(true);
}
public FullscreenJFrame(){
super("My FullscreenJFrame");
setContentPane(contentPane);
//From Here starts the trick
FullScreenEffect effect = new FullScreenEffect();
fullscreenButton.addActionListener(effect);
contentPane.add(fullscreenButton);
fullscreenButton.setVisible(true);
}
private class FullScreenEffect implements ActionListener{
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
if(Am_I_In_FullScreen == false){
PrevX = getX();
PrevY = getY();
PrevWidth = getWidth();
PrevHeight = getHeight();
dispose(); //Destroys the whole JFrame but keeps organized every Component
//Needed if you want to use Undecorated JFrame
//dispose() is the reason that this trick doesn't work with videos
setUndecorated(true);
setBounds(0,0,getToolkit().getScreenSize().width,getToolkit().getScreenSize().height);
setVisible(true);
Am_I_In_FullScreen = true;
}
else{
setVisible(true);
setBounds(PrevX, PrevY, PrevWidth, PrevHeight);
dispose();
setUndecorated(false);
setVisible(true);
Am_I_In_FullScreen = false;
}
}
}
}
I hope you enjoyed it
An example:
import java.awt.FlowLayout;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class FullScreenJFrame extends JFrame{
private GraphicsDevice vc;
public FullScreenJFrame(){
super();
GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
vc= e.getDefaultScreenDevice();
JButton b = new JButton("exit");
b.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
dispose();
System.exit(0);
}
}
);
this.setLayout(new FlowLayout());
this.add(b);
setFullScreen(this);
}
public void setFullScreen(JFrame f){
f.setUndecorated(true);
f.setResizable(false);
vc.setFullScreenWindow(f);
}
public static void main(String[] args){
new FullScreenJFrame();
}
}
private Dimension screenSize; /* class level vars */
private swidth , sheight;
/*In GUI creating method:put this code: */
screenSize = Toolkit.getDefaultToolkit().getScreenSize();
sheight = screenSize.height;
swidth = screenSize.width;
setBounds(0, 0, swidth, sheight-40);
NB: using swidth, sheight vars give you the liberty to further adjust.
Best way is to use int vars in place of - 40 e.g sheight/swidth - margin etc.
Here margin should come from parameter table. Getting full control of situation.
Direct usage also possible as: setBounds(0,0,screenSize.width, screenSize.height);
Use com.apple.eawt.FullScreenUtilities. And make sure to test that the system is running Mac OS.
public void enableFullscreen(Window window, boolean bool) {
if (System.getProperty("os.name").startsWith("Mac OS")) {
com.apple.eawt.FullScreenUtilities.setWindowCanFullScreen(window, bool);
}
}

JFrame Maximize window

I'm putting together a quick and dirty animation using swing. I would like the window to be maximized. How can I do that?
Provided that you are extending JFrame:
public void run() {
MyFrame myFrame = new MyFrame();
myFrame.setVisible(true);
myFrame.setExtendedState(myFrame.getExtendedState() | JFrame.MAXIMIZED_BOTH);
}
Something like this.setExtendedState(this.getExtendedState() | this.MAXIMIZED_BOTH);
import java.awt.*;
import javax.swing.*;
public class Test extends JFrame
{
public Test()
{
GraphicsEnvironment env =
GraphicsEnvironment.getLocalGraphicsEnvironment();
this.setMaximizedBounds(env.getMaximumWindowBounds());
this.setExtendedState(this.getExtendedState() | this.MAXIMIZED_BOTH);
}
public static void main(String[] args)
{
JFrame.setDefaultLookAndFeelDecorated(true);
Test t = new Test();
t.setVisible(true);
}
}
If you're using a JFrame, try this
JFrame frame = new JFrame();
//...
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
How about JFrame.setExtendedState(JFrame.MAXIMIZED_BOTH)?
i like this version:
import java.awt.Dimension;
import java.awt.GraphicsConfiguration;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class Test
{
public static void main(String [] args)
{
final JFrame frame = new JFrame();
final GraphicsConfiguration config = frame.getGraphicsConfiguration();
final int left = Toolkit.getDefaultToolkit().getScreenInsets(config).left;
final int right = Toolkit.getDefaultToolkit().getScreenInsets(config).right;
final int top = Toolkit.getDefaultToolkit().getScreenInsets(config).top;
final int bottom = Toolkit.getDefaultToolkit().getScreenInsets(config).bottom;
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
final int width = screenSize.width - left - right;
final int height = screenSize.height - top - bottom;
frame.setResizable(false);
frame.setSize(width,height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
The way to set JFrame to full-screen, is to set MAXIMIZED_BOTH option which stands for MAXIMIZED_VERT | MAXIMIZED_HORIZ, which respectively set the frame to maximize vertically and horizontally
package Example;
import java.awt.GraphicsConfiguration;
import javax.swing.JFrame;
import javax.swing.JButton;
public class JFrameExample
{
static JFrame frame;
static GraphicsConfiguration gc;
public static void main(String[] args)
{
frame = new JFrame(gc);
frame.setTitle("Full Screen Example");
frame.setExtendedState(MAXIMIZED_BOTH);
JButton button = new JButton("exit");
b.addActionListener(new ActionListener(){#Override
public void actionPerformed(ActionEvent arg0){
JFrameExample.frame.dispose();
System.exit(0);
}});
frame.add(button);
frame.setVisible(true);
}
}
I've tried the solutions in this thread and the ones here, but simply calling setExtendedState(getExtendedState()|Frame.MAXIMIZED_BOTH); right after calling setVisible(true); apparently does not work for my environment (Windows 10, JDK 1.8, my taskbar is on the right side of my screen). Doing it this way still leaves a tiny space on the left, right and bottom .
What did work for me however, is calling setExtendedState(... when the window is activated, like so:
public class SomeFrame extends JFrame {
public SomeFrame() {
// ...
setVisible(true);
setResizable(true);
// if you are calling setSize() for fallback size, do that here
addWindowListener (
new WindowAdapter() {
private boolean shown = false;
#Override
public void windowActivated(WindowEvent we) {
if(shown) return;
shown = true;
setExtendedState(getExtendedState()|JFrame.MAXIMIZED_BOTH);
}
}
);
}
}
I ended up using this code:
public void setMaximized(boolean maximized){
if(maximized){
DisplayMode mode = this.getGraphicsConfiguration().getDevice().getDisplayMode();
Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(this.getGraphicsConfiguration());
this.setMaximizedBounds(new Rectangle(
mode.getWidth() - insets.right - insets.left,
mode.getHeight() - insets.top - insets.bottom
));
this.setExtendedState(this.getExtendedState() | JFrame.MAXIMIZED_BOTH);
}else{
this.setExtendedState(JFrame.NORMAL);
}
}
This options worked the best of all the options, including multiple monitor support. The only flaw this has is that the taskbar offset is used on all monitors is some configurations.
#kgiannakakis answer is fully correct, but if someone stuck into this problem and uses Java 6 on Linux (by example, Mint 19 Cinnamon), MAXIMIZED_BOTH state is sometimes not applied.
You could try to call pack() method after setting this state.
Code example:
public MainFrame() {
setContentPane(contentPanel); //some JPanel is here
setPreferredSize(new Dimension(1200, 800));
setMinimumSize(new Dimension(1200, 800));
setSize(new Dimension(1200, 800));
setExtendedState(JFrame.MAXIMIZED_BOTH);
pack();
}
This is not necessary if you are using Java 7+ or Java 6 on Windows.

Categories

Resources