I cannot close JFrame - java

I have two java forms: NewJFrame i NewJFrame1. I have button on NewJFrame, so when I click on that button to open NewJFrame1 and close NewJFrame. It can open NewJFrame1, but it cannot close NewJFrame.
This:
NewJFrame frame = new NewJframe();
frame.setVisible(false);
doesn't work. Also, frame.dispose(); doesnt work. CAn someone help me to soleve problem, how can I close NewJFrame by clicking on button in it (NewJFrame).

In your code
NewJFrame frame = new NewJFrame();
creates a new (second) instance of NewJFrame. If you want to close the original one, you need a reference to this instance. Depending on your code, the reference could be this, so
this.dispose();
could work.

Check if is frame visible before u trying to close it...Maybe u are trying to close wrong instance of frame... if u have NewJFrame frame = new NewJframe()
then this same frame need to be closed .
frame.setVisible(false);
or
frame.dispose();
Just do dispose on original instance do not do JFrame frame = new JFrame()twice.

Try this one.. Hope, it will work.
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

I'm not really sure to understand why you are doing this, but I provided you a working sample :
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Tester implements ActionListener {
private static final String SHOW = "show";
private final JButton displayer = new JButton(SHOW);
private final JButton hider = new JButton("hide");
private final JFrame f;
private final JFrame f1;
Tester(){
displayer.addActionListener(this);
hider.addActionListener(this);
f = new JFrame();
f.setLayout(new FlowLayout());
f.setSize(500, 500);
f.add(displayer);
f.add(hider);
f.setVisible(true);
f1 = new JFrame();
f1.setSize(500, 500);
f1.setLocationRelativeTo(null);
f1.add(new JLabel("empty frame"));
}
public static void main(String[] args) {
new Tester();
}
#Override
public void actionPerformed(ActionEvent arg0) {
f1.setVisible(arg0.getActionCommand().equals(SHOW));
}
}

Related

Java GUI - JButton opens another frame from another class

