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);
}
}
Related
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.
I have a JFrame, and whenever I switch from one JFrame using a JButton it starts out normally, but whenever I create a new instance of the first JFrame, the JButton is in an incorrect location and is the wrong size.
Example on startup
and when another one is created
Code:
public class Menu extends JFrame implements Runnable {
private static final long serialVersionUID = 1L;
public static int Number_of_Participants = 0;
protected JPanel window = new JPanel();
double p;
private JButton Participants;
private Rectangle rParticipants;
protected int Button_width = 240;
protected int Button_height = 48;
boolean running = false;
Thread thread;
JFrame frame = new JFrame();
public Menu() {
window.setBackground(Color.BLUE);
frame.setSize(new Dimension(800, 600));
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.getContentPane().add(window);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Image image = null;
try {
image = ImageIO.read(new File("res/BG.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
generateFiles();
drawButtons();
startMenu();
frame.repaint();
}
public void drawButtons() {
rParticipants = new Rectangle(520, 12, Button_width, Button_height);
Participants = new JButton("A");
Participants.setBounds(rParticipants);
window.add(Participants);
Participants.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.dispose();
new Participant(Number_of_Participants);
}
});
}
}
Participant.java extends Menu.java
int Participant_ID;
public Participant(int Participant_ID) {
super();
this.Participant_ID = Participant_ID;
}
makes a JButton that goes back to Menu.java
As mentioned in the comment, your problem is most likely related to the call to setVisible(true). This should always be the LAST call in the constructor. Particularly, it should only be called AFTER all components have been added to the frame.
Apart from that, from the code that you posted, it seems like you want to switch through a seqence of frames, starting with a "main" menu, and then going through one frame for each "Participant". This intention could already be considered as questionable, because closing and disposing a JFrame just in order to create a new one does not seem to be very elegant. Most likely, a more elegant solution would be possible with a CardLayout : http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html
However, some general hints:
Create the GUI on the Event Dispatch Thread
Don't extend JFrame. Instead, create a JFrame and fill it as needed
Don't implement Runnable with your top level class
Obey the standardJavaNamingConventions!
Don't try to do manual layouts with setBounds
This code is still not "beautiful", but at least shows how the goal of switching through several frames might be achieved, taking into account these points
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MenuExample
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
JPanel mainMenuPanel = new MainMenuPanel();
createAndShowFrame(mainMenuPanel);
}
});
}
static void createAndShowFrame(JPanel panel)
{
JFrame frame = new JFrame();
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(800, 600));
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
static JButton createNextParticipantButton(
final JComponent container, final int nextID)
{
JButton nextParticipantButton = new JButton("New Participant");
nextParticipantButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
Window window =
SwingUtilities.getWindowAncestor(container);
window.dispose();
ParticipantPanel participantPanel =
new ParticipantPanel(nextID);
createAndShowFrame(participantPanel);
}
});
return nextParticipantButton;
}
}
class MainMenuPanel extends JPanel
{
public MainMenuPanel()
{
setBackground(Color.BLUE);
add(MenuExample.createNextParticipantButton(this, 0));
}
}
class ParticipantPanel extends JPanel
{
private final int participantID;
public ParticipantPanel(int participantID)
{
this.participantID = participantID;
add(new JLabel("Add the contents for participant "+participantID));
add(MenuExample.createNextParticipantButton(this, participantID+1));
}
}
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);
}
}
Contents
Overview
Example Code
Screenshots of Problem
1. Overview of problem
So I'm writing a GUI for a complicated program I'm developing, and I get tired of trying to get components to scale correctly when the window is resized.
At first I was using several layouts inside the jframe, and each jpanel to try and place the components correctly and scale them appropriately. Naturally, I got fed up with them, and I started trying to scale and set the x,y positions of the components dynamically (it's so much easier :D).
Basically I'm trying to divide the screen into three sections left margin (JSplitPane), center (JTabbedPane), and right margin (JSplitPane). I don't think the internal components matter at this point. The main problem is the right JSplitPane scales over the whole window despite my using setBounds() to place the x,y over on the right and set the size to 21% of the total width. It seems to interact weird with the other panels.
2. Example Code
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.Dimension;
#SuppressWarnings("deprecation")
public class test extends JFrame implements WindowListener {
/* Constants =========================================================================*/
private final double LEFT_SIZE = .21;
private final double CENTER_SIZE = .58;
private final double RIGHT_SIZE = .21;
private final int TOP_PADDING = 50;
private final int LEFT_PADDING = 4;
private final int RIGHT_PADDING = 4;
private final int BOTTOM_PADDING = 4;
private final int MIN_WIDTH = 640;
private final int MIN_HEIGHT = 480;
public static final String INIT_TITLE = "TestFrame v0.01";
/* End Constants =====================================================================*/
/* Instance Variables ================================================================*/
private int contentWidth;
private int contentHeight;
/* End Instance Variables ============================================================*/
/* Objects ===========================================================================*/
public static test window;
/* Begin Frame Design =========================================================== */
private JSplitPane left;
private JButton button1; private JButton button2;
private JTabbedPane center;
private JPanel panel1; private JPanel panel2;
private JSplitPane right;
private JButton button3; private JButton button4;
/* End Frame Design ============================================================= */
/* End Objects ====================================================================== */
/** Initializes and Places all GUI elements **/
public test ( String windowName ) {
super(windowName); //call parent constructor
this.addWindowListener(this); //adds window event functionality such as close
this.setExtendedState(this.getExtendedState() | JFrame.MAXIMIZED_BOTH); //Starts program maximized
this.setMinimumSize(new Dimension(MIN_WIDTH,MIN_HEIGHT));
this.setVisible(true);
this.setMaximumSize(this.getSize());
/* Begin Init JFrame this ------------------------------------------------------------ */
button1 = new JButton("button1");
button2 = new JButton("button2");
left = new JSplitPane(JSplitPane.VERTICAL_SPLIT, button1, button2);
left.setResizeWeight(1);
button3 = new JButton("button3");
button4 = new JButton("button4");
right = new JSplitPane(JSplitPane.VERTICAL_SPLIT, button3, button4);
right.setResizeWeight(.25);
panel1 = new JPanel();
panel2 = new JPanel();
center = new JTabbedPane();
center.addTab("Panel1", panel1);
center.addTab("Panel2", panel2);
this.add(left);
this.add(center);
this.add(right);
this.addComponentListener(new ComponentListener() {
#Override
public void componentResized (ComponentEvent e) {
window.contentWidth = window.getWidth() - window.LEFT_PADDING - window.RIGHT_PADDING;
window.contentHeight = window.getHeight() - window.TOP_PADDING - window.BOTTOM_PADDING;
window.left.setBounds ( 0, 0, (int)(window.contentWidth * window.LEFT_SIZE), window.contentHeight);
window.center.setBounds ( window.left.getWidth(), 0, (int)(window.contentWidth * window.CENTER_SIZE), window.contentHeight);
window.panel1.setBounds ( 0, 0, (int)(window.contentWidth * window.CENTER_SIZE), window.contentHeight);
window.panel2.setBounds ( 0, 0, (int)(window.contentWidth * window.CENTER_SIZE), window.contentHeight);
window.right.setBounds ( window.left.getWidth() + window.center.getWidth(), 0, (int)(window.contentWidth * window.RIGHT_SIZE), window.contentHeight);
}
public void componentHidden (ComponentEvent e) {}
public void componentMoved (ComponentEvent e) {}
public void componentShown (ComponentEvent e) {}
});
/* End Init JFrame this -------------------------------------------------------------- */
}
// window event abstracts
#Override
public void windowClosing (WindowEvent event) { window.dispose(); System.exit(0); }
public void windowClosed (WindowEvent event) {}
public void windowDeiconified (WindowEvent event) {}
public void windowIconified (WindowEvent event) {}
public void windowActivated (WindowEvent event) {}
public void windowDeactivated (WindowEvent event) {}
public void windowOpened (WindowEvent event) {}
public static void main(String[] args){
window = new test(INIT_TITLE);
window.setVisible(true);
}
}
3. Screenshots
I don't think the internal components matter at this point.
As discussed in Should I avoid the use of set[Preferred|Maximum|Minimum]Size methods in Java Swing?, nothing could be further from the truth. Correct use of layouts relies on a component's preferred size. That size is carefully calculated based on the contents. Second guessing, as shown in your example, is doomed to fail.
Instead, add components and pack() the frame. In the example below, the center panel returns an arbitrary result to show how pack() does its work.
Addendum: Two additional points helpfully adduced by #mKorbel:
Swing GUI objects should be constructed and manipulated only on the event dispatch thread.
See also this example that shows how to use setDividerLocation() in invokeLater().
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import java.awt.Dimension;
import java.awt.EventQueue;
public class Test extends JFrame {
public static final String INIT_TITLE = "TestFrame v0.02";
public static Test window;
private JSplitPane left;
private JTabbedPane center;
private JSplitPane right;
public Test(String windowName) {
super(windowName);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
left = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
new JButton("button1"), new JButton("button2"));
left.setResizeWeight(0.5);
right = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
new JButton("button3"), new JButton("button4"));
right.setResizeWeight(0.5);
center = new JTabbedPane();
center.addTab("Panel1", new MyPanel());
center.addTab("Panel2", new MyPanel());
this.add(left, BorderLayout.WEST);
this.add(center, BorderLayout.CENTER);
this.add(right, BorderLayout.EAST);
this.pack();
this.setLocationByPlatform(true);
this.setVisible(true);
}
private static class MyPanel extends JPanel {
private Dimension d = new Dimension(320, 240);
#Override
public Dimension getPreferredSize() {
return d;
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
window = new Test(INIT_TITLE);
window.setVisible(true);
}
});
}
}
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.