JDialog and JOptionPane

Could anyone please help me with this. I'm getting a class cast exception when I run this code.
final JOptionPane optionPane = new JOptionPane(message+"\nOk to proceed?",JOptionPane.QUESTION_MESSAGE,JOptionPane.YES_NO_OPTION);
     final JDialog dialog = new JDialog();
     dialog.setContentPane(optionPane);
     dialog.setDefaultCloseOperation(
          JDialog.DO_NOTHING_ON_CLOSE);
          dialog.addWindowListener(new WindowAdapter() {
               public void windowClosing(WindowEvent we) {
               JOptionPane warn = new JOptionPane();
               warn.showMessageDialog(null,"You must choose an action!","Warning",JOptionPane.WARNING_MESSAGE);
     optionPane.addPropertyChangeListener(
          new PropertyChangeListener() {
               public void propertyChange(PropertyChangeEvent e) {
                    String prop = e.getPropertyName();
                    if (dialog.isVisible()
                    && (e.getSource() == optionPane)
                    && (prop.equals(JOptionPane.VALUE_PROPERTY) ||
                         prop.equals(JOptionPane.INPUT_VALUE_PROPERTY))) {
                              //Do Check here
                              dialog.setVisible(false);
               dialog.pack();
               dialog.setVisible(true);
               int value = ((Integer)optionPane.getValue()).intValue();
               if (value == JOptionPane.YES_OPTION) {
                    returnInt = 1;
               } else if (value == JOptionPane.NO_OPTION) {
                    returnInt = 0;
               } else {returnInt = 5;}
return returnInt;
I use a small applet to call this method and pass it parameters.
thanks

Hi,
You have to check if a user has made a choice before casting optionPane.getValue to Integer. If the user has not made any selection yet, the object - JOptionPane.UNINITIALIZED_VALUE, which cannot be cast into Integer, will be returned.
Try adding the following to your code:
if (optionPane.getValue() != JOptionPane.UNINITIALIZED_VALUE) {
value = ((Integer) optionPane.getValue()).intValue();
or you could use a while loop to wait for a user to make a selection.

Similar Messages

  • JButton in JDialog vs JOptionPane

    I have created two different JDialogs, one with JOptionPane and one in the old-fashioned way. My problem is that the buttons in the different JDialogs get different appearence (I'm usings javas Metal L&F). Take a look at this sample code:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class TestFrame extends JFrame implements ActionListener {
       JDialog dialog1;
       JDialog dialog2;
       JButton button1;
       JButton button2;
       JButton dialogButton;
       public TestFrame() {
          button1 = new JButton("Open dialog 1");
          button1.addActionListener(this);
          button2 = new JButton("Open dialog 2");
          button2.addActionListener(this);
          getContentPane().add(button1, BorderLayout.NORTH);
          getContentPane().add(button2, BorderLayout.SOUTH);
          pack();
          setVisible(true);
       public static void main(String args[]) {
          new TestFrame();
       public void openDialog1() {
          JOptionPane vAbout = new JOptionPane("Just some text...", JOptionPane.INFORMATION_MESSAGE);
          dialog1 = vAbout.createDialog(this, "Dialog 1");
          dialog1.show();
       public void openDialog2() {
          dialog2 = new JDialog(this, "Dialog 2", true);
          GridBagLayout gbl = new GridBagLayout();
          GridBagConstraints gbc = new GridBagConstraints();
          dialog2.getContentPane().setLayout(gbl);
          JLabel text = new JLabel("Just some text...");
          dialogButton = new JButton("OK");
          dialogButton.addActionListener(this);
          dialog2.getContentPane().add(text, gbc);
          gbc.gridy = 1;
          dialog2.getContentPane().add(dialogButton, gbc);
          dialog2.pack();
          dialog2.setVisible(true);
       public void actionPerformed(ActionEvent e) {
          System.out.println(e.getSource());
          if (e.getSource() == button1)
             openDialog1();
          if (e.getSource() == button2)
             openDialog2();
          if (e.getSource() == dialogButton)
             dialog2.dispose();
       protected void processWindowEvent(WindowEvent e) {
          super.processWindowEvent(e);
          if(e.getID() == WindowEvent.WINDOW_CLOSING) {
             System.exit(0);
    }How can I get my button in dialog2 to look the same as the button in dialog1?

    To set the button to be default, you need some modification. Here's the basic frame work:
    public class TestFrame() extends JFrame
       //Your constructor
       public TestFrame()
          //Do stuff in here
          myDialog mydialog = new myDialog(this);
          mydialog.show()
       public static void main(String[] args)
          //etc
       private void SomeOtherMethods()
           //Declare your JOptionPane
    public class myDialog extends JDialog
       //Constructor
       public myDialog()
           //Add Components like usual
           getRootPane.setDefaultButton(DialogButton);
           getContentPane.add(Your_Panels);
        private void SomeOtherMethods()
    }Basically, you're taking your JDialog and placing it in it's own class (which is better anyway, trust me). Then it will set the button as the default and make the border darker.
    Let me know if you have anymore questions.

  • Is there any way to wait for a value without using JDialog or JOptionPane?

    I am implementing a dictionary program by detecting word in a JTextPane and asking a user to choose one of available meanings from JOptionPane or JDialog. The program runs under a while-loop until all dictionary words are detected or a user clicks cancel.
    However, I don't want to use JDialog or JOptionPane because it is sometimes annoying to have a popup window on every detected dictionary word.
    So, I use JList with Buttons on the same Frame as the JTextPane. However, now, the program does not stop when it detects a dictionary word. It just uses a default value of the JList for translating word to meaning.
    Is there any way I can simulate the JDialog or JOptionPane without using it?
    I mean I'd like to stopp the program temporary, wait for an answer from other components, and then continue to detect the next dictionary word.
    Thank you.

    I'm probably reading this all wrong, but instead of the while loop,
    the method just looked for a dictionary word from a particular caretPosition,
    so, to start, it would be findWord(0)
    when found, add whatever to wherever, note the caretPostion at the end of the 'found' word, and method returns.
    when the user selects whatever button, the button's actionListener also calls the method again, using the noted caretPosition
    findWord(42);
    so, it starts searching from 42 (instead of the start)
    basically it is event driven
    findWord sets the button/s
    click a button starts findWord

  • Problem with JDialogs and Threads

    Hi. I'm new to this forum and I hope I'm not asking a repeat question. I didn't find what I needed after a quick search of existing topics.
    I have this problem with creating a new JDialog from within a thread. I have a class which extends JDialog and within it I'm running a thread which calls up another JDialog. My problem is that the JDialog created by the Thread does not seem to function. Everything is unclickable except for the buttons in the titlebar. Is there something that I'm missing out on?

    yeah, bad idea, don't do that.

  • How to  pass data between JDialog and its parent window ?

    Hi,
    I am new to swing. I want to know how pass data between a JDialog and its parent window.
    If you have any information please reply with example code.
    Thank You

    hi Encephalopathic ,
    I was looking for something like as it was given in the link provided by you.
    Thank you for reply It really helped me.

  • Jdialog and jframe

    Hi.
    I have a problem
    I have a jdialog and when i click on a button i need open a jframe.
    i do this but the jframe is not active or not enable.
    Can you help me?
    Thanks

    Hi,
    It should work, so please post some code

  • JDialog and modality

    Hello,
    I'm wondering if my thinking is correct. If you create a jDialog box like this: JOptionPane.showMessageDialog(null, "some message here."); It's modal but since there is no parent frame it act non modal?
    And if you create it like this, JOptionPane.showMessageDialog(frame, "some message here."); Actually specifying the parent, it will act modal?
    Thank You!

    Hello,
    I see in the java tutorials it says "+A Dialog can be modal. When a modal Dialog is visible, it blocks user input to all other windows in the program. JOptionPane creates JDialogs that are modal. To create a non-modal Dialog, you must use the JDialog class directly.+" I'm using JOptionPane in both my test cases.
    I'm using the most basic test case I can think of:
    public class MyTestingApp {
        public static void main(String[] args) {
            JFrame frame = new JFrame("FrameDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
            JOptionPane.showMessageDialog(null, "My message.");
    }I cannot reproduce the problem, it always behaves modal as camickr expected. Only thing is, in my real application the dialog box appears underneath the main application window on rare occasion. I've seen it happen once in the field. I've also seen examples online where the word keyword this+ (referring to the parent objects name) was used instead of null or using the parent frame name. It doesn't seem to matter which is used, in the documentation or an application.
    Thanks,
    Sc

  • Problem with Enter key and JOptionPane in 1.4

    Hi,
    I had a problem with an application I was working on.
    In this application, pressing [Enter] anywhere within the focused window would submit the information entered into the form that was contained within the frame.
    The application would then try to validate the data. If it was found to be invalid, it would pop up a JOptionPane informing the user of that fact.
    By default, pressing [Enter] when a JOptionPane is up will activate the focused button (in most cases, the [OK] button) thus dismissing the dialog.
    In JDK 1.3 this worked fine. But in JDK 1.4, this has the result of dismissing the dialog and opping it up again. This is because the [Enter] key still works on the frame behind the JOptionPane and thus tries to validate it again, which results in another invalid dialog msg popping up.
    The only way to get out is to use the mouse or the Esc key.
    Now, in the application I put in a workaround that I was not very happy with. So, to make sure it wasn't the application itself, I created a test which demonstrates that it still misbehaves.
    Here it is.
    import java.awt.Container;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.AbstractAction;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JTextField;
    import javax.swing.KeyStroke;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    import javax.swing.WindowConstants;
    * @author avromf
    public class FocusProblemTest extends AbstractAction
         private static JFrame frame;
         public FocusProblemTest()
              super();
              putValue(NAME, "Test");
         public void actionPerformed(ActionEvent e)
              JOptionPane.showMessageDialog(frame, "This is a test.");
         public static void main(String[] args)
              FocusProblemTest action= new FocusProblemTest();
              try
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch (Exception e)
                   e.printStackTrace();
              frame= new JFrame("Test");
              frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
              Container contents= frame.getContentPane();
              contents.setLayout(new FlowLayout());
              JTextField field= new JTextField("Test");
              field.setColumns(30);
              JButton  button= new JButton(action);
              KeyStroke enterKey = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true);
              button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(enterKey, "test");
              button.getActionMap().put("test", action);
              contents.add(field);
              contents.add(button);
              frame.pack();
              frame.setVisible(true);
    }Does anyone have any solution to this problem?

    I know that focus management has changed alot.
    Based on my experimentation a while back, in 1.4 it still believes that the JFrame is the window in focus, even though a JOptionPane is currently in front of it (unless I misinterpreted what was going on). Thus, the frame seems to get the keyboard event and re-invoke the action.
    A.F.

  • Problem: modal JDialog and keyListeners

    I have some code like this:
    MyDialog extends JDialog {
    MyDialog () {
    super(someFrame, "", false);
    add(someComponent);
    someComponent.addKeyListener(listener);
    listener receives events just as I expect. Now I need to make a modal dialog and change false to true. in this case listener don't receive any events. Why? What is wrong and how should I fix it?
    However, if I create non-modal dialog, add key listener and use setModal(true) after, everything seems to work just fine. Maybe it's just a bug in java?

    Finally, I figured out the reason. Here is the code:
    class MyDialog extends JDialog {
    MyDialog() {
    super(someFrame, "", true);
    // GUI initialisation
    pack();
    someComponent.addKeyListener(listener);
    setVisible(true);
    In this case, listener receives events. But if I add listener AFTER setVisible, it does receive nothing. In case of non-modal dialog, listener receives events in both cases.

  • InputVerifier and JOptionPane.showMessageDialog

    Since I have intalled JDK 1.4. I have got the following Problem:
    in the verify Method there is a call to JOptionPane.showMessageDialog
    in order to show a error message if the input doesn�t match and before false is returned.
    It doesn�t work anymore with 1.4. In case of error, the message Dialog is not coming up and the verify methodis just called in a endless loop.

    try setting the InputVerifier to null before displaying the JOptionPane, then set it back after the JOptionPane.
    textField.setInputVerifier(null)
    JOptionPane.showMessageDialog(...)
    textField.setInputVerifier(this)

  • JDialog and request focus

    Hi
    I am designing an application that brings up a JDialog box. When a button is pressed on this JDialog box this triggers an action event and some code is executed.
    When this button is pressed I dispose the dialog box and I want the focus to change to one of my components, I have been doing this with the requestFocus command. For some reason this focused event is not picked up by the focus handler. This only happens in this one place, if I move the requestFocus code to anywhere else in the program the focus event works fine. Does anyone have any ideas why.
    Thanks

    Without seeing any code, I would guess that disposing of a dialog causes focus changes to be requested internally. So if you put your focus change request after you dispose the dialog, that might help.

  • InputVerifier and JOptionPane help please

    I am trying to create an application and require to validate input fields. I have successfully written the code to use the InputVerifier class to validate the input but want to use a JOptionPane dialog to notify errors. This doesn't seem to work as the JOption Pane is treated as an attempt to shift focus from the field being validated (which calls shouldYieldFocus() which tries to show a JOptionPane which tries to shift focus .........). I have a temporary fix by using an disabled text field to display the message but it isn't very elegant. Anyone any ideas please ?

    Did you get any solution?
    I am also facing the same problem but with Jdk 1.4 only.
    In Jdk 1.3 it's working fine.
    Please let me know if u have any solution

  • JSP and JOptionPane - show confirm on top

    When a user clicks the Exit button on my JSP page, I have a page handler to display a confirm dialog to ask the user if they are sure they want to exit without saving.
    If the user clicks OK, it redirects them back to the home page. If they click Cancel, it takes them back to the form. With the code below, the alert works fine except for 2 problems:
    1. The confirm dialog does not pop up in front of the current window. You have to minimize the form to see the dialog.
    2. All fields are erased if you choose the cancel option from the confirm dialog.
    Code:
    int choice =
    JOptionPane.showConfirmDialog(null, "Are you sure you want to exit? This application will not be saved.", "Exit without saving?", 2);
    if (choice == JOptionPane.OK_OPTION)
    res.sendRedirect("index.jsp");
    Any help is appreciated.
    Thanks!

    you want to have some sort of visible component where that null is
    int choice =
    JOptionPane.showConfirmDialog(null, "Are you sure you want to exit? This application will not be saved.", "Exit without saving?", 2);
    should/could be JOptionPane.showConfirmDialog(THIS, ...) // 'this' is in caps just to highlight change. //Should be lower case
    I'm not quite sure this will work, but if you have any components that you can give this method, it will work. If not, you can create your own component and use component.requestFocus to bring it to the front
    Hope that helps.

  • Help with JDialog and JFrame

    I have a class that extends JDialog to display images in a slide show. I use the action performed method of a button in my main Jframe Application to start the slideshow .
    When the button is clicked the JDialog opens multiple windows and the images arent displayed properly at all . But when I tested the slideshow of Jdialog separately , it works.
    Here is the code of the Jdialog part
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    import java.awt.event.*;
    public class Test extends JDialog implements ActionListener
    {  private Image img; 
    private     JMenuBar     menuBar;
    private     JMenu          menuStart;
    public Vector images = new Vector();
    public Test()
    for (int i = 1; i < 8; i++)
    {      images.add(new ImageIcon("gty"+i+".jpg").getImage());  
    menuBar = new JMenuBar();
         setJMenuBar( menuBar );
         menuStart = new JMenu( "Start" );
         menuStart.setMnemonic( 'S' );
         menuStart.addActionListener(this);
         menuBar.add( menuStart );
    setSize(600, 600);
    setVisible(true);
    showImages(images);
    private void showImages(Vector images) {
    for (int i = 1; i < images.size(); i++)
    img = (Image) (images.elementAt(i));
    int imgWidth = img.getWidth(this);
    int imgHeight = img.getHeight(this);
    setSize( imgWidth, imgHeight );
    JLabel temp=new JLabel(new ImageIcon(img));
    this.getContentPane().add(temp);
    pack();
    setVisible(true);
    try { Thread.sleep(2000);
    } catch (Exception e) {} //do nothing
    getContentPane().remove(temp);
    pack();
    setVisible(true);
    public void actionPerformed( ActionEvent event )
    public static void main(String[] arghs)
    {//new Test(null,true);
    In the main application I just gave created an object of this type test
    i.e new Test();
    I have tried changing the constructor of the Jdialog to include parent frame and modal , but it still dosen't work . Help !

    when you declare the final variables, it should be initialized otherwise you will get error
    private final JTabbedPane tabbedPane; //not assigned yet should be
    private final JTabbedPane tabbedPane = new JTabbedPane()

  • Never used JWindow&JDialog and was very happy

    Hi guys!
    I am stuck on simple task. I wanted to place my jpanel into jwin or jdialog so this panel could resize and be dragged inside the JFrame. It would look very neat. Of course I don't want the stupid title bar.
    JWindow turned out to be not resizable and non-movable. Well, I saw people put mouse listeners on it but it does not solve resizability problem.
    JDialog (1.4 jdk) when undecorated is also not resizable (.setResizable(true))and not movable.
    Do you have any idea how to accomplish this task? Will be very grateful.

    I did my best and got almost what I wanted. Some things depend on their native implementations. Nothing I could do.
    I think that JWindows and JDialog are very tricky and devious components. One should stay away from them as far as possible because it's very difficult to make them do what you want: be simple, draggable, freely resizable and stay on top of their owner.

Maybe you are looking for