i'm having trouble to get the 2nd frame to display the GUI Components. i've opened the frame using the JButton from the 1st frame.
Here's the screen shot
This is the first frame - ClientModule.java
2nd frame - ClientMenu.java
Here's the codes i've tried
ClientModule.java
import java.net.*;
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ClientModule extends JFrame implements Runnable{
private JPanel panel;
private JFrame frame;
private JLabel titleLbl, userLbl, passLbl, hostLbl, portLbl, ipLbl;
private JTextField userTxt, hostTxt, portTxt, ipTxt;
private JPasswordField passTxt;
private JButton loginBtn;
public static void main(String[] args)
{
new ClientModule().run();
}
public ClientModule()
{
frame = new JFrame("DMS(Drawing Message System)");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
panel = new JPanel();
panel.setPreferredSize(new Dimension(500,500));
panel.setLayout(new FlowLayout());
titleLbl = new JLabel("LogIn to Drawing Message System(DMS)");
titleLbl.setFont(new Font("Rockwell Condensed",Font.BOLD,28));
userLbl = new JLabel("Username:");
passLbl = new JLabel("Password:");
hostLbl = new JLabel("Hostname:");
portLbl = new JLabel("Port No.:");
ipLbl = new JLabel("IP Address:");
userTxt = new JTextField();
userTxt.setPreferredSize(new Dimension(100,30));
passTxt = new JPasswordField();
passTxt.setEchoChar('*');
passTxt.setPreferredSize(new Dimension(100,30));
portTxt = new JTextField();
portTxt.setPreferredSize(new Dimension(100,30));
ipTxt = new JTextField();
ipTxt.setPreferredSize(new Dimension(100,30));
hostTxt = new JTextField();
hostTxt.setPreferredSize(new Dimension(100,30));
loginBtn = new JButton("Login!");
loginBtn.setPreferredSize(new Dimension(90,30));
loginBtn.addActionListener(new LoginBtnListener());
panel.add(titleLbl);
panel.add(userLbl);
panel.add(userTxt);
panel.add(passLbl);
panel.add(passTxt);
panel.add(hostLbl);
panel.add(hostTxt);
panel.add(portLbl);
panel.add(portTxt);
panel.add(ipLbl);
panel.add(ipTxt);
panel.add(loginBtn);
frame.add(panel);
}
private class LoginBtnListener implements ActionListener
{
#SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent action)
{
//thinking this frame will close after ClientMenu's frame is open
ClientModule client = new ClientModule();
client.setVisible(false);
ClientMenu menu = new ClientMenu();
menu.setVisible(true);
}
}
public void run()
{
frame.pack();
frame.setVisible(true);
}
}
ClientMenu.java
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
public class ClientMenu extends JFrame{
JFrame frame;
JPanel panel;
JLabel titleLbl;
JButton sendBtn,receiveBtn,logoutBtn;
public ClientMenu()
{
frame = new JFrame("Drawing Message System(DMS)");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.setPreferredSize(new Dimension(500,500));
titleLbl = new JLabel("Main Menu");
titleLbl.setFont(new Font("Rockwell Condensed",Font.BOLD,28));
sendBtn = new JButton("Send a Drawing");
sendBtn.setPreferredSize(new Dimension(100,30));
receiveBtn = new JButton("Receive a Drawing");
receiveBtn.setPreferredSize(new Dimension(100,30));
logoutBtn = new JButton("Logout");
logoutBtn.setPreferredSize(new Dimension(100,30));
logoutBtn.addActionListener(new LogoutBtnListener());
panel.add(titleLbl);
panel.add(sendBtn);
panel.add(receiveBtn);
panel.add(logoutBtn);
frame.add(panel);
}
private class LogoutBtnListener implements ActionListener
{
//#SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent action)
{
ClientModule client = new ClientModule();
client.setVisible(true);
ClientMenu menu = new ClientMenu();
menu.setVisible(false);
}
}
public static void main(String[] args)
{
new ClientMenu().run();
}
public void run()
{
frame.pack();
frame.setVisible(true);
}
}
I'm not sure if i'm missing something, or coded something wrong, or something else. I've already searched and tried..
any help and understanding is appreciated (:
I managed to get the second frame displayed (including its contents) by adding a call to the run() method:
ClientMenu menu = new ClientMenu();
menu.setVisible(true);
menu.run();
That being said, there are quite some problems with your code:
You have a main method in each of your classes. You should have only 1 main method per application. Since ClientModule seems to be the first Frame you want to have opened, your might want to keep the main method there and remove the one in the other class.
You have a run() method in each class. Personally, I tend to avoid naming methods like this, since it might cause confusion with the run() method which needs to be overridden when dealing with threads. You are clearly attempting to do some multi threading in your ClientModule, but will not work. Please look into this concurrency tutorial to better understand threads. You should also understand that you should never call run() yourself. The tutorial should make that clear.
Swing applications are started a little bit differently that other applications. Please refer to this tutorial for more information.
You have both your classes extend JFrame but then, provide your own. This results in other JFrames being created, which is what happened in my case (I get 2 JFrames per instantiation). If you want your class to behave like a JFrame, consider extending it, if you want to use a JFrame, then compose your class of one, not both (at least not in this case).
Lastly, to get rid of the previous JFrame you could call dispose() on the it. That being said, the approach usually is to use the Card Layout. This would allow you to have 1 frame with multiple content.
Sorry for the long post, but please consider re factoring as per the above prior to continuing.
You can use the setVisible property to 'true' or 'false'.

Making a JPanel Popup

I'm developing an app for computer, and i have a JFrame with a lot of JPanel on it, and when i click on a button, i want another JPanel to popup.
Example: When i click on this button
http://i62.tinypic.com/c2fzr.jpg
I want this window to popup
http://i62.tinypic.com/2qi0in7.jpg
I already tried making a popup menu, but i don't want a menu, i want a window, and i can't seen to find out how to do it :(
It's probably easy, but i don't have enough knowledge in java
Any help? thanks guys!
Ok so,for this you will need 2 JFrames. First one is where the buttons and everything is and the second one is the one that will popup. You will have 3 classes: Main, classWhere1stJframeis, ClassWhere2ndJframeis.
This is main:
package proba;
import javax.swing.JFrame;
public class mejn {
public static void main(String[] args) {
// TODO Auto-generated method stub
Frame1 frejm = new Frame1();
frejm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frejm.setVisible(true);
frejm.setSize(250, 300);
}
}
This is Frame1:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Frame1 extends JFrame {
JFrame Frame = new JFrame();
JButton Button1 = new JButton();
public Frame1()
{
super("The title");
Frame = new JFrame();
Button1 = new JButton();
Frame.add(Button1);
thehandler handler = new thehandler();
Button1.addActionListener(handler);
}
private class thehandler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if(event.getSource()==Button1)
{
Frejm2 frejm = new Frejm2();
frejm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frejm.setVisible(true);
}
}
}
}
This is Frame2:
import javax.swing.JFrame;
public class Frejm2 extends JFrame {
JFrame Frame2 = new JFrame();
public Frejm2()
{
super("Title");
}
}
that is not just a panel you want to pop up that would be considered a whole other frame. I would suggest making a different JFrame class that when the button is clicked instantiates the other frame.

