Problem in JOptionPane

Hi,
Here's my problem, I'm making a dialog box with a JOptionPane
and I'm using a OK_CANCEL_OPTION and the method showOptionDialog(...).
When I click on the Cancel button, the value returned is 1
but the constant JOptionPane.CANCEL_OPTION=2.
I have to put an else to put the value of cancelled to true.
So what's the matter ?
int choice = JOptionPane.showOptionDialog(null, ConnectionPanel, title,
                         JOptionPane.OK_CANCEL_OPTION,
                         JOptionPane.INFORMATION_MESSAGE, null,
                         ConnectOptionNames, ConnectOptionNames[0]);                                                  
System.out.println("choice : " + choice);
System.out.println("CANCEL_OPTION" + JOptionPane.CANCEL_OPTION);
if (choice == JOptionPane.OK_OPTION) {       
    System.out.println("OK_OPTION" + JOptionPane.OK_OPTION);          
} else if (choice == JOptionPane.CANCEL_OPTION) {     
    // why is this value never got ?
    // JOptionPane.CANCEL_OPTION=2 but choice=1
    cancelled = true;
    System.out.println("CANCEL_OPTION" + JOptionPane.CANCEL_OPTION);
} else if (choice == JOptionPane.CLOSED_OPTION) {               
    cancelled = true;
    System.out.println("CLOSED_OPTION" + JOptionPane.CLOSED_OPTION);
} else cancelled = true; // another bug of Java---------------------
Thanks in advance
Yann P.
JOnAS 2.5 http://www.objectweb.org/jonas/
------------------

that JOptionPane.CANCEL_OPTION is the int taken by the joptionpane constructor to tell it to display only a cancel option...
track the int it returns and set it as that, as the int will never change!

