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));
}
}
Related
I am currently practicing OOP with Java.
I have created a GUI project via WindowBuilder with Eclipse IDE and below is the result.
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Example window = new Example();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Example() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JProgressBar progressBar = new JProgressBar();
frame.getContentPane().add(progressBar, BorderLayout.CENTER);
}
What I am trying to do is to connect the JProgressBar to another class that has the actual task, to show the progress.
For example, if the other class contains the following code:
int i = 0;
while(i <= 100) {
progressBar.setValue(i);
i++;
}
how should I change the progressBar.setValue(i); part?
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay particular attention to the Concurrency in Swing section.
Here's the simplest working example I could create. As you can see in the picture, I caught the JProgressBar in the middle.
Each time you press the button, the progress bar will count from 0 to 100, one unit every 100 milliseconds.
In order to access the progress bar, you have to make it a class field or variable. You can then access the class field with a setter. Getters and setters are a basic Java concept. You can see another example of a plain Java getter/setter class in my JProgressBarModel class.
I used a Swing Timer to add a delay to the updating of the progress bar so you can see the bar update and simulate an actual long-running task. The actual work takes place in the WorkListener class. Because the code is inside an ActionListener, the Swing update of the progress bar takes place on the Event Dispatch Thread.
Here's the complete runnable code. I made all the additional classes inner classes so I could post the code as one block.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class JProgressBarExample implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new JProgressBarExample());
}
private JProgressBar progressBar;
private final JProgressBarModel model;
public JProgressBarExample() {
this.model = new JProgressBarModel();
}
#Override
public void run() {
JFrame frame = new JFrame("Progress Bar Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
progressBar = new JProgressBar();
panel.add(progressBar);
JButton button = new JButton("Start Process");
button.addActionListener(event -> {
model.setIndex(0);
setValue();
Timer timer = new Timer(100, new WorkListener(this, model));
timer.start();
});
panel.add(button);
return panel;
}
public void setValue() {
progressBar.setValue(model.getIndex());
}
public class WorkListener implements ActionListener {
private final JProgressBarExample view;
private final JProgressBarModel model;
public WorkListener(JProgressBarExample view, JProgressBarModel model) {
this.view = view;
this.model = model;
}
#Override
public void actionPerformed(ActionEvent event) {
Timer timer = (Timer) event.getSource();
int index = model.getIndex() + 1;
model.setIndex(index);
view.setValue();
if (index >= 100) {
timer.stop();
}
}
}
public class JProgressBarModel {
private int index;
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
}
One option is to do it similar to the frame part. You Example class has a field variable that could be directly accessible to your other code.
A better way would be to have a private field for the JProgressBar and a getProgressBar() method.
But currently you are using a method variable that is forgotten when initialize() returns.
I have 2 classes. Both implements runnable to create the GUI. The first one is the main, and the second one is the secondary class.
I want within the actionlistener of the main class to startup the secondary class.
Here is the code (the two classes are separated files):
public class Main implements Runnable
{
private JTextField txt1, txt2;
private JLabel lbl1, lbl2;
public void run()
{
JFrame frame = new JFrame("Secondary");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = frame.getContentPane();
JPanel background = new JPanel();
background.setLayout(new BoxLayout(background, BoxLayout.LINE_AXIS));
.........
// Horizontally adding the textbox and button in a Box
Box box = new Box(BoxLayout.Y_AXIS);
......
background.add(box);
pane.add(background);
frame.pack();
frame.setVisible(true);
}
private class SListener implements ActionListener
{
public void actionPerformed(ActionEvent a)
{
Secondary s = new Secondary();
}
}
public static void main (String[] args)
{
Main gui = new Main();
SwingUtilities.invokeLater(gui);
}
}
public class Secondary implements Runnable
{
private JTextField txt1, txt2;
private JLabel lbl1, lbl2;
public Secondary()
{
Secondary gui = new Secondary();
SwingUtilities.invokeLater(gui);
}
public void run()
{
JFrame frame = new JFrame("Secondary");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = frame.getContentPane();
JPanel background = new JPanel();
background.setLayout(new BoxLayout(background, BoxLayout.LINE_AXIS));
.........
// Horizontally adding the textbox and button in a Box
Box box = new Box(BoxLayout.Y_AXIS);
......
background.add(box);
pane.add(background);
frame.pack();
frame.setVisible(true);
}
}
I want to keep the code in two files, I don't want to mixed the two classes in one file.
As you can see from the code, in the Secondary class, in it's constructor I create an Instance of the Secondary class and I run the gui so that when the Instance of this class is created in the Main class, to run the gui.
Unfortunately this technique is not working.
Any ideas?
Thanks
The following line are complety wrong:
public Secondary(){
Secondary gui = new Secondary();
SwingUtilities.invokeLater(gui);
}
Each time you call new Secondary() somewhere in your code, the above code will be triggered, which in turn calls new Secondary() again, and again, and again, ... and your program is blocked.
You probably want to replace it either by
public Secondary(){
SwingUtilities.invokeLater(this);
}
which will avoid the loop, but this is weird behaviour for a constructor.
It makes much more sense to switch to an empty constructor (or delete it all together)
public Secondary(){
}
and rewrite your listener to
public void actionPerformed(ActionEvent a){
Secondary s = new Secondary();
SwingUtilities.invokeLater( s );
}
I would recommend that you completely re-design your program. I find that it is most helpful to gear my GUI's towards creation of JPanels, not top level windows such as JFrame, which can then be placed into JFrames or JDialogs, or JTabbedPanes, or swapped via CardLayouts, wherever needed. I find that this greatly increase the flexibility of my GUI coding, and is exactly what I suggest that you do. So...
Your first class creates a JPanel that is then placed into a JFrame.
In the first class's ActionListener, create an instance of the 2nd class, place it into a JDialog (not a JFrame), and then display it.
For example,
import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class TwoWindowEg {
public TwoWindowEg() {
// TODO Auto-generated constructor stub
}
private static void createAndShowGui() {
GuiPanel1 mainPanel = new GuiPanel1();
JFrame frame = new JFrame("Main GUI");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class GuiPanel1 extends JPanel {
private static final int PREF_W = 800;
private static final int PREF_H = 650;
private GuiPanel2 guiPanel2 = new GuiPanel2(); // our second class!
private JDialog dialog = null; // our JDialog
public GuiPanel1() {
setBorder(BorderFactory.createTitledBorder("GUI Panel 1"));
add(new JButton(new LaunchNewWindowAction("Launch New Window")));
add(new JButton(new DisposeAction("Exit", KeyEvent.VK_X)));
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class LaunchNewWindowAction extends AbstractAction {
public LaunchNewWindowAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent e) {
if (dialog == null) {
// get the Window that holds this JPanel
Window win = SwingUtilities.getWindowAncestor(GuiPanel1.this);
dialog = new JDialog(win, "Second Window", ModalityType.APPLICATION_MODAL);
dialog.add(guiPanel2);
dialog.pack();
}
dialog.setVisible(true);
}
}
}
class GuiPanel2 extends JPanel {
public GuiPanel2() {
setBorder(BorderFactory.createTitledBorder("GUI Panel 1"));
add(new JLabel("The second JPanel/Class"));
add(new JButton(new DisposeAction("Exit", KeyEvent.VK_X)));
}
}
class DisposeAction extends AbstractAction {
public DisposeAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
Component comp = (Component) e.getSource();
Window win = SwingUtilities.getWindowAncestor(comp);
win.dispose();
}
}
Alternatively, you could swap JPanel "views" using a CardLayout, but either way, you will want to avoid showing two JFrames. Please have a look at The Use of Multiple JFrames, Good/Bad Practice?.
I'm trying to make a program thats based upon 5 Jsplitpanes and internal components, but they don't seem to get along well. Since when I run the application all the split panes are concentrated on the upper left corner
The code is really simple:
projectExplorer = new ProjectExplorer();
editorExplorer = new EditorExplorer();
favDownload = new FavDownload();
favDownloadExplorer = new FavDownloadExplorer();
//Define the listeners
addComponentListener(new ResizeListener());
horTopPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
horTopPane.setLeftComponent(projectExplorer);
horTopPane.setRightComponent(editorExplorer);
horBotPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
horBotPane.setLeftComponent(favDownload);
horBotPane.setRightComponent(favDownloadExplorer);
verticalPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
verticalPane.setTopComponent(horTopPane);
verticalPane.setBottomComponent(horBotPane);
setContentPane(verticalPane);
new Timer().schedule(new TimerTask() {
#Override
public void run() {
resizeComponents();
}
}, 100);
the resizeComponents method is
public void resizeComponents(){
int width = getWidth();
int height = getHeight();
horTopPane.setMinimumSize(new Dimension(width, (height/2)+(height/4)));
horTopPane.setSize(horTopPane.getMinimumSize());
horBotPane.setMinimumSize(new Dimension(width, (height/8)));
horBotPane.setSize(horBotPane.getMinimumSize());
projectExplorer.setMinimumSize(new Dimension(width/8, horTopPane.getHeight()));
projectExplorer.setSize(projectExplorer.getMinimumSize());
editorExplorer.setMinimumSize(new Dimension(width/2, horTopPane.getHeight()));
editorExplorer.setSize(editorExplorer.getMinimumSize());
favDownload.setMinimumSize(new Dimension(width/8, horBotPane.getHeight()));
favDownload.setSize(favDownload.getMinimumSize());
favDownloadExplorer.setMinimumSize(new Dimension(width/2, horBotPane.getHeight()));
favDownloadExplorer.setSize(favDownloadExplorer.getMinimumSize());
}
it started just as setSize, but for some reason it didn't resize them at all, then I putted setMinimumSize and it didn't resize it either, but when i move the elements a bit on the program they all go to its minimum size, am I missing something?
I've already made a few Java GUI programs, but this one just doesn't want to work properly.
What did I do wrong?
To start with, don't mess with setMinimum/Maximum/PreferredSize, have a look at Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing? for more details
Next, don't update the state of UI components from any thread other than the Event Dispatching Thread, Swing is not thread safe. java.util.Timer will trigger event notification within it's own thread context.
Next, consider overriding (at least), getPreferredSize from your custom components and return a default value, for example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class SplitPaneTest {
public static void main(String[] args) {
new SplitPaneTest();
}
public SplitPaneTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private final ProjectExplorer projectExplorer;
private final EditorExplorer editorExplorer;
private final FavDownload favDownload;
private final FavDownloadExplorer favDownloadExplorer;
private final JSplitPane horTopPane;
private final JSplitPane horBotPane;
private final JSplitPane verticalPane;
public TestPane() {
projectExplorer = new ProjectExplorer();
editorExplorer = new EditorExplorer();
favDownload = new FavDownload();
favDownloadExplorer = new FavDownloadExplorer();
horTopPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
horTopPane.setLeftComponent(projectExplorer);
horTopPane.setRightComponent(editorExplorer);
horBotPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
horBotPane.setLeftComponent(favDownload);
horBotPane.setRightComponent(favDownloadExplorer);
verticalPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
verticalPane.setTopComponent(horTopPane);
verticalPane.setBottomComponent(horBotPane);
setLayout(new BorderLayout());
add(verticalPane);
}
}
protected abstract class AbstractPane extends JPanel {
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public class ProjectExplorer extends AbstractPane {
public ProjectExplorer() {
setBackground(Color.RED);
}
}
public class EditorExplorer extends AbstractPane {
public EditorExplorer() {
setBackground(Color.BLUE);
}
}
public class FavDownload extends AbstractPane {
public FavDownload() {
setBackground(Color.MAGENTA);
}
}
public class FavDownloadExplorer extends AbstractPane {
public FavDownloadExplorer() {
setBackground(Color.CYAN);
}
}
}
If you have to modify the divider's location consider using JSplitSpane#setDividerLocation(double) or JSplitSpane#setDividerLocation(int)
Take a look at How to Use Split Panes for more details
I can't figure out why this simple program I wrote gets an IndexOutOfBounds exception when trying to update the coordinates of the mouse when the mouse leaves the tracking area (the white JPanel). I thought that the check on line 38 would take care of it. Any suggestions? Thanks!
import java.awt.*;
import javax.swing.JFrame;
public class MainFrame extends JFrame {
private static final long serialVersionUID = 1L;
Label coorLabel;
Panel coorPanel, content;
public MainFrame(String s){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cont = getContentPane();
coorLabel = new Label("Mouse Coordinates: ");
coorPanel = new Panel();
coorPanel.setPreferredSize(new Dimension(400,400));
coorPanel.setBackground(Color.WHITE);
/**
content = new Panel();
content.add(coorPanel, BorderLayout.PAGE_START);
content.add(coorLabel, BorderLayout.PAGE_END);
**/
cont.add(coorPanel, BorderLayout.PAGE_START);
cont.add(coorLabel, BorderLayout.PAGE_END);
pack();
setVisible(true);
}
public void updateCoor(){
if(coorPanel.getMousePosition()!=null){
coorLabel.setText("Mouse Coordinates: "+getMousePosition().x+", "+getMousePosition().y);
coorLabel.repaint();
}
}
public static void main(String[]args){
MainFrame frame = new MainFrame("Coor App");
while(true){
frame.updateCoor();
}
}
}
Take a look at Concurrency in Swing tutorial. You are completely hogging initial
thread with a while(true) loop and updating user interface outside of Event Dispatch Thread.
See Introduction to Event Listeners to get familiar with Swing event model and How to Write a Mouse-Motion Listener in particular for mouse motion listener example.
Here is what you should do:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.*;
public class Stack extends JFrame implements MouseMotionListener{
int x;
int y;
JPanel p = new JPanel();
JPanel detectPanel = new JPanel();
JTextField t = new JTextField(10);
JLabel l = new JLabel("Position's inside of bordered panel: ");
public Stack(){
setLayout(new BorderLayout());
t.setEditable(false);
p.add(l);
p.add(t);
detectPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
add(p,BorderLayout.NORTH);
add(detectPanel,BorderLayout.CENTER);
detectPanel.addMouseMotionListener(this);
}
public static void main(String[] a){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
Stack s = new Stack();
s.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
s.setLocationByPlatform(true);
s.setPreferredSize(new Dimension(640,480));
s.pack();
s.setVisible(true);
}
});
}
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
x= e.getX();
y= e.getY();
t.setText(x+", "+y);
}
}
You check to see if coorPanel.getMousePosition() is not null, but then reference (this.)getMouseLocation(); try changing that to just say getMousePosition in the check, and add a print:
if( this.getMousePosition() != null ){
System.out.println(getMousePosition());
coorLabel.setText("Mouse Coordinates: "+getMousePosition().x+", "+getMousePosition().y);
coorLabel.repaint();
}
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);
}
}