Java: Dispose Gui Form - java

I'm making a GUI using IntelliJ, and I have selected the option New -> Gui Form. I have made it as a login screen, but I cannot dispose the window at successful login. I have tried to extend the class with extends JFrame and then call dispose(), but it does not seem to be working. What do I do wrong?
In advance, thank you.
UPDATE with code:
public LoginFrame() {
loginButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
char[] pass = password.getPassword();
StringBuilder passwordBuilder = new StringBuilder();
for (char p : pass)
{
passwordBuilder.append(p);
}
String password = passwordBuilder.toString();
//Login.
if(DatabaseHandler.login(username.getText(), password))
{
dispose(); //THIS WINDOW.
}
else
{
JOptionPane.showMessageDialog( null, "Wrong username or password!", "Login failed!", JOptionPane.ERROR_MESSAGE);
}
}
});
}

You can try following:
if(DatabaseHandler.login(username.getText(), password))
{
Component button = (Component) e.getSource();
SwingUtilities.getWindowAncestor(button).dispose();
}
When it does not help, please provide a MCVE so we can understand what's wrong in your code.

if you have your class extending JFrame you just use your class name to dispose the JFrame as per the below
windowClassName.super.dispose();

Related

Close window after checking

I'm having a slight issue, and I can't figure it out.
I want for my code to check if the email and password matches and then close the window. This the action:
btnLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
boolean status = Email_Verification.email_validation(email_text.getText().toString().trim());
if (status) {
lbl_inco_email.setText(null);
} else {
lbl_inco_email.setText("Please enter a valid email");
}
boolean stat = Password_Verification.password_validation(password_Field.getPassword().toString());
if (stat) {
lbl_inco_pwd.setText(null);
} else {
lbl_inco_pwd.setText("Please enter a valid Password");
}
/* Exit and redirect to the main application if the email/pwd matches the database */
/** MAIN__WINDOW __EXIT__ONCLICK__ = new MAIN__WINDOW();
__EXIT__ONCLICK__.setVisible(true); */
}
});
I am going to assume you have an issue with opening a new frame and disposing of the login frame, because if you have an issue with user validation there isn't enough information for any of us to actually help.
Also, please read this concerning the use of multiple JFrames. The Use of Multiple JFrames: Good or Bad Practice?
Now for the code section...
Once user validation is done, you need to create an instance of your main window and make it visible. After that you can close the first JFrame.
Your actionPerformed would look something like this:
btnLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Let's assume you have a boolean variable that handles user validation
//for simplicity...
if(userVerified) {
// In this example let's call the main application window MainFrame
MainFrame mF = new MainFrame();
// Set it to visible
mF.setVisible(true);
mF.setLocationRelativeTo(null);
// Now you can close the first JFrame
this.dispose();
}
}
});

How to stop closing JFrame form?

I want to Stop accidentally closings in my project. I'm using JFrame Form as Home page. When I click Home window's close button I put Exit cord in Yes Option. I want to stop closing when I click No Option. Is there any way. Here is my cord. I'm using netbeans 7.3
private void formWindowClosing(java.awt.event.WindowEvent evt) {
int i= JOptionPane.showConfirmDialog(null, "Are you sure to exit?");
if (i == JOptionPane.YES_OPTION) {
System.exit(0);
} else{
new Home().setVisible(true);
}
}
How about
class MyGUI extends JFrame {
public MyGUI() {
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);// <- don't close window
// when [X] is pressed
final MyGUI gui = this;
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
int i = JOptionPane.showConfirmDialog(gui,
"Are you sure to exit?", "Closing dialog",
JOptionPane.YES_NO_OPTION);
if (i == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
});
setSize(200, 200);
setVisible(true);
}
//demo
public static void main(String[] args) {
new MyGUI();
}
}
You can simply do that like this
Integer opt = JOptionPane.showConfirmDialog(null, "This application cannot continue without login to the database\n Are you sure you need to exit...?", "Application X", JOptionPane.YES_NO_OPTION);
if(opt== JOptionPane.NO_OPTION){
this.setVisible(true);
}else{
System.exit(0);
}

return from Jframe by jbutton