Similar Messages

  • Strange problem with JOptionPane.showInputDialog

    I have a strange problem with JOptionPane.showInputDialog in that when I run a program anything that is typed in is displayed backwards, for example: I type this character > and this < is what is displayed.
    I've uninstalled the sdk and reinstalled it twice but that hasn't solved my problem and the java plug-in in the control panel is displaying the same symptoms.
    I did a search before posting this but all I got really was posts from people who wanted to reverse their text.
    Thanks for your help on this.

    Is it just the < and > characters?

  • Customized KeyboardFocusManager problems with JOptionPane-Dialogs

    Hi,
    I have a problem I'm not able to solve: With Java 1.4.2 unter Linux, as well as all newer Java Versions (1.4, 1.5, 1.6) under Windows, dialogs created by JOptionPane.showXXXDialog do not react to keyboard events like <Tab> any more when using a customized KeyboardFocusManager. Java 1.5 and 1.6 under Linux work fine.
    Here is what I did:
    I have a JFrame and want some customized focus control when navigating through the Frame with <Tab>. Therefore I've implemented a class
    public class EfaFrameFocusManager extends DefaultKeyboardFocusManagereand said in the main JFrame:
    EfaFrameFocusManager myFocusManager = new EfaFrameFocusManager(this,FocusManager.getCurrentKeyboardFocusManager());
    FocusManager.setCurrentKeyboardFocusManager(myFocusManager);The constructor of my EfaFrameFocusManager stores the JFrame (this) and the original KeyboardFocusManager (2nd arg) for later use. Within my own FocusManager, I've implemented the method
    public void processKeyEvent(Component cur, KeyEvent e)which is checking whether the desired Frame (efaFrame) is currently active or not. If it is active, it's performing my customized operations which is working well. If it is not active (e.g. because a dialog created with JOptionPane.showConfirmDialog() is open), it should perform default actions. So I said within processKeyEvent:
    if (!efaFrame.isActive()) { // efaFrame is the previous "this" arg
      fm.processKeyEvent(cur,e); // fm is the previously stored CurrentKeyboardFocusManager
      return;
    }Instead of invoking processKeyEvent on the original KeyboardFocusManager fm, I also tried super.processKeyEvent(cur,e);, but without any change in behavior.
    As I said before, this is working well under Java 1.5 and 1.6 with Linux.
    However, it is not working unter Windows (any Java version I tried, including 1.4, 1.5 and 1.6) and also not unter Linux with Java 1.4. With these combinations, dialogs created by JOptionPane.showXXXDialog(...) do not respond to the <Tab> key. I do see that my own FocusManagers processKeyEvent method is invoked, and I also see that it invokes the one of the original FocusManager, but the Dialog doesn't react.
    What am I doing wrong?
    Nick.

    I have a JFrame and want some customized focus control when navigating
    through the Frame with <Tab>. sounds like you should be doing this via a FocusTraversalPolicy
    http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html#customFocusTraversal

  • Keyboard problems with joptionpane.ShowConfirm

    hello,
    I am using show confirm dialog and there is a yes and no button with it.
    I want the software to exit when the user clicks yes button.
    the code works fine when the user uses mouse. but when I use the enter key on yes or no button, the application exits in both the cases.
    further more if I perform the same action with the space bar on the keyboard it still works fine and when I hit space bar on the no button the application stays. but with enter key the application doesn't seam to take the right yes/ no value in the integer.
    what's the problem
    and how do I correct it.
    thanks
    Krishnakant.

    import javax.swing.*;
    class Testing
       public Testing()
          try{UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");}
          catch(Exception e){e.printStackTrace();}
          int btn = JOptionPane.showConfirmDialog(null,"tab to a button, then press [ENTER]",
                                                             "",JOptionPane.YES_NO_OPTION,-1);
          String selection = "Escape (or 'x') selected";
          if(btn == 0) selection = "Selection = 'Yes'";
          else if(btn == 1)  selection = "Selection = 'No'";
          JOptionPane.showMessageDialog(null,selection);
          System.exit(0);
      public static void main(String[] args){new Testing();}
    }

  • Problems with JOptionPane and intrrupting

    1.when i interrupt in main a thread,
    and the thread is executing a JOptionPane-Message,
    the interrupt is lost, if the thread is asking isInterrupted() bevor show Message, the Interrupt is visible. ITS A BUG?
    2. if a thread is creating a new JFrame() and obtains an interrupt, a error of JVM is reported:
    AWT blocker activation interrupted:
    java.lang.InterruptedException
    What can i do? please help me???

    Well what are you trying to interrupt, and why?
    I think the interrupt was meant to be used for when the application is shutting down. So those two problems of yours seem normal. Most other application wouldn't close while a dialog box was up, right?
    If you're trying to synchronize threads, look into the wait() and notify() methods in the Object class.

  • Problem wit JOptionPane.showMessageDialog

    I'm not getting where is the problem here,
    JTextField = AlteKarte,jtf3;
    jtf3.addFocusListener(new FocusListener() {
    public void focusGained(FocusEvent e) {
    public void focusLost(FocusEvent e) {
    if (!e.isTemporary() && isEnabled() ) {
    String Alte = AlteKarte.getText();
    String FoneNum = jtf3.getText();
    if (Alte.length() != 0 ){
    if(Alte.equals("123") != FoneNum.equals("123")) {
    JOptionPane optionPane = new JOptionPane();
    int answer =((Integer)optionPane.getValue()).intValue();
    JOptionPane.showMessageDialog(MainEPOS.frame,"Geben Sie bitte gultige Karten-Seriennummer an.","Fehler",JOptionPane.WARNING_MESSAGE,null);
    if(answer == JOptionPane.OK_OPTION || answer == JOptionPane.CLOSED_OPTION){
    jtf3.requestFocus(true);
    [\code ]
    i'm getting java.lang.ClassCastException at line int answer =((Integer)optionPane.getValue()).intValue();
    [\code]

    i have made it this way :-
             jtf3.addFocusListener(new FocusListener() {
                  public void focusGained(FocusEvent e) {
                  public void focusLost(FocusEvent e) {
                    if (!e.isTemporary() && isEnabled() ) {
                      String Alte = AlteKarte.getText();
                      String FoneNum = jtf3.getText();
                      if (Alte.length() != 0 ){
                           if(Alte.equals("123")  != FoneNum.equals("123")) {
                       JOptionPane optionPane = new JOptionPane();
                       Object[] options = {"OK"};
                       int answer =   JOptionPane.showOptionDialog(MainEPOS.frame,"Geben Sie bitte gultige Karten-Seriennummer an.","Fehler",JOptionPane.WARNING_MESSAGE,JOptionPane.OK_OPTION, null, options, options[0]);
                     //  int answer =((Integer) optionPane.getValue()).intValue();
                       if(answer == JOptionPane.OK_OPTION || answer == JOptionPane.CLOSED_OPTION){
                            jtf3.requestFocus(true);
          });but now the problem is, that it does not get closed at once.
    When i click OK then message appears again, and in second attempt it works.

  • Serialization problems with JOptionPane

    Hi,
    I am having a problem attempting to serialize and deserialize a JOptionPane contained within a JPanel running in an applet.
    The code is straightforward enough:
    JOptionPane m_pane = new JOptionPane("Hello world !!");
    contentPane.add( m_pane, "Center" );
    While displaying the above contentPane, the applet is serialized.
    On deserializing the application, no deserilization errors are reported. However, the font, the borders, and the position of the (default) OK button are all altered. If I then attempt to serialize/deserialize for a second time, serialization fails, and a lengthy error message is written to the console. Here's a snippet of the console message:
    readObject - javax.swing.JOptionPane[,0,0,296x90,invalid,alignmentX=0.0,alignmentY=0.0,border=,flags=-15896,maximumSize=,minimumSize=,preferredSize=,icon=,initialValue=,message=Hello world!!,messageType=PLAIN_MESSAGE,optionType=DEFAULT_OPTION,wantsInput=false]
    Serialization Failed: Reason java.lang.Objectjava.io.NotSerializableException: java.lang.Object
    java.io.NotSerializableException: java.lang.Object
         at java.io.ObjectOutputStream.writeObject0(Unknown Source)
    If I add a simple JPanel (instead of a JOptionPane) to contentPane, then no problems are exhibited.
    Has anyone came across this issue before?
    Thanks.

    Maintaining serialized objects across versions is a problem. There are no easy solutions.
    Have you searched the site for other threads on the subject?

  • STRANGE problem with JOptionPane.showMessageDialog .. HELP!!!

    Please look at the code below and tell me what is wrong with it and my code is very very very simple!!! And I can't seem to understand why this error is coming up.
    import javax.swing.JOptionPane;
    public class ShowMessageDialog {
    public ShowMessageDialog() {
    //empty constructor for now
    public void show () {
    JOptionPane.showMessageDialog (null, "Please try again!!", "Error Message", JOptionPane.ERROR_MESSAGE);
    }This class is invoked by another class named SendPacketBack which does nothing but checks for one condition in an if statment and then make an object of this class and calls this show() method and this error comes up. Please look at the error below and tell me why it is telling me java.lang.NoClassDefFoundError and not telling me which class???
    java.lang.NoClassDefFoundError
         at java.lang.Class.forName0(Native Method)
         at java.lang.Class.forName(Class.java:141)
         at java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(GraphicsEnvironment.java:62)
         at sun.awt.motif.MToolkit.<clinit>(MToolkit.java:81)
         at java.lang.Class.forName0(Native Method)
         at java.lang.Class.forName(Class.java:141)
         at java.awt.Toolkit$2.run(Toolkit.java:748)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.awt.Toolkit.getDefaultToolkit(Toolkit.java:739)
         at javax.swing.ImageIcon.<init>(ImageIcon.java:205)
         at javax.swing.LookAndFeel$1.createValue(LookAndFeel.java:274)
         at javax.swing.UIDefaults.getFromHashtable(UIDefaults.java:184)
         at javax.swing.UIDefaults.get(UIDefaults.java:129)
         at javax.swing.MultiUIDefaults.get(MultiUIDefaults.java:44)
         at javax.swing.UIDefaults.getIcon(UIDefaults.java:410)
         at javax.swing.UIManager.getIcon(UIManager.java:537)
         at javax.swing.plaf.basic.BasicOptionPaneUI.getIconForType(BasicOptionPaneUI.java:555)
         at javax.swing.plaf.basic.BasicOptionPaneUI.getIcon(BasicOptionPaneUI.java:543)
         at javax.swing.plaf.basic.BasicOptionPaneUI.createMessageArea(BasicOptionPaneUI.java:313)
         at javax.swing.plaf.basic.BasicOptionPaneUI.installComponents(BasicOptionPaneUI.java:154)
         at javax.swing.plaf.basic.BasicOptionPaneUI.installUI(BasicOptionPaneUI.java:122)
         at javax.swing.JComponent.setUI(JComponent.java:449)
         at javax.swing.JOptionPane.setUI(JOptionPane.java:1693)
         at javax.swing.JOptionPane.updateUI(JOptionPane.java:1715)
         at javax.swing.JOptionPane.<init>(JOptionPane.java:1678)
         at javax.swing.JOptionPane.showOptionDialog(JOptionPane.java:828)
         at javax.swing.JOptionPane.showMessageDialog(JOptionPane.java:642)
         at javax.swing.JOptionPane.showMessageDialog(JOptionPane.java:613)
         at cc.ShowMessageDialogue.show(ShowMessageDialogue.java:13)
         at cc.SendPacketBack.sendPacketTo(SendPacketBack.java:62)
    I would appreciate any suggestions or advice to solve this issue.
    Regards
    Khurram

    Yes X server is alright. I should have mentioned one thing though in my previous email is that there is another class which extends JFrame and is part of the package that this class is in also running in the background but that class does not interact with this class at all and does not even know if it exists!
    I don't know if that thing is causing some kind of problem which is not coming up here?
    Khurram

  • Problem w/JOptionPane showConfirmDialog

    Okay, I have a JOptionPane.showConfirmDialog on a JInternalFrame that works for the most part, but is doing something weird. When a user clicks the Cancel option or closes the JOptionPane, I want it simply to go away. Instead, it will pop up again, and if the user click Cancel or closes the window, it will go away, but it will take the JInternalFrame with it, which I don't want it to do. I have the code pasted below, and it should work the way I have it coded, but it don't. Anyone help??int result = JOptionPane.showConfirmDialog(CustomFrame.this, getTitle() +
       " has been changed. Would you like to save?", "Save File?", JOptionPane.YES_NO_CANCEL_OPTION,
       JOptionPane.WARNING_MESSAGE);
       switch(result)
          default:
             break;
          case JOptionPane.YES_OPTION:
             save();
             break;
          case JOptionPane.NO_OPTION:
             dispose();
             break;
          case JOptionPane.CANCEL_OPTION:
             break;
       }Now this is being triggered from the internalFrameClosing method of the InternalFrameListener interface that is implemented on a private class in my JInternalFrame constructor. And like I said, all other aspects of it work fine and when it's supposed to, but with the Cancel option or closing the JOptionPane (which would trigger the default: option from the switch construct, correct?), I want it to go away. It will pop up a second time, then go away with the JInternalFrame. Any suggestions? Thanks a lot. I'm using JDK 1.4.1 for the Macintosh (15" iMac G4).
    James

    Okay, I have a JOptionPane.showConfirmDialog on a JInternalFrame that works for the most part, but is doing something weird. When a user clicks the Cancel option or closes the JOptionPane, I want it simply to go away. Instead, it will pop up again, and if the user click Cancel or closes the window, it will go away, but it will take the JInternalFrame with it, which I don't want it to do. I have the code pasted below, and it should work the way I have it coded, but it don't. Anyone help??int result = JOptionPane.showConfirmDialog(CustomFrame.this, getTitle() +
       " has been changed. Would you like to save?", "Save File?", JOptionPane.YES_NO_CANCEL_OPTION,
       JOptionPane.WARNING_MESSAGE);
       switch(result)
          default:
             break;
          case JOptionPane.YES_OPTION:
             save();
             break;
          case JOptionPane.NO_OPTION:
             dispose();
             break;
          case JOptionPane.CANCEL_OPTION:
             break;
       }Now this is being triggered from the internalFrameClosing method of the InternalFrameListener interface that is implemented on a private class in my JInternalFrame constructor. And like I said, all other aspects of it work fine and when it's supposed to, but with the Cancel option or closing the JOptionPane (which would trigger the default: option from the switch construct, correct?), I want it to go away. It will pop up a second time, then go away with the JInternalFrame. Any suggestions? Thanks a lot. I'm using JDK 1.4.1 for the Macintosh (15" iMac G4).
    James

  • JOptionPane Problem, pls reply

    Hi, I am having a problem with JOptionPane that I have noticed other people have had but I could not find a solution. Here it is:
    When I use a Showconfirmdialog. It works fine in the develop. environment buts has a bug when I view it in a browser. About 20% of the time, it cuts off the last two letters and replaces them with ... If I stretch the box out the message displays as it should.
    Here is my code:
    java.awt.Frame f = (java.awt.Frame)((MainTabPage)getController().getMainTabPage()).getParentContainer();
              int n = JOptionPane.showConfirmDialog(f,"Changes have been made. Would you like to save?", "User Profile", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
              if (n == JOptionPane.YES_OPTION){
                   this.btnSave_ActionPerformed(actionEvent);
                   return;
    and it goes on for the no and cancel option as well.
    ANY help would be greatly app.
    Thanks

    the best way should be to "pack()" the dialog, but as you can't access thatdialog instance...
    I suggest you use html tags :
    simply change your String :
    "Changes have been made. Would you like to save?"
    by
    "<html>Changes have been made. <br>Would you like to save?</html>"the <br> tag indicates a lineBreak
    moreover, you could use the tagts to display some parts of the string as bold or itaic of in colours...
    vincent

  • JOptionPane Text Wrap

    I'm trying to display text on a JOptionPane.showMessageDialog, but sometimes the the string can be so long the dialog box goes off the computer monitor. Is there a way to do text wrapping on a JOptionPane box?

    Just in case anyone is still struggling with this, I wrote a method that works well to correct the problem. Sorry to dig up an old thread, but I just now joined the forum and saw this was still in stasis.
    Hope it helps someone.
        public String wrapText(String passedStr)
            * This method solves the problem of JOptionPanes not automatically   *
            * wrapping long lines of text.  Set the LINE_LENGTH constant to      *
            * the length you want each line to be.  A newline character will be  *
            * inserted at the first whitespace after each character located at   *
            * the LINE_LENGTH postition.                                         *
            * Known problem:                                                     *
            *  - Traditional double-whitespace that appears between sentences    *
            *    can sometimes result in lines starting with whitespace, causing *
            *    the left edge of the text to look jagged.  This can be "fixed"  *
            *    by only hitting the spacebar once between sentences.            *
              // Constant to indicate the length of each line.
              final short LINE_LENGTH = 80;
              // Variable to indicate the next carriage-return position.
              int nextCR = LINE_LENGTH;
              // Create a StringBuffer copy of the string to wrap (passedStr).
              StringBuffer newStr = new StringBuffer(passedStr);
              // Read entire string from beginning to end.
              for (int i = 0; i < newStr.length(); i++)
                   // Push back nextCR another LINE_LENGTH for all newlines found.
                   if (newStr.charAt(i) == '\n' || newStr.charAt(i) == '\r')
                        nextCR = i + LINE_LENGTH;
                   // Insert carriage-return at whitespace on or after nextCR.
                   if (newStr.charAt(i) == ' ' && i >= nextCR)
                        newStr.insert((i + 1), "\n");
                        nextCR += LINE_LENGTH;
              return newStr.toString();
         }Usage:
    JOptionPane.showMessageDialog(null, wrapText(stringThatNeedsWrapped), header, JOptionPane.PLAIN_MESSAGE);

  • JOptionPane keeps popping up behind windows

    I'm having trouble with my JOptionPane popping up behind my main window, rather than in front. On the advise of someone more experienced than me, I encased the JOptionPane in a JDialog, as follows:
    Object[] array =
            new JLabel("Enter some text:"),          };
         JOptionPane pane = new JOptionPane(array,
    JOptionPane.ERROR_MESSAGE);
         JDialog dialog = pane.createDialog(null, "Result
    Data"); 
    dialog.setResizable(true);
    dialog.setVisible(true);
         dialog.toFront();and it keeps appearing behind all my windows.
    The first time the program runs each session, it pops up behind all the windows, making hte program appear to hang. If I alt-Tab and bring it front, all is fine, and then subsequent iterations of the dialog come up in front
    Can anyone help me makes sure these boxes pop up in front every time?
    Thanks

    lkb3 wrote:
    The programming I"m doing is in an API for a CAD program - the Java is launched by the CAD program.
    This problem of JOptionPane's popping up behind the main window is a common one with this particular CAD program, and a guy who has done a lot of programming in this API advised me to create the dialogI'd try it without the dialog bypass to be sure, if I were you.
    What's the best way to specify the mainWindowReference? You simply need a reference to +any+ Component or Window. For instance, if you're executing that code in an event handler, you could simply use the event's source (provided that is actually a Component).

  • JOptionPane Help Needed

    I basically have two problems with JOptionPane that I've searched for answers yet I haven't found an applicable answer for my application. Here they are:
    1) How can I get a JPasswordField in a JOptionPane to be given focus when the JOptionPane is displayed?
    2) How can I get the default key mappings for JOptionPane not to work or atleast make it where when a user hits "Enter", it activates the button that has current focus? I have a problem with highlighting "Cancel" and hitting "Enter".
    Here is my code being used for the JOptionPane:
    String pwd = "";
    int tries = 0;
    JPasswordField txt = new JPasswordField(10);
    JLabel lbl = new JLabel("Enter Password :");
    JLabel lbl1 = new JLabel("Invalid Password.  Please try again:");
    JPanel pan = new JPanel(new GridLayout(2,1));
    int retval;
    while(tries < 3 && !valid)
         if(tries > 0)
              pan.remove(lbl);
              pan.remove(txt);
              pan.add(lbl1);
              pan.add(txt);
              txt.setText("");
         else
              pan.add(lbl);
              pan.add(txt);
         retval = JOptionPane.showOptionDialog(DBPirate.appWindow,pan,
         "Password Input",                              JOptionPane.OK_CANCEL_OPTION,                              JOptionPane.QUESTION_MESSAGE,
         null,null,null);
         if(retval == JOptionPane.OK_OPTION)
              pwd = new String(txt.getPassword());
              setPassword(pwd);
              if(cryptoUtil.testPassword(pwd))
                   valid = true;
              else
                   tries += 1;
         else
              System.exit(0);
    }Any help would be appreciated. Thanks, Jeremy

    Hello Jeremy,
    I am not too happy with my code, for I think there must be something more efficient and elegant. But after trying in vain with KeyListener and ActionMap this is presently the only way I could do it.
    // JOptionPane where the <ret>-key functions just as the space bar, meaning the
    // button having focus is fired.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ReturnSpace extends JFrame implements ActionListener
    { JButton bYes, bNo, bCancel;
      JDialog d;
      JOptionPane p;
      public ReturnSpace()
      { setSize(300,300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        Container cp= getContentPane();
        cp.setLayout(new FlowLayout());
        JButton b= new JButton("Show OptionPane");
        b.addActionListener(this);
        p=new JOptionPane("This is the question",
              JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION);
        d=p.createDialog(this,"JOptionPane with changing default button.");
        FocusListener fl= new FocusAdapter()
        { public void focusGained(FocusEvent e)
          {     JButton focusButton= (JButton)(e.getSource());
         d.getRootPane().setDefaultButton(focusButton);
        int i=1;
    //    if (plaf.equals("Motif")) i=2;
        bYes = (JButton)((JPanel)p.getComponent(i)).getComponent(0);
        bYes.addFocusListener(fl);
        bNo = (JButton)((JPanel)p.getComponent(i)).getComponent(1);
        bNo.addFocusListener(fl);
        bCancel = (JButton)((JPanel)p.getComponent(i)).getComponent(2);
        bCancel.addFocusListener(fl);
        cp.add(b);
        setVisible(true);
        d.setLocationRelativeTo(this);
      public void actionPerformed(ActionEvent e)
      { bYes.requestFocus();
        d.setVisible(true);
        Object value = p.getValue();
        if (value == null || !(value instanceof Integer))
        { System.out.println("Closed");
        else
        { int i = ((Integer)value).intValue();
          if (i == JOptionPane.NO_OPTION)
          { System.out.println("No");
          else if (i == JOptionPane.YES_OPTION)
          { System.out.println("Yes");
          else if (i == JOptionPane.CANCEL_OPTION)
          { System.out.println("Cancelled");
      public static void main(String argsv[])
      { new ReturnSpace();
    }Greetings
    Joerg

  • Displaying windows messages from an appln.

    Hi,
    I'm creating a no-window java program. In that, when some exception occures I need to display a message box decribing the problem (like JOptionPane). Is there any method to display message box from non-window application?
    Have a nice time
    Thanks in Advance

    Try Dialog

  • Variable might not have been initialized error in an assignment for school

    Hello All... I am very new to Java (started class about 2 weeks ago) and my current assignment has me a bit stumped on what I am doing wrong. I have put the code in this message for everyone to take a look at and offer advice or point me in the right direction on what I missed a step on. I appreciate any help you can offer.
    The error is coming on line 39:
    * Program: MathProgramExtra
    * Author: Michael Stewart
    * Date: August 22, 2010
    * Program Purpose: This program is intended to display selection and iterative statements.
    import javax.swing.*;
    public class MathProgramExtra
        public static void main (String[] args)
            Object[] mathPossibilities = {"+", "-", "*", "/", "%"};
            Object[] firstintegerPossibilities = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
            Object[] secondintegerPossibilities = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
            Object[] options = {"Yes, Please", "No, Thank You"};
            String m;
            String f;
            String s;
            int firstint;
            int secondint;
            int answer;
            char ans = 'Y';
            while(ans !='N')
                System.out.println("ans in beginning of loop is :"+ans);
                m = mathOp(mathPossibilities);
                f = firstNum(firstintegerPossibilities);
                s = secondNum(secondintegerPossibilities);
                firstint = firstNumConversion(f);
                secondint = secondNumConversion(s);
                performMath(m, firstint, secondint);
                add(m, firstint, secondint);
                subtract(m, firstint, secondint);
                multiply(m, firstint, secondint);
                divide(m, firstint, secondint);
                modulus(m, firstint, secondint);
                printMath(answer);
                ans = verifyAnswer(options);
                System.out.println("ans in end of loop is :"+ans);
                if (ans == 'Y')
                    continue;
                else
                    break;
            System.exit(0);
        public static String mathOp(Object[] possibilities)
            String sentence = "Please select a mathematical operation";
            String m = (String)JOptionPane.showInputDialog(null, sentence, "Operation Question",
            JOptionPane.PLAIN_MESSAGE, null, possibilities, "+");
            return m;
        public static String firstNum(Object[] possibilities)
            String sentence = "Please select an integer";
            String f = (String)JOptionPane.showInputDialog(null, sentence, "First Integer",
            JOptionPane.PLAIN_MESSAGE, null, possibilities, "0");
            return f;
        public static String secondNum(Object[] possibilities)
            String sentence = "Please select another integer";
            String s = (String)JOptionPane.showInputDialog(null, sentence, "Second Integer",
            JOptionPane.PLAIN_MESSAGE, null, possibilities, "1");
            return s;
        public static int firstNumConversion(String f)
            int firstint = 0;
            if(f.equals ("0"))
                firstint = 0;
            else if(f.equals("1"))
                firstint = 1;
            else if(f.equals("2"))
                firstint = 2;
            else if(f.equals("3"))
                firstint = 3;
            else if(f.equals("4"))
                firstint = 4;
            else if(f.equals("5"))
                firstint = 5;
            else if(f.equals("6"))
                firstint = 6;
            else if(f.equals("7"))
                firstint =7;
            else if(f.equals("8"))
                firstint = 8;
            else if(f.equals("9"))
                firstint = 9;
            else if(f.equals("10"))
                firstint = 10;
            return firstint;
        public static int secondNumConversion(String s)
            int secondint = 0;
            if(s.equals("1"))
                secondint = 1;
            else if(s.equals("2"))
                secondint = 2;
            else if(s.equals("3"))
                secondint = 3;
            else if(s.equals("4"))
                secondint = 4;
            else if(s.equals("5"))
                secondint = 5;
            else if(s.equals("6"))
                secondint = 6;
            else if(s.equals("7"))
                secondint =7;
            else if(s.equals("8"))
                secondint = 8;
            else if(s.equals("9"))
                secondint = 9;
            else if(s.equals("10"))
                secondint = 10;
            return secondint;
        public static int performMath(String m, int firstint, int secondint)
            int answer = 0;
            if (m.equals("+"))
            answer = add(m,firstint, secondint);
            if (m.equals("-"))
            answer = subtract(m,firstint, secondint);
            if (m.equals("*"))
            answer = multiply(m,firstint, secondint);
            if (m.equals ("/"))
            answer = divide(m,firstint, secondint);
            if (m.equals ("%"))
            answer = modulus(m, firstint, secondint);
            return answer;
        public static int add(String m, int firstint, int secondint)
            int answer;
            answer = (firstint + secondint);
            return answer;
        public static int subtract(String m, int firstint, int secondint)
            int answer;
            answer = (firstint - secondint);
            return answer;
        public static int multiply(String m, int firstint, int secondint)
            int answer;
            answer = (firstint * secondint);
            return answer;
        public static int divide(String m, int firstint, int secondint)
            int answer;
            answer = (firstint / secondint);
            return answer;
        public static int modulus (String m, int firstint, int secondint)
            int answer;
            answer = (firstint % secondint);
            return answer;
        public static void printMath(int answer)
            String message = "Your answer is:" + answer;
            JOptionPane.showMessageDialog(null, message, "Alert", JOptionPane.INFORMATION_MESSAGE);
        public static char verifyAnswer(Object[] options)
            char ans = 'N';
            int n = JOptionPane.showOptionDialog(null, "Would you like to enter another problem, Yes or No?", "Another Problem?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
            switch(n)
                case 0:
                    ans = 'Y'; break;
                case 1:
                    ans = 'N'; break;
            return ans;
       

    mstew1979 wrote:
    Thank you! I actually just got it working :)Cool. Here's a bit of advice, just in case you "fixed" it by making a common mistake: Don't just initialize a variable to a dummy value to make the compiler happy. Those "not initialized" errors usually point to a logic error. But just initializing the variable to 0, null, etc. at declaration, usually you're just masking the logic error so the compiler doesn't see it. You haven't fixed anything.
    public String signum (int x) {
      String result;
      if (x > 0) {
        result = "positive";
      else if (x < 0) {
        result = "negative";
      return result;
    }Here we have a compiler error, brought on by my logic error of forgetting to account for x being 0. The wrong way to fix it would be to blindly change the declaration of result to String result = ""; or == null;. The logic error is still there, but now it's hidden from the compiler. So we have an error at runtime instead--we don't get a valid response if we pass in 0. Runtime errors are much harder to debug than compile-time errors.
    The correct response to the compiler's "not initialized" error is to look at our code more carefully and see what we might have missed. In this case, we would add and else clause that returns "zero".

Maybe you are looking for

  • I have just set up my Apple TV, how do I set it to show my screen on my TV

    I have just set up my Apple TV, how do I set it to show my screen on my TV

  • Change icon for file type

    how to change icon for all of the tile type? not just one, but all!

  • I purchased a song, and it won't play. How do I fix it?

    How do I go about getting a song I payed for to actually play?????  I use the same computer or phone to make my purchases, and this has never happened, every other song I downloaded the same night dowloaded correctly, but this one I guess didn't. How

  • Syncing unsuccessful

    My playlists are showing up, however they are not in the same order as my itunes folders are. Even after multiple attempts to sync again, some lists come up in the same desired order however, most are not and my tracks are listed alphabetically by ar

  • Monthly script not showing???

    I used terminal to find out when scripts were running. This is what it shows. -rw-r--r-- 1 root wheel 4412 Aug 26 10:02 /var/log/daily.out -rw-r--r-- 1 root wheel 278 Aug 22 12:23 /var/log/weekly.out shouldn't there be a monthly one as well? thank yo