I'm doing a program in java, and I want pass at the new window when I click the button but when I run the program it automatically open me the 2 views also if I don't press the button.What can I do for fix this problem?
Main:
package com.SimplyGeometry.src.tiles;
import com.SimplyGeometry.src.windows.SelectWindow;
import com.SimplyGeometry.src.windows.StartWindow;
public class Main {
public static void main(String[] args) {
String title = "SimplyGeometry";
int WIDTH = 1320, HEIGHT = 840;
StartWindow stw = new StartWindow(/*WIDTH, HEIGHT, title*/);
}
}
Vew1:
package com.SimplyGeometry.src.windows;
import javax.swing.*;
import Actions.Actions;
public class StartWindow implements ActionListener {
public static JFrame window;
SelectWindow sw;
public StartWindow(/*int WIDTH, int HEIGHT, String title*/) {
window = new JFrame("SimplyGeometry");
window.setPreferredSize(new Dimension(1320, 840));
window.setMaximumSize(new Dimension(1320, 840));
window.setMinimumSize(new Dimension(1320, 840));
window.setLocationRelativeTo(null);
window.setResizable(false);
JPanel panel = new JPanel();
panel.setLayout(null);
panel.setBounds(0, 0, 1320, 840);
panel.setBackground(Color.CYAN);
JLabel label = new JLabel();
label.setIcon(new ImageIcon("/Users/gaetanodonnarumma/Documents/workspace/SimplyGeometry(Complete)/src/Images/titolo.png"));
label.setSize(650, 250);
label.setLocation(320, 100);
JButton button = new JButton("Start");
button.setBackground(Color.white);
button.setForeground(Color.black);
button.setSize(350, 100);
button.setLocation(455, 450);
button.setEnabled(true);
button.addActionListener(new Actions());
window.add(panel);
panel.add(label);
window.validate();
panel.add(button);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
View 2:
package com.SimplyGeometry.src.windows;
import java.awt.Dimension;
import javax.swing.*;
public class SelectWindow {
public static JFrame window;
public SelectWindow(/*int WIDTH, int HEIGHT, String title*/) {
window = new JFrame("SimplyGeometry");
window.setPreferredSize(new Dimension(1320, 840));
window.setMaximumSize(new Dimension(1320, 840));
window.setMinimumSize(new Dimension(1320, 840));
window.setLocationRelativeTo(null);
window.setLayout(null);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
the actionListener class:
package Actions;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import com.SimplyGeometry.src.windows.SelectWindow;
import com.SimplyGeometry.src.windows.StartWindow;
public class Actions implements ActionListener {
public Actions() {
SelectWindow window = new SelectWindow();
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
It is happening because of the line below:
public StartWindow(
...
button.addActionListener(new Actions());
...
}
In the constructor of the Actions, SelectWindow is creating. So it is coming to the screen after you create StartWindow.
public Actions() {
SelectWindow window = new SelectWindow();
}
To solve the problem create SelectWindow in actionPerformed.
public class Actions implements ActionListener {
public Actions() {
//SelectWindow window = new SelectWindow();
}
#Override
public void actionPerformed(ActionEvent e) {
SelectWindow window = new SelectWindow();
}
}
Related
Mouse event appears not to work, and i can't find out, why.
I added a debug output at imgEdit.drawDot and there's no output at the console. I'm a newbie in java, so my code may seem to be very bad, as well as my english
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
/**
* Created by doctor on 12/29/15.
*/
public class MainUI {
Window mainWindow;
MainUI() {
mainWindow = new Window();
}
}
class Window extends JFrame {
Window() {
setBounds(0, 0, 600, 400);
setTitle("RebBrush");
Panel mainPanel = new Panel();
Container mainCont = getContentPane();
mainCont.setLayout(null);
mainCont.add(mainPanel);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
class Panel extends JPanel {
private ImageEdit imgEdit;
private JLabel imgLabel;
Panel() {
setLayout(null);
imgEdit = new ImageEdit(600, 400);
imgLabel = new JLabel(new ImageIcon(imgEdit.getImage()));
imgLabel.setBounds(0, 0, 600, 400);
add(imgLabel);
addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent e) {
imgEdit.drawDot(e.getX(), e.getY());
}
#Override
public void mouseMoved(MouseEvent e) {
}
});
}
}
Simply getting rid of the null layouts did the trick for me. I'm not sure what ImageEdit is (some other class you've defined?), but by running the following I see "Mouse Dragged" show up in the console, so the mouseDragged method is definitely being called. Just uncomment the imageEdit stuff to put it back in.
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
/**
* Created by doctor on 12/29/15.
*/
public class MainUI {
Window mainWindow;
MainUI() {
mainWindow = new Window();
}
public static void main(String[] args) {
new MainUI();
}
}
class Window extends JFrame {
Window() {
setBounds(0, 0, 600, 400);
setTitle("RebBrush");
Panel mainPanel = new Panel();
Container mainCont = getContentPane();
mainCont.add(mainPanel);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
class Panel extends JPanel {
//private ImageEdit imgEdit;
private JLabel imgLabel;
Panel() {
//imgEdit = new ImageEdit(600, 400);
//imgLabel = new JLabel(new ImageIcon(imgEdit.getImage()));
//imgLabel.setBounds(0, 0, 600, 400);
//add(imgLabel);
addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent e) {
System.out.println("Mouse Dragged");
//imgEdit.drawDot(e.getX(), e.getY());
}
#Override
public void mouseMoved(MouseEvent e) {
}
});
}
}
I have two frames with contents . The first one has a jlabel and jbutton which when it is clicked it will open a new frame. I need to repaint the first frame or the panel that has the label by adding another jlabel to it when the second frame is closed.
//Edited
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class FirstFrame extends JPanel implements KeyListener{
private static String command[];
private static JButton ok;
private static int count = 1;
private static JTextField text;
private static JLabel labels[];
private static JPanel p ;
private static JFrame frame;
public int getCount(){
return count;
}
public static void createWindow(){
JFrame createFrame = new JFrame();
JPanel panel = new JPanel(new GridLayout(2,1));
text = new JTextField (30);
ok = new JButton ("Add");
ok.requestFocusInWindow();
ok.setFocusable(true);
panel.add(text);
panel.add(ok);
text.setFocusable(true);
text.addKeyListener(new FirstFrame());
createFrame.add(panel);
createFrame.setVisible(true);
createFrame.setSize(600,300);
createFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
createFrame.setLocationRelativeTo(null);
createFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
System.out.println(command[count]);
if(command[count] != null){
p.add(new JLabel("NEW LABEL"));
p.revalidate();
p.repaint();
count++;
System.out.println(count);
}
}
});
if(count >= command.length)
count = 1;
ok.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(command[count] == null)
command[count] = text.getText();
else
command[count] = command[count]+", "+text.getText();
text.setText("");
}
});
}
public FirstFrame(){
p = new JPanel();
JButton create = new JButton ("CREATE");
command = new String[2];
labels = new JLabel[2];
addKeyListener(this);
create.setPreferredSize(new Dimension(200,100));
//setLayout(new BorderLayout());
p.add(new JLabel("dsafsaf"));
p.add(create);
add(p);
//JPanel mainPanel = new JPanel();
/*mainPanel.setFocusable(false);
mainPanel.add(create);
*/
create.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
createWindow();
}
});
//add(mainPanel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
frame = new JFrame();
frame.add(new FirstFrame());
frame.setVisible(true);
frame.pack();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER)
if(ok.isDisplayable()){
ok.doClick();
return;}
}
}
}
});
}
}
As per my first comment, you're better off using a dialog of some type, and likely something as simple as a JOptionPane. For instance in the code below, I create a new JLabel with the text in a JTextField that's held by a JOptionPane, and then add it to the original GUI:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class FirstPanel2 extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = 300;
private JTextField textField = new JTextField("Hovercraft rules!", 30);
private int count = 0;
public FirstPanel2() {
AddAction addAction = new AddAction();
textField.setAction(addAction);
add(textField);
add(new JButton(addAction));
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class AddAction extends AbstractAction {
public AddAction() {
super("Add");
}
#Override
public void actionPerformed(ActionEvent e) {
String text = textField.getText();
final JTextField someField = new JTextField(text, 10);
JPanel panel = new JPanel();
panel.add(someField);
int result = JOptionPane.showConfirmDialog(FirstPanel2.this, panel, "Add Label",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
JLabel label = new JLabel(someField.getText());
FirstPanel2.this.add(label);
FirstPanel2.this.revalidate();
FirstPanel2.this.repaint();
}
}
}
private static void createAndShowGui() {
FirstPanel2 mainPanel = new FirstPanel2();
JFrame frame = new JFrame("My 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();
}
});
}
}
Also, don't add KeyListeners to text components as that is a dangerous and unnecessary thing to do. Here you're much better off adding an ActionListener, or as in my code above, an Action, so that it will perform an action when the enter key is pressed.
Edit
You ask:
Just realized it is because of the KeyListener. Can you explain please the addAction ?
This is functionally similar to adding an ActionListener to a JTextField, so that when you press enter the actionPerformed(...) method will be called, exactly the same as if you pressed a JButton and activated its ActionListener or Action. An Action is like an "ActionListener" on steroids. It not only behaves as an ActionListener, but it can also give the button its text, its icon and other properties.
after looking for an answer for 3 hours, I am just about to give up on this idea:
I am making an application that displays the followers of a Twitch streamer.
A couple of features i am trying to add:
the display frame is a separate window from the controls frame.
I am trying to use (JFrame as display window) (JDialog as controls frame)
And furthermore: Settings is in another JDialog (this one has Modal(true))
Settings needs to be able to send the JFrame information such as: "username" and "text color"
And the settings JDialog will only pop up from clicking "settings" on the controls JDialog.
It will setVisible(false) when you click "save settings" or the X.
On the controls JDialog (b_console) needs to receive error messages and info like that.
And on the same JDialog, "filler" needs to receive follower count and things like that.
Here follows my code involving the transfers listed above:
package javafollowernotifier;
import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics.*;
import javax.swing.*;
import java.io.*;
import java.net.URL;
public class JavaFollowerNotifier extends JFrame implements ComponentListener
{
Settings settings = new Settings();
ControlPanel ctrlPnl = new ControlPanel();
public JavaFollowerNotifier()
{
try
{
settings.readSettings();
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
}
public void grabFollower()
{
ctrlPnl.b_console.setText("Retrieving Info...");
try
{
URL twitch = new URL("https://api.twitch.tv/kraken/channels/" + savedSettings[1] + "/follows?limit=1&offset=0");
ctrlPnl.b_console.setText("Retrieved");
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
}
public void grabStats()
{
ctrlPnl.b_console.setText("Retrieving Info...");
try
{
URL twitch = new URL("https://api.twitch.tv/kraken/channels/" + savedSettings[1] + "/follows?limit=1&offset=0");
ctrlPnl.filler.setText("Followers: " + totalFollowers + "\nLatest: " + lastFollower);
ctrlPnl.b_console.setText("Retrieved");
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
}
public void componentMoved(ComponentEvent arg0)
{
//this is only to *attach this JDialog to the JFrame and make it move together my plan is to have it undecorated as well
int x = this.getX() + this.getWidth();
int y = this.getY();
ctrlPnl.movePanel(x, y);
}
public void paint(Graphics g)
{
if(clearPaint == false)
{
//any "savedSettings[n]" are saved in Settings.java (just not in this version)
g.setColor(Color.decode(savedSettings[3]));
scaledFont = scaleFont(follower + " followed!", bounds, g, new Font(savedSettings[2], Font.PLAIN, 200));
}
}
}
package javafollowernotifier;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Settings extends JDialog implements ActionListener
{
JavaFollowerNotifier jfollow = new JavaFollowerNotifier();
ControlPanel ctrlPnl = new ControlPanel();
//here are the settings mention above
String[] savedSettings = {"imgs/b_b.jpg","username","font","color","Nightbot"};
public Settings()
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
}
public void saveSettings()
{
savedSettings[4] = jfollow.lastFollower;
try
{
PrintWriter save = new PrintWriter("config.cfg");
ctrlPnl.b_console.setText("Saving...");
for(int i = 0; i < 5; i++)
{
save.println(savedSettings[i]);
}
save.close();
ctrlPnl.b_console.setText("Saved");
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
canClose = false;
}
readSettings();
this.repaint();
}
public void readSettings()
{
ctrlPnl.b_console.setText("Loading...");
try
{
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
jfollow.lastFollower = savedSettings[4];
try
{
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
ctrlPnl.b_console.setText("Loaded Settings");
}
}
package javafollowernotifier;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ControlPanel extends JDialog implements ActionListener
{
public ControlPanel()
{
try
{
}
catch (Exception e)
{
b_console.setText("Error");
System.out.println(e);
}
}
public void movePanel(int x, int y)
{
//here is where i *attach the JDialog to the JFrame
controlPanel.setLocation(x, y);
}
public void actionPerformed(ActionEvent ie)
{
if(ie.getSource() == b_settings)
{
settings.frame.setVisible(true);
}
}
}
I tried to fix your program, but I wasn't too sure about its flow. So I created another simple one. What I did was pass the labels from the main frame to the dialogs' constructors. In the dialog, I took those labels and changed them with text entered in their text fields. If you hit enter after writing text from the dialog, you'll see the text in the frame change
public class JavaFollowerNotifier1 extends JFrame{
private JLabel controlDialogLabel = new JLabel(" ");
private JLabel settingDialogLabel = new JLabel(" ");
private ControlDialog control;
private SettingsDialog settings;
public JavaFollowerNotifier1() {
control = new ControlDialog(this, true, controlDialogLabel);
settings = new SettingsDialog(this, true, settingDialogLabel);
....
class ControlDialog extends JDialog {
private JLabel label;
public ControlDialog(final Frame frame, boolean modal, final JLabel label) {
super(frame, modal);
this.label = label;
....
class SettingsDialog extends JDialog {
private JLabel label;
public SettingsDialog(final Frame frame, boolean modal, final JLabel label) {
super(frame, modal);
this.label = label;
Test it out and let me know if you have any questions
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class JavaFollowerNotifier1 extends JFrame{
private JLabel controlDialogLabel = new JLabel(" ");
private JLabel settingDialogLabel = new JLabel(" ");
private JButton showControl = new JButton("Show Control");
private JButton showSetting = new JButton("Show Settings");
private ControlDialog control;
private SettingsDialog settings;
public JavaFollowerNotifier1() {
control = new ControlDialog(this, true, controlDialogLabel);
settings = new SettingsDialog(this, true, settingDialogLabel);
showControl.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
control.setVisible(true);
}
});
showSetting.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
settings.setVisible(true);
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(showControl);
buttonPanel.add(showSetting);
add(buttonPanel, BorderLayout.SOUTH);
add(controlDialogLabel, BorderLayout.NORTH);
add(settingDialogLabel, BorderLayout.CENTER);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new JavaFollowerNotifier1();
}
});
}
}
class ControlDialog extends JDialog {
private JLabel label;
private JTextField field = new JTextField(15);
private JButton button = new JButton("Close");
private String s = "";
public ControlDialog(final Frame frame, boolean modal, final JLabel label) {
super(frame, modal);
this.label = label;
setLayout(new BorderLayout());
add(field, BorderLayout.NORTH);
add(button, BorderLayout.CENTER);
pack();
setLocationRelativeTo(frame);
field.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
s = field.getText();
label.setText("Message from Control Dialog: " + s);
}
});
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
ControlDialog.this.setVisible(false);
}
});
}
}
class SettingsDialog extends JDialog {
private JLabel label;
private JTextField field = new JTextField(15);
private JButton button = new JButton("Close");
private String s = "";
public SettingsDialog(final Frame frame, boolean modal, final JLabel label) {
super(frame, modal);
this.label = label;
setLayout(new BorderLayout());
add(field, BorderLayout.NORTH);
add(button, BorderLayout.CENTER);
pack();
setLocationRelativeTo(frame);
field.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
s = field.getText();
label.setText("Message from Settings Dialog: " + s);
}
});
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
SettingsDialog.this.setVisible(false);
}
});
}
}
Typically when I build GUI's which use modal dialogs to gather user input, I build my own class, which extends the JDialog or in some cases a JFrame. In that class I expose a getter method for an object which I usually call DialgResult. This object acts as the Model for the input I gather from the user. In the class that has the button, or whatever control which triggers asking the user for the information, I create it, show it as a modal dialog, then when it is closed, I retrieve the object using that same getter.
This is a very primitive example:
package arg;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class asdfas extends JFrame {
public static void main(String[] args) {
asdfas ex = new asdfas();
ex.setVisible(true);
}
public asdfas() {
init();
}
private void init() {
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setBounds(100,100,200,200);
final JButton button = new JButton("Show modal dialog");
button.addActionListener( new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Dialog d = new Dialog();
d.setVisible(true);
button.setText(d.getDialogResult().value);
revalidate();
repaint();
}
});
this.add(button);
}
class DialogResult {
public String value;
}
class Dialog extends JDialog {
JTextField tf = new JTextField(20);
private DialogResult result = new DialogResult();
public Dialog() {
super();
init();
}
private void init() {
this.setModal(true);
this.setSize(new Dimension(100,100));
JButton ok = new JButton("ok");
ok.addActionListener( new ActionListener () {
#Override
public void actionPerformed(ActionEvent arg0) {
result = new DialogResult();
result.value = tf.getText();
setVisible(false);
}
});
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
p.add(tf);
p.add(ok);
this.add(p);
}
public DialogResult getDialogResult() {
return result;
}
}
}
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);
}
}
I am trying to remove a JPanel not hide it but i can't find anything that works.
This is the code in the panel that needs to remove itself when a button is pressed:
play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Frame frame = new Frame(); //referencing to my JFrame class (this class is a JPanel)
//need to remove this panel on this line
frame.ThreeD(); // adds a new panel
}
});
UPDATED
This is the full code:
package ThreeD;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.UIManager;
import Run.Frame;
public class Launcher extends JPanel{
private JButton play, options, help, mainMenu;
private Rectangle rplay, roptions, rhelp, rmainMenu;
private int buttonWidthLocation, buttonWidth, buttonHeight;
private int width = 1280;
public Launcher() {
this.setLayout(null);
drawButtons();
}
private void drawButtons() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
e.printStackTrace();
}
play = new JButton("Play");
options = new JButton("Options");
help = new JButton("Help");
mainMenu = new JButton("Main Menu");
buttonWidthLocation = (width / 2) - (buttonWidth / 2);
buttonWidth = 80;
buttonHeight = 40;
rplay = new Rectangle(buttonWidthLocation, 150, buttonWidth, buttonHeight);
roptions = new Rectangle(buttonWidthLocation, 300, buttonWidth, buttonHeight);
rhelp = new Rectangle(buttonWidthLocation, 450, buttonWidth, buttonHeight);
rmainMenu = new Rectangle(buttonWidthLocation, 600, buttonWidth, buttonHeight);
play.setBounds(rplay);
options.setBounds(roptions);
help.setBounds(rhelp);
mainMenu.setBounds(rmainMenu);
add(play);
add(options);
add(help);
add(mainMenu);
play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Frame frame = new Frame();
//need to remove this panel here
frame.ThreeD();
}
});
options.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("options");
}
});
help.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("help");
}
});
mainMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("mainMenu");
}
});
}
}
And this is my Frame class:
package Run;
import javax.swing.*;
import ThreeD.Display;
import ThreeD.Launcher;
import TowerDefence.Window;
import java.awt.*;
import java.awt.image.BufferedImage;
public class Frame extends JFrame{
public static String title = "Game";
/*public static int GetScreenWorkingWidth() {
return java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().width;
}*/
/*public static int GetScreenWorkingHeight() {
return java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().height;
}*/
//public static Dimension size = new Dimension(GetScreenWorkingWidth(), GetScreenWorkingHeight());
public static Dimension size = new Dimension(1280, 774);
public static void main(String args[]) {
Frame frame = new Frame();
System.out.println("Width of the Frame Size is "+size.width+" pixels");
System.out.println("Height of the Frame Size is "+size.height+" pixels");
}
public Frame() {
setTitle(title);
setSize(size);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ThreeDLauncher();
}
public void ThreeDLauncher() {
Launcher launcher = new Launcher();
add(launcher);
setVisible(true);
}
public void TowerDefence() {
setLayout(new GridLayout(1, 1, 0, 0));
Window window = new Window(this);
add(window);
setVisible(true);
}
public void ThreeD() {
BufferedImage cursor = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
Cursor blank = Toolkit.getDefaultToolkit().createCustomCursor(cursor, new Point(0, 0), "blank");
getContentPane().setCursor(blank);
Display display = new Display();
add(display);
setVisible(true);
display.start();
}
}
Basically - you are creating new instance of Frame in line:
Frame frame = new Frame(); //referencing to my JFrame class (this class is a JPanel)
New instance of Frame is not visible, and you're try to remove your Launcher from not visible new Frame. But this is wrong - you should remove Launcher from Frame that you created previously in main function (that is: parent of Launcher component).
Here goes an example:
public class TestFrame extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
TestFrame frame = new TestFrame();
frame.getContentPane().add(new MyPanel(frame));
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
And MyPanel class:
public class MyPanel extends JPanel {
public MyPanel(final TestFrame frame) {
JButton b = new JButton("Play");
add(b);
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Container pane = frame.getContentPane();
pane.remove(MyPanel.this);
JPanel otherPanel = new JPanel();
otherPanel.add(new JLabel("OtherPanel"));
pane.add(otherPanel);
pane.revalidate();
}
});
}
}
In your example you should add a reference to Frame in your Launcher constructor:
public Launcher(Frame frame) {
this.frame = frame;
...
Init Launcher:
public void ThreeDLauncher() {
Launcher launcher = new Launcher(this);
and use:
play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//need to remove this panel here
frame.getContentPane().remove(Launcher.this);
frame.ThreeD();
}
});
Say your panel is myPanel you can remove it from the main frame by:
frame.getContentPane().remove(myPanel);