Alert messages in java

Swing Examples — Show Alert message Dialog

Following example showcase how to show a simple message alert with Ok button in swing based application.

We are using the following APIs.

  • JOptionPane − To create a standard dialog box.
  • JOptionPane.showMessageDialog() − To show the simple alert message.

Example

import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.LayoutManager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; public class SwingTester < public static void main(String[] args) < createWindow(); >private static void createWindow() < JFrame frame = new JFrame("Swing Tester"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); createUI(frame); frame.setSize(560, 200); frame.setLocationRelativeTo(null); frame.setVisible(true); >private static void createUI(final JFrame frame) < JPanel panel = new JPanel(); LayoutManager layout = new FlowLayout(); panel.setLayout(layout); JButton button = new JButton("Click Me!"); button.addActionListener(new ActionListener() < @Override public void actionPerformed(ActionEvent e) < JOptionPane.showMessageDialog(frame, "Welcome to Swing!"); >>); panel.add(button); frame.getContentPane().add(panel, BorderLayout.CENTER); > >

Output

Show a simple message alert

Источник

Swing Examples — Show Alert message Dialog

Solution 2: This is what i see > Question: I would like to show an error message within an alert dialog box for password reset, however no error message shows inside the dialog pop up. However, entering in a valid email does show the toast message «Reset Email Sent» The validations are 1) leaving the email address empty , 2)not giving a proper email Login.java Solution: Use this code:

Читайте также:  Adding files to python path

Java alert box

1- import static javax.swing.JOptionPane.showMessageDialog; 2- showMessageDialog(null, "My Result est " + ResultVariable);
JOptionPane.showMessageDialog(null, "My Goodness, this is so concise");

Message Dialogs in Java (GUI), Message dialogs provide information to the user. Message dialogs are created with the JOptionPane.showMessageDialog() method. We call the static

6 — How to show alert box after execution of query

in this video you will learn to display alert box or option message in java swing . Here we have Duration: 3:47

(Java 2020) Creating a custom Alert Dialog Box in Android Studio

In this video I’ll be showing you how to create an Alert Dialog Box. There are more options Duration: 2:17

Alert | JavaFX GUI Tutorial for Beginners

In this tutorial we will explore the JavaFX Alert Dialog Class. The JavaFX Alert Dialog Class Duration: 9:44

Making a JFrame button create a Alert Dialog. Java

I use NetBeans IDE, as you may know there is a JFrame creator plugin (Its pre-installed) I use it to make JFrames (Because I’m too lazy to do it my self =/). in the event of creating a button within that JFrame it will generate a area for the event code. I was wondering what code i need to type in to generate the Alert Dialog. Heres what is pre-generated upon create a swing/awt component or a JFrame:

 public class NewJFrame extends javax.swing.JFrame < public NewJFrame() < initComponents(); >@SuppressWarnings("unchecked") // private void initComponents() < jDialog2 = new javax.swing.JDialog(); jButton1 = new javax.swing.JButton(); javax.swing.GroupLayout jDialog2Layout = new javax.swing.GroupLayout(jDialog2.getContentPane()); jDialog2.getContentPane().setLayout(jDialog2Layout); jDialog2Layout.setHorizontalGroup( jDialog2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 400, Short.MAX_VALUE) ); jDialog2Layout.setVerticalGroup( jDialog2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 300, Short.MAX_VALUE) ); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle(">:D"); setResizable(false); addHierarchyBoundsListener(new java.awt.event.HierarchyBoundsListener() < public void ancestorMoved(java.awt.event.HierarchyEvent evt) < formAncestorMoved(evt); >public void ancestorResized(java.awt.event.HierarchyEvent evt) < >>); jButton1.setText("Press Me :D"); jButton1.addActionListener(new java.awt.event.ActionListener() < public void actionPerformed(java.awt.event.ActionEvent evt) < jButton1ActionPerformed(evt); >>); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 349, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(null); >// private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) < //This is the area for the code dialog code >private void formAncestorMoved(java.awt.event.HierarchyEvent evt) < // TODO add your handling code here: >/** * @param args the command line arguments */ public static void main(String args[]) < /* Set the Nimbus look and feel */ ///* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try < for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) < if ("Nimbus".equals(info.getName())) < javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; >> > catch (ClassNotFoundException ex) < java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); >catch (InstantiationException ex) < java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); >catch (IllegalAccessException ex) < java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); >catch (javax.swing.UnsupportedLookAndFeelException ex) < java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); >// /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() < public void run() < new NewJFrame().setVisible(true); >>); > 

Did you see the Button1ActionPerformed thing. that’s where the code goes. I need code that will create a new Alert Dialog (javax.swing.JDialog) When that is pressed.

Sounds like you might want a JOptionPane message dialog.

JOptionPane.showMessageDialog(null, "", "Alert", JOptionPane.ERROR_MESSAGE); 

So for your case, this is what your action performed method will look like:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) < JOptionPane.showMessageDialog(null, "", "Alert", JOptionPane.ERROR_MESSAGE); > 

Note there is no «variable» to store the JOptionPane object, it’s a static method called on the JOptionPane class. Each time you want an alert/confirm/input/etc. dialog, you generate one on the fly using the static members of the JOptionPane class.

See the reference for more info.