I have Jframe that has a JTextField and a JButton. It should return text of Jtextfield to anotherClass (MainPage).
but when program starts, It returns null to the class.
public class JframeFoo extends JFrame {
private String username = new String();
public JframeFoo() {
// --------------------------------------------------------------
// Making Frame for login
final JTextField usernameFiled = new JTextField();
this.add(usernameFiled);
JButton signinButton = new JButton();
// ------------------------------------------------------------
signinButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
setVisible(false);
Main.mainpage.setVisible(true);
}
});
// ----------------------------------------------------------------------
username = usernameFiled.getText();
}
public String getuserName() {
return this.username;
}
}
(this Jframe should run at the start of program and when it gets text, it should go to invisible and another class should become visible.)
You need to move the call to username = usernameField.getText() into the actionPerformed method. It only gets set to null the way you currently have it.
The constructor JFrameFoo() is called when that frame is created. Therefore, this line:
username = usernameFiled.getText();
is also called at that moment. What you want to do instead is:
signinButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
username = usernameFiled.getText();
setVisible(false);
Main.mainpage.setVisible(true);
}
});
EDIT
What I expect is also going wrong is that you use userName in your main class before it is initialized. I would recommend two things:
Learn about event-driving programming and callbacks. The simple fact that a line is below another in the source does not mean that it is executed later.
Instead of calling mainPage.setVisible, do something like
signinButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
setVisible(false);
Main.mainpage.open(usernameFiled.getText());
}
});
and add that method in your mainpage, doing something like
public void open(String username) {
this.setVisible(true);
// do whatever you want to do with username
}
In addition to calling the getText() method from within the actionPerformed overridden method, you can also use this.dispose(); rather than setVisible(false);
so your code would look something like:
signinButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
username = usernameFiled.getText();
if ((username != null) || !(username.length() == 0)) {
this.dispose();
Main.mainpage.setVisible(true);
} else {
// Appropriate error here...
}
}
});
Calling getText() from within actionPerformed will also allow you to do some checks on the username variable before you dispose of the frame and proceed (again, see above snippet).
Good luck!

ActionListener on JOptionPane

I am following the Oracle tutorial on how to create a custom dialog box: http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html
I have two buttons: Save Object and Delete Object which when clicked should execute a certain piece of code. Unfortunately I can't seem to add any ActionListener to the JOptionPane buttons so when they're clicked nothing happens.
Can anyone help tell me how I can go about doing this? Here is the class I have for the dialog box so far:
class InputDialogBox extends JDialog implements ActionListener, PropertyChangeListener {
private String typedText = null;
private JTextField textField;
private JOptionPane optionPane;
private String btnString1 = "Save Object";
private String btnString2 = "Delete Object";
/**
* Returns null if the typed string was invalid;
* otherwise, returns the string as the user entered it.
*/
public String getValidatedText() {
return typedText;
}
/** Creates the reusable dialog. */
public InputDialogBox(Frame aFrame, int x, int y) {
super(aFrame, true);
setTitle("New Object");
textField = new JTextField(10);
//Create an array of the text and components to be displayed.
String msgString1 = "Object label:";
Object[] array = {msgString1, textField};
//Create an array specifying the number of dialog buttons
//and their text.
Object[] options = {btnString1, btnString2};
//Create the JOptionPane.
optionPane = new JOptionPane(array,
JOptionPane.PLAIN_MESSAGE,
JOptionPane.YES_NO_OPTION,
null,
options,
options[0]);
setSize(new Dimension(300,250));
setLocation(x, y);
//Make this dialog display it.
setContentPane(optionPane);
setVisible(true);
//Handle window closing correctly.
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
/*
* Instead of directly closing the window,
* we're going to change the JOptionPane's
* value property.
*/
optionPane.setValue(new Integer(
JOptionPane.CLOSED_OPTION));
}
});
//Ensure the text field always gets the first focus.
addComponentListener(new ComponentAdapter() {
public void componentShown(ComponentEvent ce) {
textField.requestFocusInWindow();
}
});
//Register an event handler that puts the text into the option pane.
textField.addActionListener(this);
//Register an event handler that reacts to option pane state changes.
optionPane.addPropertyChangeListener(this);
}
/** This method handles events for the text field. */
public void actionPerformed(ActionEvent e) {
optionPane.setValue(btnString1);
System.out.println(e.getActionCommand());
}
/** This method reacts to state changes in the option pane. */
public void propertyChange(PropertyChangeEvent e) {
String prop = e.getPropertyName();
if (isVisible()
&& (e.getSource() == optionPane)
&& (JOptionPane.VALUE_PROPERTY.equals(prop) ||
JOptionPane.INPUT_VALUE_PROPERTY.equals(prop))) {
Object value = optionPane.getValue();
if (value == JOptionPane.UNINITIALIZED_VALUE) {
//ignore reset
return;
}
//Reset the JOptionPane's value.
//If you don't do this, then if the user
//presses the same button next time, no
//property change event will be fired.
optionPane.setValue(JOptionPane.UNINITIALIZED_VALUE);
if (btnString1.equals(value)) {
typedText = textField.getText();
String ucText = typedText.toUpperCase();
if (ucText != null ) {
//we're done; clear and dismiss the dialog
clearAndHide();
} else {
//text was invalid
textField.selectAll();
JOptionPane.showMessageDialog(
InputDialogBox.this,
"Please enter a label",
"Try again",
JOptionPane.ERROR_MESSAGE);
typedText = null;
textField.requestFocusInWindow();
}
} else { //user closed dialog or clicked delete
// Delete the object ...
typedText = null;
clearAndHide();
}
}
}
/** This method clears the dialog and hides it. */
public void clearAndHide() {
textField.setText(null);
setVisible(false);
}
I think you're missing the point of the JOptionPane. It comes with the ability to show it's own dialog...
public class TestOptionPane02 {
public static void main(String[] args) {
new TestOptionPane02();
}
public TestOptionPane02() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JTextField textField = new JTextField(10);
String btnString1 = "Save Object";
String btnString2 = "Delete Object";
//Create an array of the text and components to be displayed.
String msgString1 = "Object label:";
Object[] array = {msgString1, textField};
//Create an array specifying the number of dialog buttons
//and their text.
Object[] options = {btnString1, btnString2};
int result = JOptionPane.showOptionDialog(null, array, "", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, "New Object", options, options[0]);
switch (result) {
case 0:
System.out.println("Save me");
break;
case 1:
System.out.println("Delete me");
break;
}
}
});
}
}
To do it manually, you're going to have to do a little more work.
Firstly, you're going to have to listen to the panel's property change events, looking for changes to the JOptionPane.VALUE_PROPERTY and ignoring any value of JOptionPane.UNINITIALIZED_VALUE...
Once you detect the change, you will need to dispose of your dialog.
The you will need extract the value that was selected via the JOptionPane#getValue method, which returns an Object. You will have to interrupt the meaning to that value yourself...
Needless to say, JOptionPane.showXxxDialog methods do all this for you...
Now if you worried about having to go through all the setup of the dialog, I'd write a utility method that either did it completely or took the required parameters...but that's just me
UPDATED
Don't know why I didn't think it sooner...
Instead of passing an array of String as the options parameter, pass an array of JButton. This way you can attach your own listeners.
options - an array of objects indicating the possible choices the user
can make; if the objects are components, they are rendered properly;
non-String objects are rendered using their toString methods; if this
parameter is null, the options are determined by the Look and Feel
For the flexibility you seem to want you should have your class extend JFrame instead of JDialog. Then declare your buttons as JButtons:
JButton saveButton = new JButton("Save"); and add an actionListnener to this button:
saveButton.addActionListener();
either you can put a class name inside the parenthesis of the saveButton, or you can simply pass it the keyword 'this' and declare a method called actionPerformed to encapsulate the code that should execute when the the button is pressed.
See this link for a JButton tutorial with more details:
http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html

