How can I create a dialog box in Java with Yes No and cancel buttons?

Java 8Object Oriented ProgrammingProgramming

For a dialog box with Yes No Cancel buttons, you need to use the JOptionPane.showConfirmDialog(), wherein you will get a confirmation dialog box.

The following is an example to create a dialog box in Java with Yes No and cancel buttons −

Example

package my;
import java.awt.Dimension;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
public class SwingDemo {
   public static void main(String[] args) {
      ImageIcon icon = new ImageIcon("E −\\new.PNG");
      JPanel panel = new JPanel();
      panel.setSize(new Dimension(250, 100));
      panel.setLayout(null);
      JLabel label1 = new JLabel("The file may contain virus.");
      label1.setVerticalAlignment(SwingConstants.BOTTOM);
      label1.setBounds(20, 20, 200, 30);
      label1.setHorizontalAlignment(SwingConstants.CENTER);
      panel.add(label1);
      JLabel label2 = new JLabel("Do you still want to save it?");
      label2.setVerticalAlignment(SwingConstants.TOP);
      label2.setHorizontalAlignment(SwingConstants.CENTER);
      label2.setBounds(20, 80, 200, 20);
      panel.add(label2);
      UIManager.put("OptionPane.minimumSize", new Dimension(400, 200));
      int res = JOptionPane.showConfirmDialog(null, panel, "File",
      JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, icon);
      if(res == 0) {
         System.out.println("Pressed YES");
      }
      else if (res == 1){
         System.out.println("Pressed NO");
      } else {
         System.out.println("Pressed CANCEL");
      }
   }
}

Output

Now, let’s say we clicked on the Yes button. In that case, we have displayed the following on Console. Here, 0 is returned for YES, 1 for NO and 2 for CANCEL −

raja
Published on 31-May-2019 11:30:09
Advertisements