public class NewJFrame extends javax.swing.JFrame < /** * Creates new form NewJFrame */ public NewJFrame() < initComponents(); >/** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // private void initComponents() < jOptionPane1 = new javax.swing.JOptionPane(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle(">:D"); setResizable(false); addHierarchyBoundsListener(new java.awt.event.HierarchyBoundsListener() < public void ancestorMoved(java.awt.event.HierarchyEvent evt) < formAncestorMoved(evt); >public void ancestorResized(java.awt.event.HierarchyEvent evt) < >>); jButton1.setText("Press Me :D"); jButton1.addActionListener(new java.awt.event.ActionListener() < public void actionPerformed(java.awt.event.ActionEvent evt) < jButton1ActionPerformed(evt); >>); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 353, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(0, 45, Short.MAX_VALUE) .addComponent(jOptionPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 46, Short.MAX_VALUE))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jOptionPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))) ); pack(); setLocationRelativeTo(null); >// private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) < //jOptionPane.showMessageDialog(null, "", "Alert", jOptionPane.ERROR_MESSAGE); > private void formAncestorMoved(java.awt.event.HierarchyEvent evt) < // TODO add your handling code here: >/** * @param args the command line arguments */ public static void main(String args[]) < /* Set the Nimbus look and feel */ ///* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try < for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) < if ("Nimbus".equals(info.getName())) < javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; >> > catch (ClassNotFoundException ex) < java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); >catch (InstantiationException ex) < java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); >catch (IllegalAccessException ex) < java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); >catch (javax.swing.UnsupportedLookAndFeelException ex) < java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); >// /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() < public void run() < new NewJFrame().setVisible(true); >>); > // Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JOptionPane jOptionPane1; // End of variables declaration 

Java JOptionPane, The JOptionPane class is used to provide standard dialog boxes such as message dialog box, confirm dialog box and input dialog box. These dialog boxes are used

Error Messages not showing inside Alert Dialog Box

I would like to show an error message within an alert dialog box for password reset, however no error message shows inside the dialog pop up.

When clicking «Reset» the dialog box will close. However, entering in a valid email does show the toast message «Reset Email Sent»

The validations are 1) leaving the email address empty , 2)not giving a proper email

//onclick for forgot password forgotPText = findViewById(R.id.forgotPassText); forgotPText.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View v) < //start alert dialog View view = inflater.inflate(R.layout.reset_popup,null); reset_alert.setTitle("Forgot Password ?") .setMessage("Enter Email For Password Reset Link.") .setPositiveButton("Reset", new DialogInterface.OnClickListener() < @Override public void onClick(DialogInterface dialog, int which) < //validate the email address is not empty or not valid email EditText email = view.findViewById(R.id.reset_popup_Email); String emailChar = email.getText().toString(); if (email.getText().toString().isEmpty())< email.setError("Required Field!"); return; >if(!Patterns.EMAIL_ADDRESS.matcher(emailChar).matches()) < email.setError("Please provide valid email!"); email.requestFocus(); return; >//send reset link firebaseAuth.sendPasswordResetEmail(email.getText().toString()) .addOnSuccessListener(new OnSuccessListener() < @Override public void onSuccess(Void aVoid) < //FirebaseUser user = firebaseAuth.getCurrentUser(); //updateUI(user); Toast.makeText(LoginActivity.this , "Reset Email Sent", Toast.LENGTH_SHORT).show(); >>).addOnFailureListener(new OnFailureListener() < @Override public void onFailure(@NonNull Exception e) < Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); >>); > >).setNegativeButton("Cancel",null) .setView(view) .create().show(); > >); 
forgotPText.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View v) < //start alert dialog LayoutInflater inflater = getLayoutInflater(); AlertDialog.Builder reset_alert = new AlertDialog.Builder(MainActivity.this); View view = inflater.inflate(R.layout.reset_popup,null); reset_alert.setView(view); EditText email = view.findViewById(R.id.email); TextView tv_cancel = view.findViewById(R.id.tv_cancel); TextView tv_submit = view.findViewById(R.id.tv_submit); tv_cancel.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View view) < InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); new Handler().postDelayed(new Runnable() < @Override public void run() < alertDialog.dismiss(); >>, 200); > >); email.setOnFocusChangeListener(new View.OnFocusChangeListener() < @Override public void onFocusChange(View v, boolean hasFocus) < if (!hasFocus) < InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0); >> >); tv_submit.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View view) < InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); String emailChar = email.getText().toString(); if (email.getText().toString().isEmpty())< email.setError("Required Field!"); return; >if (!Patterns.EMAIL_ADDRESS.matcher(emailChar).matches()) < email.setError("Please provide valid email!"); email.requestFocus(); return; >//send reset link firebaseAuth.sendPasswordResetEmail(email.getText().toString()) .addOnSuccessListener(new OnSuccessListener() < @Override public void onSuccess(Void aVoid) < //FirebaseUser user = firebaseAuth.getCurrentUser(); //updateUI(user); Toast.makeText(LoginActivity.this , "Reset Email Sent", Toast.LENGTH_SHORT).show(); >>).addOnFailureListener(new OnFailureListener() < @Override public void onFailure(@NonNull Exception e) < Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); >>); > >); alertDialog = reset_alert.create(); alertDialog.setCanceledOnTouchOutside(false); alertDialog.show(); > >); //////// reset_popup.xml        

How to present a simple alert message in java?, Call «setWarningMsg()» Method and pass the text that you want to show. exm:- setWarningMsg(«thank you for using java»); public static void

Источник

Оцените статью