Using JFrame with Netbeans on a Mac

I want to run this code that will create a window with a simple button on it. The program will run in Netbeans on a Mac but the problem is that it does not work. Here is the code below.
import javax.swing.JFrame;
public class Test {
public static JButton button(){
JButton button = new JButton("random button");
}
public static void main(String[] args) {
button();
new JFrame();
}
}
Please help me figure this out soon please. Thank you.
You're not adding the button to anything or displaying the JFrame. Your method returns a JButton object, but you're not doing anything with this object.
Create a JPanel
Add the JButton to the JPanel
Add the JPanel to the JFrame
Display the JFrame by calling setVisible(true)
Most important: Making up code and hoping it will magically work is not a successful heuristic for learning to program. Instead read the Swing tutorials which you can find here.
For example
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MyTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JButton button = new JButton("Button");
JPanel panel = new JPanel();
panel.add(button);
JFrame frame = new JFrame("foo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

How to reference JFrame

I have a problem which is most likely "simple" however I can't figure it out. I am trying to reference my current JFrame so that I can dispose of it, and create a new one, thus "resetting" the program, however I and having trouble figuring out how to reference the JFrame, I have tried, super, this and getParent(), but none of the seem to work. Thanks for any / all help. ^^
Here is my code:
Main Class, just sets up the Jframe and calls the class that creates everything:
public static void main(String args[]) {
JFrame window = new JFrame();
Director director = new Director(window, args);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLocationRelativeTo(null);
window.pack();
window.setVisible(true);
}
}
Class the creates everything:
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class Director extends JFrame implements CollisionListener {
private BrickWall wall;
private JLabel gameTitle, gameScore, gameLives;
private JPanel controlPanel;
private JButton reset, quit;
private JRadioButton hard, normal, easy;
private int score = 6, lives = 5;
private ButtonGroup difficulty;
public Director(JFrame window, String[] args) {
window.getContentPane().add(makeGamePanel(), BorderLayout.CENTER);
window.getContentPane().add(gameControlPanel(), BorderLayout.NORTH);
}
public void collisionDetected(CollisionEvent e) {
wall.setBrick(e.getRow(), e.getColumn(), null);
}
private JComponent makeGamePanel() {
wall = new BrickWall();
wall.addCollisionListener(this);
wall.buildWall(3, 6, 1, wall.getColumns(), Color.GRAY);
return wall;
}
// Reset method I'm trying to dispose of the JFrame in.
private void reset() {
JFrame frame = new JFrame();
frame.getContentPane().add(makeGamePanel(), BorderLayout.CENTER);
frame.getContentPane().add(gameControlPanel(), BorderLayout.NORTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private JComponent gameControlPanel() {
// CONTROL PANEL PANEL!
controlPanel = new JPanel();
gameTitle = new JLabel("Brickles");
gameScore = new JLabel("Score:" + " " + score);
gameLives = new JLabel("Lives:" + " " + lives);
reset = new JButton("Reset");
quit = new JButton("Quit");
hard = new JRadioButton("Hard", false);
normal = new JRadioButton("Normal", true);
easy = new JRadioButton("Easy", false);
difficulty = new ButtonGroup();
difficulty.add(hard);
difficulty.add(normal);
difficulty.add(easy);
controlPanel.setLayout(new GridLayout(4, 2));
controlPanel.add(gameTitle);
controlPanel.add(gameScore);
controlPanel.add(hard);
controlPanel.add(gameLives);
controlPanel.add(normal);
controlPanel.add(reset);
controlPanel.add(easy);
controlPanel.add(quit);
// Action Listener, where I'm caling the reset method.
reset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
reset();
}
});
return controlPanel;
}
}
You can refer to the "outer this" from a nested class with the following syntax:
reset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Director.this.reset();
}
});
Yes, you can refer to the outer class by specifying it with the class name as noted in DSquare's good answer (1+ to it), but I urge you not to fling JFrame's at the user as you're program is trying to do. I recommend:
Instead of opening and closing multiple JFrames, use only one JFrame as the main application's window.
If you need helper windows, such as modal windows to get critical information that is absolutely needed, before the program can progress, use modal dialogs such as JDialogs or JOptionPanes.
If you need to swap GUI's, instead of swapping JFrames, swap "views" inside the JFrame via a CardLayout.
Gear your code towards creating these JPanel views and not JFrames as it will make your Swing GUI's much more flexible and portable.

