Popup Message boxes

JavaSwingNetbeans

Java Problem Overview


I am unsure of how to code popup message box in my methods.

public String verify(){
    String result = "failed";
    int authcode = staffBean.getVerifyCodeByName(getLoginUserName());
   
    if (code == authcode){       
        result ="success";
    }    
    else{ //statement to popup an error message box

    }
    return result;
}

I have tried to use JOptionPane in my method but it does not work:

String st = "Welcome";
JOptionPane.showMessageDialog(null, st);

Java Solutions


Solution 1 - Java

javax.swing.JOptionPane

Here is the code to a method I call whenever I want an information box to pop up, it hogs the screen until it is accepted:

import javax.swing.JOptionPane;

public class ClassNameHere
{

    public static void infoBox(String infoMessage, String titleBar)
	{
		JOptionPane.showMessageDialog(null, infoMessage, "InfoBox: " + titleBar, JOptionPane.INFORMATION_MESSAGE);
	}
}

The first JOptionPane parameter (null in this example) is used to align the dialog. null causes it to center itself on the screen, however any java.awt.Component can be specified and the dialog will appear in the center of that Component instead.

I tend to use the titleBar String to describe where in the code the box is being called from, that way if it gets annoying I can easily track down and delete the code responsible for spamming my screen with infoBoxes.

To use this method call:

ClassNameHere.infoBox("YOUR INFORMATION HERE", "TITLE BAR MESSAGE");

javafx.scene.control.Alert

For a an in depth description of how to use JavaFX dialogs see: JavaFX Dialogs (official) by code.makery. They are much more powerful and flexible than Swing dialogs and capable of far more than just popping up messages.

As above I'll post a small example of how you could use JavaFX dialogs to achieve the same result

import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.application.Platform;

public class ClassNameHere
{

    public static void infoBox(String infoMessage, String titleBar)
    {
        /* By specifying a null headerMessage String, we cause the dialog to
           not have a header */
        infoBox(infoMessage, titleBar, null);
    }

    public static void infoBox(String infoMessage, String titleBar, String headerMessage)
	{
	    Alert alert = new Alert(AlertType.INFORMATION);
        alert.setTitle(titleBar);
        alert.setHeaderText(headerMessage);
        alert.setContentText(infoMessage);
        alert.showAndWait();
	}
}

One thing to keep in mind is that JavaFX is a single threaded GUI toolkit, which means this method should be called directly from the JavaFX application thread. If you have another thread doing work, which needs a dialog then see these SO Q&As: JavaFX2: Can I pause a background Task / Service? and Platform.Runlater and Task Javafx.

To use this method call:

ClassNameHere.infoBox("YOUR INFORMATION HERE", "TITLE BAR MESSAGE");

or

ClassNameHere.infoBox("YOUR INFORMATION HERE", "TITLE BAR MESSAGE", "HEADER MESSAGE");

Solution 2 - Java

first you have to import: import javax.swing.JOptionPane; then you can call it using this:

JOptionPane.showMessageDialog(null, 
                              "ALERT MESSAGE", 
                              "TITLE", 
                              JOptionPane.WARNING_MESSAGE);

the null puts it in the middle of the screen. put whatever in quotes under alert message. Title is obviously title and the last part will format it like an error message. if you want a regular message just replace it with PLAIN_MESSAGE. it works pretty well in a lot of ways mostly for errors.

Solution 3 - Java

A couple of "enhancements" I use for debugging, especially when running projects (ie not in debug mode).

  1. Default the message-box title to the name of the calling method. This is handy for stopping a thread at a given point, but must be cleaned-up before release.

  2. Automatically copy the caller-name and message to the clipboard, because you can't search an image!

     package forumposts;
    
     import java.awt.Toolkit;
     import java.awt.datatransfer.Clipboard;
     import java.awt.datatransfer.StringSelection;
     import javax.swing.JOptionPane;
    
     public final class MsgBox
     {
         public static void info(String message) {
             info(message, theNameOfTheMethodThatCalledMe());
         }
         public static void info(String message, String caller) {
             show(message, caller, JOptionPane.INFORMATION_MESSAGE);
         }
    
         static void error(String message) {
             error(message, theNameOfTheMethodThatCalledMe());
         }
         public static void error(String message, String caller) {
             show(message, caller, JOptionPane.ERROR_MESSAGE);
         }
    
         public static void show(String message, String title, int iconId) {
             setClipboard(title+":"+NEW_LINE+message);
             JOptionPane.showMessageDialog(null, message, title, iconId);
         }
         private static final String NEW_LINE = System.lineSeparator();
    
         public static String theNameOfTheMethodThatCalledMe() {
             return Thread.currentThread().getStackTrace()[3].getMethodName();
         }
    
         public static void setClipboard(String message) {
             CLIPBOARD.setContents(new StringSelection(message), null);
             // nb: we don't respond to the "your content was splattered"
             //     event, so it's OK to pass a null owner.
         }
         private static final Toolkit AWT_TOOLKIT = Toolkit.getDefaultToolkit();
         private static final Clipboard CLIPBOARD = AWT_TOOLKIT.getSystemClipboard();
    
     }
    

The full class also has debug and warning methods, but I cut them for brevity and you get the main points anyway. You can use a public static boolean isDebugEnabled to suppress debug messages. If done properly the optimizer will (almost) remove these method calls from your production code. See: http://c2.com/cgi/wiki?ConditionalCompilationInJava

Cheers. Keith.

Solution 4 - Java

import javax.swing.*;
class Demo extends JFrame
{
           String str1;
           Demo(String s1)
           {
             str1=s1;
            JOptionPane.showMessageDialog(null,"your message : "+str1);
            }
            public static void main (String ar[])
            {
             new Demo("Java");
            }
}

Solution 5 - Java

JOptionPane.showMessageDialog(btn1, "you are clicked save button","title of dialog",2);

btn1 is a JButton variable and its used in this dialog to dialog open position btn1 or textfield etc, by default use null position of the frame.next your message and next is the title of dialog. 2 numbers of alert type icon 3 is the information 1,2,3,4. Ok I hope you understand it

Solution 6 - Java

Ok, SO Basically I think I have a simple and effective solution.

package AnotherPopUpMessage;
import javax.swing.JOptionPane;
public class AnotherPopUp {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JOptionPane.showMessageDialog(null, "Again? Where do all these come from?", 
            "PopUp4", JOptionPane.CLOSED_OPTION);
    }
}

Solution 7 - Java

Use the following library: import javax.swing.JOptionPane;

Input at the top of the code-line. You must only add this, because the other things is done correctly!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongymcodeView Question on Stackoverflow
Solution 1 - JavaTroysephView Answer on Stackoverflow
Solution 2 - JavaBrendan CronanView Answer on Stackoverflow
Solution 3 - JavacorlettkView Answer on Stackoverflow
Solution 4 - JavaRohit RamtirtheView Answer on Stackoverflow
Solution 5 - JavaSaquib AzamView Answer on Stackoverflow
Solution 6 - JavaNinjaFangGamesView Answer on Stackoverflow
Solution 7 - JavaAbel NebayView Answer on Stackoverflow