JoptionPane ShowConfirmDialog

I have a Java program. When I run the program, it will give me a GUI which as I attached.
When I want to close it, it will prompt out a confirm dialog. If I press the Yes button, it will quit the program using System.exit().
public static void main(String args[])
{
ButtonTest app = new ButtonTest( );
app.addWindowListener(
new WindowAdapter( )
{
public void windowClosing (WindowEvent e)
{
String message = " Really Quit ? ";
String title = "Quit";
int reply = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION)
{
System.exit(0);
}
}
}
);
}
If I don't want to quit the program, what can I do? System.continued() ?
You Don't need the else in this case
Try setting this,
app.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE)
[Edited]
So, your code will become something like this,
public static void main(String args[]) {
ButtonTest app = new ButtonTest();
app.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
int reply = JOptionPane.showConfirmDialog(null,
"Really Quit ?", "Quit", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION)
System.exit(0);
}
});
app.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
app.setSize(640, 480);
app.setVisible(true);
}
[Explanation]
You might be thinking that why it is like that. The behaviour of windows close button for JFrame, unlike Frame,is to hide the window. Therefore, it will hide/close the window anyway. But when you specify that it must also exit the program, when the user click yes. Then, besides closing the window, it also exits the program. And when user clicks no, it does nothing but closes the window anyway. Hence, you must tell it explicitly that DO_NOTHING_ON_CLOSE.
[Docs]
Unlike a Frame, a JFrame has some notion of how to respond when the
user attempts to close the window. The default behavior is to simply
hide the JFrame when the user closes the window. To change the default
behavior, you invoke the method setDefaultCloseOperation(int). To make
the JFrame behave the same as a Frame instance, use
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE).
Ref: JFrame docs
If you will ask me, I will go with, on YES SELECTION instead of abruptly closing my Application with System.exit(0), I will choose the gracious way of closing my Application, by using frameObject.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) and on NO SELECTION , I will go for frameObject.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE). Here is one sample program for your help :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ApplicationCloseExample
{
private void displayGUI()
{
final JFrame frame = new JFrame("Application Close Example");
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
int result = JOptionPane.showConfirmDialog(
frame, "Do you want to Exit ?"
, "Exit Confirmation : ", JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
else if (result == JOptionPane.NO_OPTION)
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
});
frame.setSize(300, 300);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ApplicationCloseExample().displayGUI();
}
});
}
}
If you want the program to continue when you press NO, place the rest of your code in else block or call the function where you have placed the rest of your code.
Removing else block is also an option if you don't want to place any action on the NO button because the JOptionPane.showConfirmDialog() will close anyways. You can continue with rest of your code after the if statement.
FYI- There is no System.continue(). The program pretty much does that on it's own.
You can add an else block. if you want to run the main method again (which I assume you do) it should look like this. You should have some method which you run if the user chooses no, whether it is the main method main(null) or another method.
public static void main(String args[])
{
ButtonTest app = new ButtonTest( );
app.addWindowListener(
new WindowAdapter( )
{
public void windowClosing (WindowEvent e)
{
String message = " Really Quit ? ";
String title = "Quit";
int reply = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION)
{
System.exit(0);
}
else
{
//whatever you plan on running instead here, instead of quitting,
//main(null) to run the main method, or put another method if you want
}
}
}
);
}

Categories

Resources