Redrawing a new JFrame in an existing one?

I'm trying to display a different JFrame after the user does something in the same window they are using, similar to a login feature. Haven't been able to figure out how to do that.
The workaround I have now is to just hide the current JFrame and then open a new one, which simulates a similar effect. But ideally I want it to just display the next JFrame in the same existing window.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Login extends JFrame {
private static int x = 0;
static JTextField txtInput = new JTextField(10);
static JButton btnSwitch = new JButton("Log on");
public Login(){
setLayout(new FlowLayout());
//add button and register
add(new JLabel("Enter password:"));
add(txtInput);
add(btnSwitch);
}
public static void main(String[] args) {
final JFrame frame = new Login();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 150);
frame.setVisible(true);
btnSwitch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(txtInput.getText().equals("123")){
//frame = new GUIHelloWorld(); this doesn't work because "The final local variable frame cannot be assigned, since it is defined in an enclosing type"
//so I went with the below workaround
GUIHelloWorld frame = new GUIHelloWorld();
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 100);
frame.setVisible(true);
}
}
});
}
}
Once the user get pass the first part of the GUI, I want to show em something else like this:
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class GUIHelloWorld extends JFrame {
public GUIHelloWorld(){
setLayout(new GridLayout(0,1));
add(new JLabel("Hello World"));
add(new JLabel("Welcome to the 2nd part of the GUI"));
}
public static void main(String[] args) {
JFrame frame = new GUIHelloWorld();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 100);
frame.setVisible(true);
}
}
Can someone give me an idea of how to display a new JFrame into the existing window that the user is using?
Don't extend from JFrame, especially in the case, frame's can't be added to other frames. Instead, based you individual UI views on something like JPanel
Create a single instance of a JFrame, set it's layout manager to use a CardLayout.
Add each of your view's to the frame, naming each view appropriately
Use CardLayout to switch between the view as needed
You could also consider using a JDialog for the login window, but the basic advice remains; create windows, extend components...

Categories

Resources