I have three buttons close,min and max.
When i want to max it then it will take the shape of the main container and overlaps all the panel and when i close it then only that panel gets affected. But when i hit the min button it gets minimized to the task bar which i do not want.
I want it inside conatiner like that of internalFrame when you click the minimize the button then it gets minimized inside the main frame.
here is the code
package Project;
import java.awt.Color;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
public class MinPanel {
public MinPanel() {
createAndShowGui();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MinPanel();
}
});
}
private void createAndShowGui() {
JFrame frame = new JFrame();
frame.setSize(300, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel mainPanel = new JPanel(new GridLayout(2, 2));
for (int i = 0; i < 4; i++) {
final int num = i;
OmniPanel op = new OmniPanel(mainPanel, frame) {
#Override
public JPanel createPanel() {
JPanel p = createSimplePanelInterface();
p.add(new JLabel("Panel " + (num + 1)));
return p;
}
#Override
void toPanel() {
super.toPanel();
System.out.println("Frame requested to be brought to panel");
}
};
mainPanel.add(op.getPanel());
}
frame.add(mainPanel);
//frame.pack();
frame.setVisible(true);
}
}
abstract class OmniPanel {
protected JFrame frame;
protected JPanel panel;
boolean maximized = false;
private final JComponent owner;
private final JFrame ownerFrame;
public OmniPanel(JComponent owner, JFrame con) {
this.owner = owner;
initOmniPanel();
this.ownerFrame = con;
}
private void initOmniPanel() {
panel = createPanel();
createFrame();
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowDeiconified(WindowEvent we) {
super.windowDeiconified(we);
toPanel();
}
});
}
public JPanel getPanel() {
return panel;
}
public JFrame getFrame() {
return frame;
}
public boolean goFrame() {
frame.add(panel);
frame.pack();
frame.setState(JFrame.ICONIFIED);
frame.setVisible(true);
return true;
}
protected void createFrame() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
void toPanel() {
frame.remove(panel);
frame.dispose();
owner.add(panel);
owner.revalidate();
owner.repaint();
}
public JPanel createSimplePanelInterface() {
JPanel p = new JPanel();
JButton close = new JButton("X");
JButton minimize = new JButton("_");
JButton maximize = new JButton("[]");
p.add(close);
p.add(minimize);
p.add(maximize);
close.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if (maximized) {
maximized = false;
ownerFrame.setGlassPane(new JComponent() {
});
ownerFrame.revalidate();
ownerFrame.repaint();
} else {
removePanelFromOwner();
getFrame().dispose();
}
}
});
minimize.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if (maximized) {
maximized = false;
ownerFrame.setGlassPane(new JComponent() {
});
owner.add(panel);
owner.revalidate();
owner.repaint();
ownerFrame.revalidate();
ownerFrame.repaint();
} else {
removePanelFromOwner();
goFrame();
frame.setState(Frame.ICONIFIED);
}
}
});
maximize.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if (maximized) {
return;
}
maximized = true;
removePanelFromOwner();
ownerFrame.setGlassPane(panel);
ownerFrame.revalidate();
ownerFrame.repaint();
panel.setVisible(true);//
}
});
p.setBorder(new LineBorder(Color.black));
return p;
}
private void removePanelFromOwner() {
owner.remove(getPanel());
owner.revalidate();
owner.repaint();
}
abstract JPanel createPanel();
}
I would suggest you to create an internalframe and then add buttons.If you do not want to add buttons then you make internalframe arguments true
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyVetoException;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.SwingUtilities;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane;
import javax.swing.plaf.basic.BasicInternalFrameUI;
public class MinPanel {
public MinPanel() throws HeadlessException, PropertyVetoException {
createAndShowGUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new MinPanel();
} catch (HeadlessException ex) {
} catch (PropertyVetoException ex) {
}
}
});
}
private void createAndShowGUI() throws HeadlessException, PropertyVetoException {
JFrame frame = new JFrame();
frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
final JDesktopPane jdp = new JDesktopPane() {
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
};
frame.setContentPane(jdp);
frame.pack();
createAndAddInternalFrame(jdp, 0, 0);
createAndAddInternalFrame(jdp, 200, 0);
frame.setVisible(true);
}
private void createAndAddInternalFrame(final JDesktopPane jdp, int x, int y) throws PropertyVetoException {
final JInternalFrame jInternalFrame = new JInternalFrame("Test1", false, false, false, false);
jInternalFrame.setLocation(x, y);
jInternalFrame.setLayout(new GridLayout(2, 2));
jInternalFrame.setSize(200, 200);//testing
JButton jb = new JButton("min");
jInternalFrame.add(jb);
jb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
try {
jInternalFrame.setIcon(true);
} catch (PropertyVetoException ex) {
}
}
});
BasicInternalFrameTitlePane titlePane = (BasicInternalFrameTitlePane) ((BasicInternalFrameUI) jInternalFrame.getUI()).getNorthPane();
jInternalFrame.remove(titlePane);
jInternalFrame.setVisible(true);
jdp.add(jInternalFrame);
}
}
Related
I am working on a simple paint app in Java, when I choose a color the button background changes perfectly, but the returned color is always the previous one.
For example, if I choose black then blue, it will paint in black.And if I choose another color after blue it will paint in Blue.
public class ColorChooserBtn extends JButton {
private Color color;
public ColorChooserBtn() {
super();
this.setBackground(Color.BLACK);
this.setPreferredSize(new Dimension(16, 16));
this.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
Color c = JColorChooser.showDialog(null, "Choose a Color", color);
if (c != null){
setSelectedColor(c);
setBackground(color);
}
}
});
}
public Color getSelectedColor() {
return color;
}
public void setSelectedColor(Color newColor) {
color = newColor;
}
}
public class Paint {
DrawArea drawArea;
JButton clearBtn;
ColorChooserBtn colorBtn;
ActionListener actionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == clearBtn){
drawArea.clear();
} else if(e.getSource() == colorBtn){
drawArea.coloring(colorBtn.getSelectedColor());
}
}
};
public Paint() {
JFrame frame = new JFrame("Paint");
frame.getContentPane().setLayout(new BorderLayout());
drawArea = new DrawArea();
frame.getContentPane().add(drawArea, BorderLayout.CENTER);
JPanel controls = new JPanel();
clearBtn = new JButton("Clear");
clearBtn.addActionListener(actionListener);
colorBtn = new ColorChooserBtn();
colorBtn.addActionListener(actionListener);
controls.add(clearBtn);
controls.add(colorBtn);
frame.getContentPane().add(controls,BorderLayout.NORTH);
frame.setSize(600, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
new Paint();
}
}
The problem is the order in which the ActionListener's are notified. Generally, Swing calls listens in LIFO order
So, using the following code, with some additional System.outs...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
ColorChooserBtn btn = new ColorChooserBtn();
add(btn);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Get color");
System.out.println(btn.getSelectedColor());
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public class ColorChooserBtn extends JButton {
private Color color;
public ColorChooserBtn() {
super();
this.setBackground(Color.BLACK);
this.setPreferredSize(new Dimension(16, 16));
this.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Choose color");
Color c = JColorChooser.showDialog(null, "Choose a Color", color);
if (c != null) {
setSelectedColor(c);
setBackground(color);
}
}
});
}
public Color getSelectedColor() {
return color;
}
public void setSelectedColor(Color newColor) {
color = newColor;
}
}
}
prints...
Get color
null
Choose color
This means that the ActionListener used to "get" the selected color from the button is called first, before the ActionListener which is used to actually select the color
One, possible, solution might be to use a PropertyChangeListener and trigger a propertyChanged event when the selectedColor is changed, for example...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
ColorChooserBtn btn = new ColorChooserBtn();
add(btn);
btn.addPropertyChangeListener("selectedColor", new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
System.out.println("Changed");
System.out.println(evt.getNewValue());
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public class ColorChooserBtn extends JButton {
private Color color;
public ColorChooserBtn() {
super();
this.setBackground(Color.BLACK);
this.setPreferredSize(new Dimension(16, 16));
this.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Choose color");
Color c = JColorChooser.showDialog(null, "Choose a Color", color);
if (c != null) {
setSelectedColor(c);
setBackground(color);
}
}
});
}
public Color getSelectedColor() {
return color;
}
public void setSelectedColor(Color newColor) {
if (newColor != color) {
Color oldColor = color;
color = newColor;
firePropertyChange("selectedColor", oldColor, newColor);
}
}
}
}
I'm trying to make a Russian Roulette game and I'm trying to change the JLabel to the gif of the revolver spinning. However, I can change it from the gif but not back to the picture of the revolver. Or is there a way to play the gif only once and have it stop then change it to another gif?
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class RussianRoulette extends JFrame {
private int Chamber;
private int BulletPos;
private boolean ButtonToggle;
JButton Fire = new JButton("Fire");
JButton Spin = new JButton("Spin");
JLabel Gun = new JLabel();
public RussianRoulette() {
ButtonToggle = true;
Chamber = (int) (Math.random() * 6 + 1);
BulletPos = 0;
JFrame frame = new JFrame();
frame.getContentPane().setLayout(null);
Gun.setBounds(0, 0, 500, 375);
Fire.setBounds(25, 375, 100, 100);
Spin.setBounds(350, 375, 100, 100);
ImageIcon imgThisImg = new ImageIcon("Revolver2.png");
Gun.setIcon(imgThisImg);
Spin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
spinGun();
sleep(600);
}
});
Fire.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
fireGun();
}
});
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.add(Gun);
frame.add(Fire);
frame.add(Spin);
frame.setResizable(true);
frame.setSize(500, 500);
Image im = Toolkit.getDefaultToolkit().getImage("icon.png");
frame.setIconImage(im);
frame.setVisible(true);
frame.setResizable(false);
frame.setTitle("Russian Roulette");
}
public void spinGun() {
ImageIcon imgThisImg = new ImageIcon("SpinRevolver.gif");
Gun.setIcon(imgThisImg);
sleep(600);
AudioPlayer player3 = new AudioPlayer("Spin.wav");
player3.play();
BulletPos = (int) (Math.random() * 6 + 1);
}
public void fireGun() {
if (ButtonToggle == false) {
AudioPlayer player5 = new AudioPlayer("Click.wav");
player5.play();
}
if (Chamber == BulletPos && ButtonToggle == true) {
AudioPlayer player2 = new AudioPlayer("Shot.wav");
player2.play();
ButtonToggle = false;
} else {
Chamber++;
CheckNum();
AudioPlayer player = new AudioPlayer("Click.wav");
player.play();
}
}
public void CheckNum() {
if (Chamber > 6) {
Chamber = 1;
}
}
public void reload()
{
//play reload animation
ButtonToggle = true;
}
public void sleep(int ammount)
{
try {
Thread.sleep(ammount);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
So, based on feedback, you want the animation to start running on a button click and stop automatically after a given period of time...
Probably the simplest solution would be to use a javax.swing.Timer, otherwise you'll need to set yourself up as some kind of ImageObserver and interrupt the various events coming from the image...like I said, simpler...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class SpiningLabel {
public static void main(String[] args) {
new SpiningLabel();
}
public SpiningLabel() {
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 ImageIcon spin;
private ImageIcon still;
private JLabel label;
private Timer timer;
private JButton button;
public TestPane() {
spin = new ImageIcon("spin.gif");
still = new ImageIcon("still.png");
label = new JLabel(still);
button = new JButton("Allons-y!");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
label.setIcon(spin);
button.setEnabled(false);
timer.restart();
}
});
timer = new Timer(2000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
label.setIcon(still);
button.setEnabled(true);
}
});
timer.setRepeats(false);
setLayout(new BorderLayout());
add(label);
add(button, BorderLayout.SOUTH);
}
}
}
For Example:
When JButton1 click JInternalFrame1 Show on the JDesktopPane
And when JButton2 Click JInternalFrame1 Close and JInternalFrame2 Show on the JDesktopPane.
thx before
Edit: with code from comment
if (JInternalFrame1 == null) {
JInternalFrame1 = new FJInternalFrame();
Desktop.add(JInternalFrame1);
JInternalFrame1.toFront();
} else {
JInternalFrame1.dispose();
}
Take a look at this example. I created a custom JInternalFrame that has a different title every time you create a new frame. when you click on the button, a new one is created and the old one disapears
Here is the important code that may help you out. I add a new frame if the desktop size is equal to 0, other wise I remove the previous one, add a new frame, and revalidate
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (desktop.getAllFrames().length == 0) {
desktop.add(new MyInternalFrame());
} else {
desktop.remove(0);
desktop.add(new MyInternalFrame());
revalidate();
repaint();
}
}
});
Here is the complete code. It's two different files.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class InternalFrameDemo1 extends JPanel {
JDesktopPane desktop;
JButton button;
public InternalFrameDemo1() {
desktop = new JDesktopPane();
button = new JButton("Get Next Frame");
setLayout(new BorderLayout());
add(desktop, BorderLayout.CENTER);
add(button, BorderLayout.SOUTH);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (desktop.getAllFrames().length == 0) {
desktop.add(new MyInternalFrame());
} else {
desktop.remove(0);
desktop.add(new MyInternalFrame());
revalidate();
repaint();
}
}
});
}
public static void createAndShowGui() {
JFrame frame = new JFrame();
frame.add(new InternalFrameDemo1());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.pack();
frame.setVisible(true);
}
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
import javax.swing.JInternalFrame;
public class MyInternalFrame extends JInternalFrame {
static int openFrameCount = 0;
static final int xOffset = 30, yOffset = 30;
public MyInternalFrame() {
super("Document #" + (++openFrameCount),
true, //resizable
true, //closable
true, //maximizable
true);//iconifiable
setSize(300,300);
setLocation(xOffset*openFrameCount, yOffset*openFrameCount);
setVisible(true);
}
}
In my application I have a JTable where I mapped a Key event. The source:
getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "selectNextColumnCell");
getActionMap().put("selectNextColumnCell", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
//DO SOMETHING
}
});
}
But this action is only called when I press the enter key and don't release it. But I need call this action every time when the user type the enter key.
please see my syntax for put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER....
for example
import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
public class FullScreen {
private static final long serialVersionUID = 1L;
private GraphicsDevice device;
private JButton button = new JButton("Close Meeee");
private JPanel myPanel = new JPanel();
private JFrame frame = new JFrame();
public FullScreen() {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
myPanel.setFocusable(true);
myPanel.add(button);
frame.add(myPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setUndecorated(true);
frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke("ENTER"), "clickENTER");
frame.getRootPane().getActionMap().put("clickENTER", new AbstractAction() {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
exitFullScreen();
}
});
enterFullScreen();
frame.setVisible(true);
// code line for #MOD
// from http://stackoverflow.com/questions/15152297/how-to-get-extendedstate-width-of-jframe
Runnable doRun = new Runnable() {
#Override
public void run() {
System.out.println(frame.getBounds());
}
};
SwingUtilities.invokeLater(doRun);
}
private void enterFullScreen() {
GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
device = graphicsEnvironment.getDefaultScreenDevice();
if (device.isFullScreenSupported()) {
device.setFullScreenWindow(frame);
frame.validate();
}
}
private void exitFullScreen() {
device.setFullScreenWindow(null);
myPanel.setPreferredSize(new Dimension(400, 300));
frame.pack();
}
public static void main(String[] args) {
Runnable doRun = new Runnable() {
#Override
public void run() {
FullScreen fullScreen = new FullScreen();
}
};
SwingUtilities.invokeLater(doRun);
}
}
I'm trying to make a JPanel go full screen when you click a button, and back again when you press escape.
I've managed to get the window to go full screen, but because of the whole thing about adding components removing them from other containers, I end up with a blank JPanel.
I chose to make a separate JFrame to render full screen, the class of which is as follows (note that this is an inner class, so myPanel refers to a panel that already exists in MyJFrame):
public class FullScreen extends JFrame {
private static final long serialVersionUID = 1L;
private GraphicsDevice device;
private boolean isFullScreen;
public FullScreen() {
this.setContentPane(myPanel);
this.setUndecorated(true);
// Fullscreen return
this.addKeyListener(new KeyListener() {
#Override
public void keyPressed(KeyEvent e) {
// Exit fullscreen when ESC pressed
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
exitFullScreen();
}
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
}
});
}
public void enterFullScreen() {
if (!isFullScreen) {
// Get the current device
GraphicsEnvironment graphicsEnvironment =
GraphicsEnvironment.getLocalGraphicsEnvironment();
device = graphicsEnvironment.getDefaultScreenDevice();
if (device.isFullScreenSupported()) {
// Make the current window invisible
MyJFrame.this.setVisible(false);
// Set the full screen window
device.setFullScreenWindow(this);
isFullScreen = true;
}
}
}
public void exitFullScreen() {
if (isFullScreen) {
// Reset the full screen window
device.setFullScreenWindow(null);
MyJFrame.this.setVisible(true);
isFullScreen = false;
}
}
}
Any other bright ideas on how to accomplish this?
Something like this seems to do it alright (to be improved and adapted):
import java.awt.BorderLayout;
import java.awt.Container;
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.JPanel;
import javax.swing.SwingUtilities;
class TestFullScreenPanel {
private static class FSPanel implements ActionListener {
private JPanel panel;
private JButton button;
private boolean fullScreen = false;
private Container previousContentPane;
public FSPanel(String label) {
panel = new JPanel(new BorderLayout());
button = new JButton(label);
button.addActionListener(this);
panel.add(button);
}
public JComponent getComponent() {
return panel;
}
#Override
public void actionPerformed(ActionEvent e) {
if (!fullScreen) {
goFullScreen();
} else {
ungoFullScreen();
}
}
private void goFullScreen() {
Window w = SwingUtilities.windowForComponent(button);
if (w instanceof JFrame) {
JFrame frame = (JFrame) w;
frame.dispose();
frame.setUndecorated(true);
frame.getGraphicsConfiguration().getDevice().setFullScreenWindow(w);
previousContentPane = frame.getContentPane();
frame.setContentPane(button);
frame.revalidate();
frame.repaint();
frame.setVisible(true);
fullScreen = true;
}
}
private void ungoFullScreen() {
Window w = SwingUtilities.windowForComponent(button);
if (w instanceof JFrame) {
JFrame frame = (JFrame) w;
frame.dispose();
frame.setUndecorated(false);
frame.getGraphicsConfiguration().getDevice().setFullScreenWindow(null);
frame.setContentPane(previousContentPane);
panel.add(button);
frame.revalidate();
frame.repaint();
frame.setVisible(true);
fullScreen = false;
}
}
}
TestFullScreenPanel() {
final JFrame f = new JFrame(TestFullScreenPanel.class.getSimpleName());
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.add(new FSPanel("Center").getComponent(), BorderLayout.CENTER);
f.add(new FSPanel("North").getComponent(), BorderLayout.NORTH);
f.add(new FSPanel("South").getComponent(), BorderLayout.SOUTH);
f.add(new FSPanel("West").getComponent(), BorderLayout.WEST);
f.add(new FSPanel("East").getComponent(), BorderLayout.EAST);
f.setSize(800, 600);
f.setLocationByPlatform(true);
f.setVisible(true);
}
public static void main(String[] args) {
// start the GUI on the EDT
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestFullScreenPanel();
}
});
}
}
PS: disposal of the JFrame is only there to change the setUndecorated state.
don't extend JFrame, create this Object an local variable
JFrame by default never react to the KeyEvents, set KeyListener to the JPanel
don't to use KeyListener for Swing JComponents, otherwise have to JPanel#setFocusable
use KeyBindings instead of KeyListener
use Escape by #camickr
.
import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
public class FullScreen {
private static final long serialVersionUID = 1L;
private GraphicsDevice device;
private JButton button = new JButton("Close Meeee");
private JPanel myPanel = new JPanel();
private JFrame frame = new JFrame();
public FullScreen() {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
myPanel.setFocusable(true);
myPanel.add(button);
frame.add(myPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setUndecorated(true);
frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke("ENTER"), "clickENTER");
frame.getRootPane().getActionMap().put("clickENTER", new AbstractAction() {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
exitFullScreen();
}
});
enterFullScreen();
frame.setVisible(true);
// code line for #MOD
// from http://stackoverflow.com/questions/15152297/how-to-get-extendedstate-width-of-jframe
Runnable doRun = new Runnable() {
#Override
public void run() {
System.out.println(frame.getBounds());
}
};
SwingUtilities.invokeLater(doRun);
}
private void enterFullScreen() {
GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
device = graphicsEnvironment.getDefaultScreenDevice();
if (device.isFullScreenSupported()) {
device.setFullScreenWindow(frame);
frame.validate();
}
}
private void exitFullScreen() {
device.setFullScreenWindow(null);
myPanel.setPreferredSize(new Dimension(400, 300));
frame.pack();
}
public static void main(String[] args) {
Runnable doRun = new Runnable() {
#Override
public void run() {
FullScreen fullScreen = new FullScreen();
}
};
SwingUtilities.invokeLater(doRun);
}
}
Here's my class built into an example that works very nicely. I'm sure I'm not disposing and validating the frame properly so please comment on it so I can update it.
public class FullScreenExample extends JFrame {
public class FullScreen {
private GraphicsDevice device;
private JFrame frame;
private boolean isFullScreen;
public FullScreen() {
frame = new JFrame();
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
frame.setContentPane(content);
frame.setUndecorated(true);
// Full screen escape
frame.addKeyListener(new KeyListener() {
#Override
public void keyPressed(KeyEvent e) {
// Exit full screen when ESC pressed
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
exitFullScreen();
}
}
#Override
public void keyReleased(KeyEvent e) {}
#Override
public void keyTyped(KeyEvent e) {}
});
}
public void enterFullScreen() {
if (!isFullScreen) {
// Get the current device
GraphicsConfiguration config = FullScreenExample.this.getGraphicsConfiguration();
device = config.getDevice();
// Remove the panel from the wrapper
myWrapper.remove(myPanel);
// Add the panel to the full screen frame
frame.getContentPane().add(myPanel);
// Set the full screen window
device.setFullScreenWindow(frame);
isFullScreen = true;
}
}
public void exitFullScreen() {
if (isFullScreen) {
// Remove the fractal from the full screen frame
frame.getContentPane().remove(myPanel);
// Add the panel back to the wrapper
myWrapper.add(myPanel);
// Disable full screen
device.setFullScreenWindow(null);
// Dispose frame
frame.dispose();
// Revalidate window
FullScreenExample.this.validate();
isFullScreen = false;
}
}
}
/*
* This example uses a main content panel, myPanel
* and a wrapper to host the panel in the main JFrame, myWrapper.
*/
private JPanel myPanel, myWrapper;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
FullScreenExample frame = new FullScreenExample();
frame.init();
frame.setVisible(true);
}
});
}
public void init() {
// Generate example main window
JPanel content = new JPanel();
content.setBorder(new EmptyBorder(5, 5, 5, 5));
content.setLayout(new BorderLayout());
this.setContentPane(content);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myPanel = new JPanel();
myPanel.setBackground(Color.BLUE);
// Full screen button and listener
JButton fullscreen = new JButton("Full Screen");
final FullScreen fs = new FullScreen();
fullscreen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
fs.enterFullScreen();
}
});
myWrapper = new JPanel();
myWrapper.setLayout(new BorderLayout());
myWrapper.add(myPanel);
content.add(myWrapper, BorderLayout.CENTER);
content.add(fullscreen, BorderLayout.SOUTH);
this.setBounds(100, 100, 350, 350);
}
}