Handling JOptionPane.CANCEL_OPTION ?

hi
i'm making confirmation dialog with yes,no,cancel option
and i have a problem that when i press the cancel button the program automatically exits why?
i want to do other operation when pressing cancel,but it doesn't response to any thing?
    int option = JOptionPane.showConfirmDialog(null,"Save Chages?","Warning",JOptionPane.YES_NO_CANCEL_OPTION);
            if (option == JOptionPane.YES_OPTION) {
            Save();
        else if (option == JOptionPane.NO_OPTION) {
           System.exit(0);
       else if(option == JOptionPane.CANCEL_OPTION){
                //any thing here doesn't invoke even left empty the program exits
               frame.requestFocusInWindow();
                             }

First of all, please please please clean up the indentation problems with your posted code. This is painful and at times torture. Check out camickr's rec's in your recent thread.
Next, does the line: frame.requestFocusInWindow();get called if cancel is pressed? It should. Does your program exit after this? If so, maybe this has nothing to do with the option pane and everything to do with your code stream running out of the the river. The program just naturally ended. This is hard for us to know without seeing your code in context.
Here's my version of your code, formatted
import javax.swing.JOptionPane;
class Fubar
  public static void main(String[] args)
    int option = JOptionPane.showConfirmDialog(null, "Save Chages?", "Warning",
        JOptionPane.YES_NO_CANCEL_OPTION);
    if (option == JOptionPane.YES_OPTION)
      System.out.println("Save();");
    else if (option == JOptionPane.NO_OPTION)
      System.exit(0);
    else if (option == JOptionPane.CANCEL_OPTION)
      System.out.println("frame.requestFocusInWindow();");
}Edited by: Encephalopathic on Sep 15, 2008 8:16 PM

Similar Messages

  • Key-enable buttons on a JOptionPane

    Hi,
    The existing code in my Application uses a JOptionPane static method = JOptionPane.showOptionDialog() to create a dialog box.Is there any way I can key-enable the buttons on the dialog created by this method.
    public int createAndShowGUI() {
    if (!issuesPanel.hasIssues())
    return -2; //TODO make constant
    else {
    //Custom button text
    String[] options = should_continue ? new String[] {returnText, continueText} : new String[] {returnText};
    int optionButtons = should_continue ? JOptionPane.OK_CANCEL_OPTION : JOptionPane.CANCEL_OPTION ;
    log.info("IssuesOptionPane displayed - " + title);
    int optionChosen = JOptionPane.showOptionDialog(parent,
    issuesPanel.createAndGetIssuesPanel(),
    title,
    optionButtons,
    JOptionPane.PLAIN_MESSAGE,
    null, //don't use a custom icon
    options, //titles of buttons
    null); //no default selected button
    String buttontext = optionChosen == CLOSE ? "X" : options[optionChosen];
    log.info("User clicked on the " + buttontext + " button");
    return optionChosen;
    I see that there is no way to get a handle on the JButtons created by the JOptionPane.So, one work around that I tried is to create a JPanel, add JButtons , set Input Map, set Action Map ( to add key bindings ) on it.Then create a JDialog and pass this JPanel to the dialog using setContentPane
         private static void createAndShowGUI(){
              JButton bookingButton=new JButton(bookStr);
              JButton returnButton=new JButton(returnStr);
              bookingButton.addActionListener(new BookAction());
              returnButton.addActionListener(new ReturnAction());
              JPanel panel=new JPanel();
              panel.add(bookingButton);
              panel.add(returnButton);
              panel.setActionMap(initActionMap());
              initAndSetInputMap(panel);
              JDialog dialog=new JDialog();
              dialog.setSize(400,100);
              dialog.setModal(true);
              dialog.setContentPane(panel);
              dialog.addPropertyChangeListener(indicator,listener);
              System.out.println("step 1" );
              dialog.pack();
              System.out.println("step 2");
              dialog.setVisible(true);
    But the problem that I am facing here is that the property change events triggered by the code inside the actionPerformed methods is not getting capturesd by the listener attached to the JDialog.
    Any thoughts?
    Thanks
    Aman

    google: JOptionPane mnemonics
    http://www.devx.com/tips/Tip/13718
    http://forum.java.sun.com/thread.jspa?threadID=321824&messageID=1649963
    http://coding.derkeiler.com/Archive/Java/comp.lang.java.gui/2005-03/0495.html
    etc.

  • A custom version of JOptionPane.showInputDialog();

    I am trying to create a custom input dialog window so that I can have a right click event handler which lets me copy/cut/paste text using the mouse. However, after constructing the following code [as a standalone class, how I plan on using it], I lost the ability to finalize my selection with the 'Enter' key:
    class CustomInputDialog {
         public static javax.swing.JLabel lbl;
         public static javax.swing.JTextField txt;
         public static javax.swing.JPopupMenu pop;
         public static String showInputDialog(String message, String guess) {
              lbl = new javax.swing.JLabel(message);
              txt = new javax.swing.JTextField(guess, 10);
              pop = new javax.swing.JPopupMenu();
              javax.swing.Action copyAction = new javax.swing.AbstractAction(javax.swing.text.DefaultEditorKit.copyAction) {
                   public void actionPerformed(java.awt.event.ActionEvent e) {
                        txt.copy();
              javax.swing.Action cutAction = new javax.swing.AbstractAction(javax.swing.text.DefaultEditorKit.cutAction) {
                   public void actionPerformed(java.awt.event.ActionEvent e) {
                        txt.cut();
              javax.swing.Action pasteAction = new javax.swing.AbstractAction(javax.swing.text.DefaultEditorKit.pasteAction) {
                   public void actionPerformed(java.awt.event.ActionEvent e) {
                        txt.paste();
              javax.swing.JMenuItem m1 = new javax.swing.JMenuItem(copyAction);
              javax.swing.JMenuItem m2 = new javax.swing.JMenuItem(cutAction);
              javax.swing.JMenuItem m3 = new javax.swing.JMenuItem(pasteAction);
              m1.setText("Copy"); m2.setText("Cut"); m3.setText("Paste");
              pop.add(m1); pop.add(m2); pop.add(m3);
              txt.setComponentPopupMenu(pop);
              java.awt.Container ct = new java.awt.Container();
              ct.setLayout(new java.awt.GridLayout(2,1));
              ct.add(lbl); ct.add(txt); txt.selectAll();
              Object[] options = {"OK", "Cancel"};
              int responce = javax.swing.JOptionPane.showOptionDialog(null, ct, "TITLE.", javax.swing.JOptionPane.OK_CANCEL_OPTION, javax.swing.JOptionPane.QUESTION_MESSAGE, null, options, txt);
              if (responce == javax.swing.JOptionPane.OK_OPTION) {
                   return txt.getText();
              return null;
    }In an attempt to get the enter key working, I separated an instance of the JOptionPane class, so I could refer to it in a keyHandler event using the JTextField. In doing the following code adjustments, now not only does the enter key do nothing, but the method seems to always return null, even if the OK button is selected by the user via mouse:
    class CustomInputDialog {
         public static javax.swing.JLabel lbl;
         public static javax.swing.JTextField txt;
         public static javax.swing.JPopupMenu pop;
         public static javax.swing.JOptionPane op;
         public static String showInputDialog(String message, String guess) {
              lbl = new javax.swing.JLabel(message);
              txt = new javax.swing.JTextField(guess, 10);
              pop = new javax.swing.JPopupMenu();
              javax.swing.Action copyAction = new javax.swing.AbstractAction(javax.swing.text.DefaultEditorKit.copyAction) {
                   public void actionPerformed(java.awt.event.ActionEvent e) {
                        txt.copy();
              javax.swing.Action cutAction = new javax.swing.AbstractAction(javax.swing.text.DefaultEditorKit.cutAction) {
                   public void actionPerformed(java.awt.event.ActionEvent e) {
                        txt.cut();
              javax.swing.Action pasteAction = new javax.swing.AbstractAction(javax.swing.text.DefaultEditorKit.pasteAction) {
                   public void actionPerformed(java.awt.event.ActionEvent e) {
                        txt.paste();
              javax.swing.JMenuItem m1 = new javax.swing.JMenuItem(copyAction);
              javax.swing.JMenuItem m2 = new javax.swing.JMenuItem(cutAction);
              javax.swing.JMenuItem m3 = new javax.swing.JMenuItem(pasteAction);
              m1.setText("Copy"); m2.setText("Cut"); m3.setText("Paste");
              pop.add(m1); pop.add(m2); pop.add(m3);
              txt.setComponentPopupMenu(pop);
              txt.addKeyListener(new java.awt.event.KeyListener() {
                   @Override public void keyTyped(java.awt.event.KeyEvent e) {}
                   @Override public void keyReleased(java.awt.event.KeyEvent e) {}
                   @Override public void keyPressed(java.awt.event.KeyEvent e) {
                        if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {
                             op.setInitialValue(javax.swing.JOptionPane.OK_OPTION);
                             op.selectInitialValue();
              java.awt.Container ct = new java.awt.Container();
              ct.setLayout(new java.awt.GridLayout(2,1));
              ct.add(lbl); ct.add(txt); txt.selectAll();
              Object[] options = {"OK", "Cancel"};
              op = new javax.swing.JOptionPane(ct, javax.swing.JOptionPane.QUESTION_MESSAGE, javax.swing.JOptionPane.OK_CANCEL_OPTION, null, options, txt);
              op.createDialog(null, "TITLE.").setVisible(true);
              int returnValue = (op.getValue() instanceof Integer) ? ((Integer)op.getValue()).intValue() : javax.swing.JOptionPane.CANCEL_OPTION;
              if (returnValue == javax.swing.JOptionPane.OK_OPTION) {
                   return txt.getText();
              return null;
    }I've been going through the javax.swing references on the APIs, but I cannot find anything that seems to make sense to me as to a way to work towards the solution, if anyone could give me some help or guidance, it would be much appreciated. Thanks!
    Ps: I think the issue may be in "returnValue" getting set to JOptionPane.CANCEL_OPTION as it is being executed before the JOptionPane dialog is finally closed and a value is entered. However, on the examples I was looking at, it didn't seem like there was an onClosed event handler or something similar used.
    Pps [note]: I originally posted this in the Java Programming area, and was directed to come here. Original Post: [http://forums.sun.com/thread.jspa?threadID=5445202|http://forums.sun.com/thread.jspa?threadID=5445202].

    EDIT: I finally was able to get everything working the way I want it. Thanks for everyone's help. If anyone would like to use my code in the future, I'll attach it to this post. Note: For new lines, I had to use the <html> tag at the start of the msg and <br> tags for new lines instead of using the \r\n characters.
    class CustomInputDialog {
         public static javax.swing.JLabel lbl;
         public static javax.swing.JTextField txt;
         public static javax.swing.JPopupMenu pop;
         public static javax.swing.JButton ok_button, cancel_button;
         public static javax.swing.JDialog optionWindow;
         public static String returnValue = null;
         public static String showInputDialog(String title, String message, String guess) {
              CustomInputDialog.returnValue = null;
              Object[] options = {"OK", "Cancel"};
              lbl = new javax.swing.JLabel(message); txt = new javax.swing.JTextField(guess, 40);
              txt.addKeyListener(new java.awt.event.KeyListener() {
                   @Override public void keyTyped(java.awt.event.KeyEvent evt) {}
                   @Override public void keyReleased(java.awt.event.KeyEvent evt) {}
                   @Override public void keyPressed(java.awt.event.KeyEvent evt) {
                        if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {
                             ok_button.doClick();
                        else if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_ESCAPE) {
                             cancel_button.doClick();
              ok_button = new javax.swing.JButton((String)options[0]); cancel_button = new javax.swing.JButton((String)options[1]);
              ok_button.addActionListener(new java.awt.event.ActionListener() {
                   public void actionPerformed(java.awt.event.ActionEvent evt) {
                        CustomInputDialog.returnValue = txt.getText();
                        optionWindow.dispose();
              cancel_button.addActionListener(new java.awt.event.ActionListener() {
                   public void actionPerformed(java.awt.event.ActionEvent evt) {
                        optionWindow.dispose();
              pop = new javax.swing.JPopupMenu();
              javax.swing.JMenuItem m1 = new javax.swing.JMenuItem(new javax.swing.AbstractAction(javax.swing.text.DefaultEditorKit.copyAction) {
                   public void actionPerformed(java.awt.event.ActionEvent evt) {
                        txt.copy();
              }); m1.setText("Copy");
              javax.swing.JMenuItem m2 = new javax.swing.JMenuItem(new javax.swing.AbstractAction(javax.swing.text.DefaultEditorKit.cutAction) {
                   public void actionPerformed(java.awt.event.ActionEvent evt) {
                        txt.cut();
              }); m2.setText("Cut");
              javax.swing.JMenuItem m3 = new javax.swing.JMenuItem(new javax.swing.AbstractAction(javax.swing.text.DefaultEditorKit.pasteAction) {
                   public void actionPerformed(java.awt.event.ActionEvent evt) {
                        txt.paste();
              }); m3.setText("Paste");
              pop.add(m1); pop.add(m2); pop.add(m3);
              txt.setComponentPopupMenu(pop);
              java.awt.Container text_container = new java.awt.Container();
              text_container.setLayout(new java.awt.FlowLayout());
              text_container.add(txt);
              java.awt.Container button_container = new java.awt.Container();
              button_container.setLayout(new java.awt.FlowLayout());
              button_container.add(ok_button); button_container.add(cancel_button);
              java.awt.Container ct = new java.awt.Container();
              javax.swing.GroupLayout layout = new javax.swing.GroupLayout(ct);
              layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                   .addGroup(layout.createSequentialGroup().addContainerGap().addComponent(lbl).addContainerGap())
                   .addGroup(layout.createSequentialGroup().addContainerGap().addComponent(text_container).addContainerGap())
                   .addGroup(layout.createSequentialGroup().addContainerGap().addComponent(button_container).addContainerGap())
              layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                   .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(lbl)
                        .addContainerGap()
                        .addComponent(text_container)
                        .addContainerGap()
                        .addComponent(button_container)
                        .addContainerGap()
              ct.setLayout(layout);
              optionWindow = new javax.swing.JDialog((javax.swing.JFrame)null, title, true);
              optionWindow.setContentPane(ct); txt.selectAll();
              optionWindow.pack();
              optionWindow.setResizable(false);
              java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(), size = optionWindow.getSize();
              optionWindow.setLocation((screenSize.width-size.width)/2, (screenSize.height-size.height)/2);
              optionWindow.setVisible(true);
              return CustomInputDialog.returnValue;
    public class customDialogTestApp {
         public static void main(String[] args) {
              String ex = "<html><p>This is a really long group of text,<br>";
              ex += "The goal of this text group is to show that new lines seem to not be working<br>";
              ex += "properly with the customDialog class that I wrote up.<br>";
              ex += "However input right-clicking and [enter] key functionality in the text field now works fine<br>";
              ex += "as you can probably see in the textfield below this message.<br><br>";
              ex += "Thanks for your time and help in this manner!";
              String returnVal = CustomInputDialog.showInputDialog("Custom Dialog Test Application", ex, "NOTE: This time the label text is being passed with HTML formatting in a <p> tag, using '<br>' for linebreaks as opposed to '\r\n'.");
    }Thanks to everyone who had helped me!
    Edited by: xel614 on Jul 21, 2010 11:34 AM

  • Key mapping for JOptionPane

    My problem is pretty simple. When presented with a YES_NO_CANCEL option, I want the escape key to trigger the CANCEL operation.
    I've tried numerous methods including creating my own JOptionPane, adding/removing KeyListeners, etc., but I can't seem to get around this default behavior. Any suggestions?
    Michael

    By default, the Esc key closes the dialog with a return value of JOptionPane.CLOSED_OPTION. Why can't you simply perform the same action as when the return value is JOptionPanel.CANCEL_OPTION ?
    db
    edit Or even reassign the return value, if you prefer to do that (I wouldn't)int retVal = JOptionPane.showOptionDialog(...);
    if (retVal == JOptionPane.CLOSED_OPTION) {
       retVal = JOptionPane.CANCEL_OPTION;
    }Edited by: Darryl.Burke

  • Trying to write an if statement around the return value of a CANCEL_OPTION

    I am writing a program that takes an input String using JOptionPane. The String can be made of only letters of the A-Z alphabet and the space character. I have written an error-checking loop that will pop another input box up along with an error message if any invalid character is detected. The input box has an 'ok' button and a 'cancel' button. As it is, if you hit cancel, the program crashes and you get a NullPointerException. All I want to do is place an if statement inside of the error-checking loop, immediatly after the code to pop up the second input box, that simply does System.exit() and exits the program correctly(rather than crashing) if 'cancel' is clicked.
    My attempt at such an if statement is visible in the following code(letter is a boolean variable defined earlier, and message is the input String that has already been read in):
                   letter = isValidMessage(message);
              while(!letter)
                   message = JOptionPane.showInputDialog(null, "Message must contain only A-Z, a-z, or space character...");
                            if(JOptionPane.CANCEL_OPTION > 0  //or ==0 or ==1 or ==2, nothing works//)
                                JOptionPane.showMessageDialog(null, "No valid message entered - program will terminate...");
                                System.exit(JOptionPane.CANCEL_OPTION);
                   letter = isValidMessage(message);
                    }The if statement doesn't work correctly. If you click 'cancel' when the input box comes up, the program does terminate as it is supposed to. The problem is that if I type something in the box and click 'ok', it also causes the program to terminate rather than continuing. I've tried changing the > to ==. I've tried changing 0 to 1 to 2 to -1(I really am not sure which int return value of CANCEL_OPTION corresponds to which event). I think once I got to do the exact opposite...that is to say, it would continue on with the program whether I clicked 'cancel' or 'ok'. Which is equally bad. I don't know what I'm doing wrong.
    It's probably something simple that I'm just overlooking.

    Well, here's what CANCEL_OPTION is, according to the JOptionPane class:
    /** Return value from class method if CANCEL is chosen. */
        public static final int         CANCEL_OPTION = 2;However, I believe you're going about this in the wrong way.
    With JOptionPane, whenever you show a dialog, it usually returns whatever OPTION the user chose.
    For instance,
        int choice = JOptionPane.showConfirmDialog(parentComponent, "hello");That will bring up a dialog centered on parentComponent, with a message of "hello".
    It will have the default options (YES_NO_OPTION).
    What it returns is the option the user chose.
    There are 4 possible things it can return:
    YES_OPTION, when user clicks "Yes"
    NO_OPTION, when user clicks "No"
    ERROR_OPTION, when an unforseen error occurs and the dialog closes
    CANCEL_OPTION, when the user clicks "Cancel" (if that OPTION type were being used), or if they close the dialog
    So this is how you would check for CANCEL_OPTION:
        int choice = JOptionPane.showConfirmDialog(parentComponent, "hello");
        if (choice == JOptionPane.CANCEL_OPTION) {
            // User cancelled
        else if (choice == JOptionPane.YES_OPTION) {
            // User chose yes
        // EtcSo you see, going about it like this:
    if(JOptionPane.CANCEL_OPTION > 0  //or ==0 or ==1 or ==2, nothing works//)Is really the wrong way, because you're not checking what the user DID, but just what the constant variable "CANCEL_OPTION" is.
    However, it seems as if you're in a unique situation where you don't want the OPTION chosen by the user, but an input String.
    This is all well and good, but I think this limits how you can interact with the user, as the "showInputDialog" methods return the String the user input- not the OPTION they chose, and you need to use both.
    What I've done in the past is created a simple JPanel with its own JTextField.
    I pass the JPanel in as the "message" parameter of a showConfirmDialog call, and get both the user input and their chosen OPTION based off a getText call to the JTextField and the OPTION constant returned by showConfirmDialog.
    Basically,
    JPanel promptPanel = new JPanel(new BorderLayout());
    JTextField promptField = new JTextField();
    promptPanel.add(promptField, BorderLayout.CENTER);
    int choice = JOptionPane.showConfirmDialog(parentComponent, promptPanel, "Input", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
    if (choice == JOptionPane.OK_OPTION) {
       // User chose OK, see if invalid characters were entered
       String input = promptField.getText();
    else if (choice == JOptionPane.CANCEL_OPTION) {
       // User cancelled
    }Hope that helps.
    (note that I'm unsure if showConfirmDialog can accept OK_CANCEL_OPTION as its OPTION parameter, as it says only YES_NO_OPTION and YES_NO_CANCEL_OPTION can be used, but I seem to remember using it in the past. if OK_CANCEL_OPTION doesn't want to work, then use one of the other two and adjust your if statements accordingly)
    Cheers!
    Edited by: LukeFoss on Oct 9, 2007 10:39 PM

  • 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

  • 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!

  • 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

  • JOptionPane with Timeout

    Hello All,
    I am putting a new version of my application out tommorow where I have replaced all of the JOptionPane's with one's that timeout after a given time limit. I have tested it and it seems to work fine on my environment, does anyone see any problems with the code? The last thing I want is to find potential problems after I release it.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.beans.*;
    * @author Malcolm F
    public class TimeoutOptionPane {
        public static Object showTimeoutPane( final JOptionPane optionPane,
                final Frame frame, final String title, final int timeoutMillis ) {
            // Listen for property changes in the JOptionPane
            optionPane.addPropertyChangeListener( new PropertyChangeListener() {
                public void propertyChange( PropertyChangeEvent e ) {
                    if ( e.getPropertyName().equals( JOptionPane.VALUE_PROPERTY ) ) {
                        synchronized ( e.getSource() ) {
                            e.getSource().notify();
            // Create dialog based on JOptionPane and set visible
            final JDialog timeoutDialog = optionPane.createDialog( frame, title );
            SwingUtilities.invokeLater( new Runnable() {
                public void run() {
                    timeoutDialog.setVisible( true );
            // Wait for timeout, notified early if value property changes
            synchronized ( optionPane ) {
                try {
                    optionPane.wait( timeoutMillis );
                } catch ( Exception e ) {
                    e.printStackTrace();
            // Dispose of dialog
            SwingUtilities.invokeLater( new Runnable() {
                public void run() {
                    timeoutDialog.dispose();
            return optionPane.getValue();
    }

    Here is the code I use :
    import java.awt.BorderLayout;
    import java.awt.Frame;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.JDialog;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    import javax.swing.WindowConstants;
    * A message dialog that closes after a timeout.
    * @author clap
    public class TimedOptionPane {
         protected static int UPDATE_PERIOD = 1000;
          * Show a dialogBox.
          * @param f
          *            the owner
          * @param message
          *            the message to display
          * @param timeout
          *            in milliseconds
          * @param title
          *            title of the dialog box
          * @param timeoutMessage
          *            text showing remaining seconds
          * @return {@link JOptionPane#YES_OPTION}, when YEs is clicked, {@link JOptionPane#NO_OPTION}
          *         if NO is clicked, or {@link JOptionPane#CANCEL_OPTION} on timeout or window closed
          *         event.
         public final static int showTimedOptionPane(Frame f, String message, String title,
                   String timeoutMessage, final long timeout) {
              final JDialog dialog = new JDialog(f, title, true);
              final Message messageComponent = new Message(message, timeout, timeoutMessage);
              final JOptionPane pane = new JOptionPane(messageComponent, JOptionPane.QUESTION_MESSAGE,
                        JOptionPane.YES_NO_OPTION);
              dialog.setContentPane(pane);
              dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
              Timer timer = new Timer(UPDATE_PERIOD, new ActionListener() {
                   @Override
                   public void actionPerformed(ActionEvent e) {
                        messageComponent.addEllapsedMilliseconds(UPDATE_PERIOD);
                        if (messageComponent.isOver()) {
                             dialog.dispose();
              timer.start();
              pane.addPropertyChangeListener(new PropertyChangeListener() {
                   @Override
                   public void propertyChange(PropertyChangeEvent e) {
                        String prop = e.getPropertyName();
                        if (dialog.isVisible() && (e.getSource() == pane)
                                  && (JOptionPane.VALUE_PROPERTY.equals(prop))) {
                             dialog.setVisible(false);
              dialog.pack();
              dialog.setLocationRelativeTo(f);
              dialog.setVisible(true);
              String valueString = pane.getValue().toString();
              if (JOptionPane.UNINITIALIZED_VALUE.equals(valueString)) {
                   return JOptionPane.CANCEL_OPTION;
              return ((Integer) pane.getValue()).intValue();
          * Test...
          * @param args
         public static void main(String args[]) {
              int response = showTimedOptionPane(null, "Did you choose ?", "Please Choose",
                        "Remaining : ", 4000);
              System.out.println("Choosen :" + response);
              System.exit(0);
          * Content of the {@link JOptionPane}.
          * @author clap
         static class Message extends JPanel {
              private final static String RS = "Remaining seconds : ";
              JLabel message;
              JLabel remaining;
              private long timeout;
              private long ellapsed = 0;
               * Build content panel.
               * @param message
               *            the message to show
               * @param milliseconds
               *            timeout in milliseconds
               * @param timeoutMessage
               *            text showing remaining seconds
              protected Message(String message, long milliseconds, String timeoutMessage) {
                   super(new BorderLayout());
                   this.timeout = milliseconds;
                   this.message = new JLabel(message);
                   add(this.message, BorderLayout.NORTH);
                   this.remaining = new JLabel(formatRemainingSeconds(milliseconds));
                   add(this.remaining, BorderLayout.SOUTH);
              private String formatRemainingSeconds(long ms) {
                   return RS + (ms / 1000) + "s.";
               * @return true if the timeout has been reached.
              protected boolean isOver() {
                   return ellapsed >= timeout;
               * Indicates that some milliseconds has occured.
               * @param milliseconds
              protected void addEllapsedMilliseconds(long milliseconds) {
                   ellapsed += milliseconds;
                   remaining.setText(formatRemainingSeconds(timeout - ellapsed));
                   repaint();
    }

  • JOptionPane focus

    Hello Please look at this code below:
                   JPasswordField pwdField = new JPasswordField();
                   if(JOptionPane.showConfirmDialog(null,pwdField,"Enter Password",
                        JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
                        pass = new String(pwdField.getPassword());
                   else {
                          JOptionPane.showMessageDialog(null,"Password Required, shutting system");
                          System.exit(0);
                   char[] password = pass.toCharArray();Is there a way to make the textfield in the joptionpane to be focused other than using the parent? Because I am calling this class from many other classes and I want to avoid making more references to the JFrame class. I have tried to use pwdField .grabFocus() and all of the other focus stuff I could find in the API. But none worked. Seems to me only way is to use a Parent (where I have no null). Any ideas anyone?

    Hi ,
    Try this sample code,
    package com.dany;
    import java.beans.* ;
    import javax.swing.* ;
    * @author Little Dany
    public class OptionTest {
        public static void main ( String[] args ) {
            JTextField tf = new JTextField ( "Enter you text" );
            tf.requestFocus ();
            JOptionPane op = new JOptionPane ( tf ,
                    JOptionPane.INFORMATION_MESSAGE , JOptionPane.OK_CANCEL_OPTION ,
                    null , null , null );
            JDialog jd = new JDialog ();
            jd.setTitle( "Dialog Title" ) ;
            op.addPropertyChangeListener(JOptionPane.VALUE_PROPERTY, new MyChngLsnr(jd));
            jd.getContentPane ().add ( op , "Center" );
            jd.setDefaultCloseOperation ( JDialog.DISPOSE_ON_CLOSE );
            jd.setModal ( true );
            jd.pack ();
            jd.setVisible ( true );
            Object value = op.getValue() ;
            if( value instanceof Integer ) {
                int iv = ( ( Integer ) value ).intValue() ;
                if( iv == JOptionPane.OK_OPTION ) {
                    System.out.println ( "Ok Pressed." );
                } else if( iv == JOptionPane.CANCEL_OPTION ) {
                    System.out.println( "Operation cancel" ) ;
            } else {
                System.out.println ( "You do not use buttons" );
        public static class MyChngLsnr implements PropertyChangeListener {
            private JDialog jd;
            public MyChngLsnr ( JDialog jd ) {
                if ( jd == null ) {
                    throw new NullPointerException ( "dialog is null" );
                this.jd = jd;
            public void propertyChange ( PropertyChangeEvent evt ) {
                if ( jd.isVisible () ) {
                    jd.dispose ();
    }

  • ActionListener for JOptionPane.showConfirmDialog

    Is it possible to handle JOptionPane.showConfirmDailog 's button click events through action listeners?
    I want to execute some code on the "Save" button click and want to do it like my JFileChooser window stays in the background until either of the Yes,No or Cancel buttons of the showConfirmDialog is pressed.In fact I'm able to get the state of the button pressed using,
    int i=JOptionPane.showConfirmDialog(null,"Confirm file overwrite?")but can't make the showConfirmDialog window stay in the background,,,
    Can anybody please help?
    Thanks in advance...

    There are forums specifically for GUI questions.
    I believe there is also a forum for international issues.

  • [HELP! ] why my program thows a javax.swing.text.ChangedCharSetException?

    there's the source:
    import java.io.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    import javax.swing.border.*;
    class HTMLMagician extends JFrame
         protected static final String APP_NAME="HTML Magician V1.0 Produced By V Studio";
         protected JTextPane hm_textPane;
         protected StyleSheet hm_styleSheet;
         protected HTMLEditorKit html_kit;
         protected HTMLDocument html_document;
         protected JMenuBar hm_menuBar;
         protected JToolBar hm_toolBar;
         protected JFileChooser hm_fileChooser;
         protected File current_file;
         protected boolean text_changed=false;
         public HTMLMagician()
              super(APP_NAME);
              setSize(800,600);
              getContentPane().setLayout(new BorderLayout());
              produceMenuBar();
              hm_textPane=new JTextPane();
              html_kit=new HTMLEditorKit();
              hm_textPane.setEditorKit(html_kit);
              JScrollPane textPane_scrollPane=new JScrollPane();
              textPane_scrollPane.getViewport().add(hm_textPane);
              getContentPane().add(textPane_scrollPane,BorderLayout.CENTER);
              hm_fileChooser=new JFileChooser();
              javax.swing.filechooser.FileFilter hm_filter=new javax.swing.filechooser.FileFilter()
                   public boolean accept(File pathname)
                        if(pathname.isDirectory())
                             return true;
                        String ext_name=pathname.getName().toLowerCase();
                        if(ext_name.endsWith(".htm"))
                             return true;
                        if(ext_name.endsWith(".html"))
                             return true;
                        if(ext_name.endsWith(".asp"))
                             return true;
                        if(ext_name.endsWith(".jsp"))
                             return true;
                        if(ext_name.endsWith(".css"))
                             return true;
                        if(ext_name.endsWith(".php"))
                             return true;
                        if(ext_name.endsWith(".aspx"))
                             return true;
                        if(ext_name.endsWith(".xml"))
                             return true;
                        if(ext_name.endsWith(".txt"))
                             return true;
                        return false;
                   public String getDescription()
                        return "HTML files(*.htm,*.html,*.asp,*.jsp,*.css,*.php,*.aspx,*.xml)";
              hm_fileChooser.setAcceptAllFileFilterUsed(false);
              hm_fileChooser.setFileFilter(hm_filter);
              try
                   File dir=(new File(".")).getCanonicalFile();
                   hm_fileChooser.setCurrentDirectory(dir);
              }catch(IOException ex)
                   showError(ex,"Error openning current directory");
              newDocument();
              WindowListener action_winClose=new WindowAdapter()
                   public void windowClosing(WindowEvent evt)
                        if(!promptToSave())
                             return;
                        System.exit(0);
              addWindowListener(action_winClose);
              setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
              setVisible(true);
         protected void produceMenuBar()
              hm_menuBar=new JMenuBar();
              hm_toolBar=new JToolBar();
              JMenu menu_file=new JMenu("File");
              menu_file.setMnemonic('f');
              ImageIcon icon_new=new ImageIcon("imgs/file.gif");
              Action action_new=new AbstractAction("New",icon_new)
                   public void actionPerformed(ActionEvent evt)
                        if(!promptToSave())
                             return;
                        newDocument();
              JMenuItem item_new=new JMenuItem(action_new);
              item_new.setMnemonic('n');
              item_new.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,InputEvent.CTRL_MASK));
              menu_file.add(item_new);
              JButton button_new=hm_toolBar.add(action_new);
              ImageIcon icon_open=new ImageIcon("imgs/folder_open.gif");
              Action action_open=new AbstractAction("Open...",icon_open)
                   public void actionPerformed(ActionEvent evt)
                        if(!promptToSave())
                             return;
                        openDocument();
              JMenuItem item_open=new JMenuItem(action_open);
              item_open.setMnemonic('o');
              item_open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,InputEvent.CTRL_MASK));
              menu_file.add(item_open);
              JButton button_open=hm_toolBar.add(action_open);
              ImageIcon icon_save=new ImageIcon("imgs/floppy.gif");
              Action action_save=new AbstractAction("Save",icon_save)
                   public void actionPerformed(ActionEvent evt)
                        saveAs(false);
              JMenuItem item_save=new JMenuItem(action_save);
              item_save.setMnemonic('s');
              item_save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,InputEvent.CTRL_MASK));
              menu_file.add(item_save);
              JButton button_save=hm_toolBar.add(action_save);
              Action action_saveAs=new AbstractAction("Save As...")
                   public void actionPerformed(ActionEvent evt)
                        saveAs(true);
              JMenuItem item_saveAs=new JMenuItem(action_saveAs);
              item_saveAs.setMnemonic('a');
              item_saveAs.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,InputEvent.CTRL_MASK));
              menu_file.add(item_saveAs);
              menu_file.addSeparator();
              Action action_close=new AbstractAction("Quit")
                   public void actionPerformed(ActionEvent evt)
                        if(!promptToSave())
                             return;
                        System.exit(0);
              JMenuItem item_exit=new JMenuItem(action_close);
              item_exit.setMnemonic('q');
              item_exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,InputEvent.CTRL_MASK));
              menu_file.add(item_exit);
              hm_menuBar.add(menu_file);
              setJMenuBar(hm_menuBar);
              getContentPane().add(hm_toolBar,BorderLayout.NORTH);
         protected String getDocumentName()
              return current_file==null ? "Untitled" : current_file.getName();
         protected void newDocument()
              html_document=(HTMLDocument)html_kit.createDefaultDocument();
              hm_styleSheet=html_document.getStyleSheet();
              hm_textPane.setDocument(html_document);
              current_file=null;
              setTitle(getDocumentName()+" - "+APP_NAME);
              Runnable runner=new Runnable()
                   public void run()
                        text_changed=false;
                        html_document.addDocumentListener(new action_textChanged());
              SwingUtilities.invokeLater(runner);
         protected void openDocument()
              if(hm_fileChooser.showOpenDialog(HTMLMagician.this)!=JFileChooser.APPROVE_OPTION)
                   return;
              File f=hm_fileChooser.getSelectedFile();
              if(f==null || !f.isFile())
                   return;
              current_file=f;
              setTitle(getDocumentName()+" - "+APP_NAME);
              HTMLMagician.this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
              try
                   InputStream in=new FileInputStream(current_file);
                   html_document=(HTMLDocument)html_kit.createDefaultDocument();
                   html_kit.read(in,html_document,0);
                   hm_styleSheet=html_document.getStyleSheet();
                   hm_textPane.setDocument(html_document);
                   in.close();
              }catch(Exception ex)
                   showError(ex,"Error openning file "+current_file);
              HTMLMagician.this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
              Runnable runner=new Runnable()
                   public void run()
                        text_changed=false;
                        html_document.addDocumentListener(new action_textChanged());
              SwingUtilities.invokeLater(runner);
         protected boolean saveAs(boolean as)
              if(!as && !text_changed)
                   return true;
              if(as || current_file==null)
                   if(hm_fileChooser.showSaveDialog(HTMLMagician.this)!=JFileChooser.APPROVE_OPTION)
                        return false;
                   File f=hm_fileChooser.getSelectedFile();
                   if(f==null || !f.isFile())
                        return false;
                   current_file=f;
                   setTitle(getDocumentName()+" - "+APP_NAME);
              HTMLMagician.this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
              try
                   OutputStream out=new FileOutputStream(current_file);
                   html_kit.write(out,html_document,0,html_document.getLength());
                   out.close();
              }catch(Exception ex)
                   showError(ex,"Error saving file "+current_file);
              HTMLMagician.this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
              return true;
         protected boolean promptToSave()
              if(!text_changed)
                   return true;
              int result=JOptionPane.showConfirmDialog(this,"Save change to "+getDocumentName(),APP_NAME,JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE);
              switch(result)
                   case JOptionPane.YES_OPTION:
                        if(!saveAs(false))
                             return false;
                        return true;
                   case JOptionPane.NO_OPTION:
                        return true;
                   case JOptionPane.CANCEL_OPTION:
                        return false;
              return true;
         protected void showError(Exception ex,String message)
              ex.printStackTrace();
              JOptionPane.showMessageDialog(this,message,APP_NAME,JOptionPane.WARNING_MESSAGE);
         public static void main(String[] args)
              new HTMLMagician();
         class action_textChanged implements DocumentListener
              public void changedUpdate(DocumentEvent evt)
                   text_changed=true;
              public void insertUpdate(DocumentEvent evt)
                   text_changed=true;
              public void removeUpdate(DocumentEvent evt)
                   text_changed=true;
    when i open a .html file,the command output :
    javax.swing.text.ChangedCharSetException
         at javax.swing.text.html.parser.DocumentParser.handleEmptyTag(Unknown Source)
         at javax.swing.text.html.parser.Parser.startTag(Unknown Source)
         at javax.swing.text.html.parser.Parser.parseTag(Unknown Source)
         at javax.swing.text.html.parser.Parser.parseContent(Unknown Source)
         at javax.swing.text.html.parser.Parser.parse(Unknown Source)
         at javax.swing.text.html.parser.DocumentParser.parse(Unknown Source)
         at javax.swing.text.html.parser.ParserDelegator.parse(Unknown Source)
         at javax.swing.text.html.HTMLEditorKit.read(Unknown Source)
         at javax.swing.text.DefaultEditorKit.read(Unknown Source)
         at HTMLMagician.openDocument(HTMLMagician.java:222)
         at HTMLMagician$4.actionPerformed(HTMLMagician.java:128)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at javax.swing.JComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    why? what's wrong? thanks

    The DocumentParser seems to throw a ChangedCharSetException if it finds a "http-equiv" meta tag for "content-type" or "charset" and if the parser's "ignoreCharSet" property is set to false on creation.

  • Drawing in java

    hi, i have got some problems for drawing (using an application not an applet)
    wat JComponent should i used for the drawing area
    Below is my programs (several classes)
    errors as appeared on dos screen:
    at java.awt.Component.processMouseEvent(Component.java:4906)
    at java.awt.Component.processEvent(Component.java:4732)
    at java.awt.Container.processEvent(Container.java:1337)
    at java.awt.Component.dispatchEventImpl(Component.java:3476)
    at java.awt.Container.dispatchEventImpl(Container.java:1399)
    at java.awt.Component.dispatchEvent(Component.java:3343)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3302
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3014)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:2967)
    at java.awt.Container.dispatchEventImpl(Container.java:1373)
    at java.awt.Window.dispatchEventImpl(Window.java:1459)
    at java.awt.Component.dispatchEvent(Component.java:3343)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:439)
    at java.awt.EventDispatchThread.pumpOneEvent(EventDispatchThread.java:15
    0)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:131)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
    MousePressed x=84,y=41
    MouseReleased x=84,y=41
    //end of errors
    my programs is abt drawing uml diagrams and then generate the code..i got a program udgp�.from the internet
    I modified the interface, I used the udgp class, ( click on class diagram to get my main menu) and some other classes which I consider important for drawing a class diagram and I make also some of the code in the classes I used as comments �as I do not see them important for drawing�
    My problem: I got some problem, only the textdialog appears to add classname but no drawing of the class diagram occurs ..why??? the errors as shown in the diagram above appears when I click on ok of the textdialog.
    Plzzzz help me wiz my problems
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    //import javax.swing.event.*;
    import java.io.*;
    import java.util.*;
    import java.util.Vector;
    class MainMenu extends JDialog{
    static int WIDTH = 700;
    static int HEIGHT = 400;
    public static final String APP_NAME = "Code Generator for Java";
    private String fileName = "Untitled.pjt";
    protected boolean m_fileChanged = false;
    protected File m_currentFile;
    protected ProjectDoc doc;
    protected ClassView classView;
    protected JScrollPane drawingPane;
    protected ClassDiagram classDiagram;
    private TextField modeDisplay;
    // JTextArea pane;
    JLabel statusInfo;
    // JFrame frame=new JFrame();
    /*public MainMenu(String title){
         super(title);
    public MainMenu (Frame frame,String title,ProjectDoc doc) {
         super (frame,title,false);
         this.doc = doc;
         classView = new ClassView(doc,this);
    Container content = getContentPane();
    content.setLayout(new BorderLayout());
    JToolBar toolBar = new JToolBar();
    content.add (toolBar, BorderLayout.NORTH);
    //pane = new JTextArea ();
    //pane.setEditable(false);
    // pane.setViewportView(classView);
    classView.setPreferredSize (new Dimension(6000,3500));
    drawingPane = new JScrollPane (classView,
                   ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                   ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    drawingPane.setViewportView(classView);
    drawingPane.getViewport().setBackground(Color.white);
    content.add (drawingPane, BorderLayout.CENTER);
    statusInfo = new JLabel();
    content.add (statusInfo, BorderLayout.SOUTH);
    content.setVisible(true);
         // Make toolBar floatable
    toolBar.setFloatable (true);
    // Setup Menus
    JMenuBar menuBar = new JMenuBar();
    setJMenuBar (menuBar);
    //Build the File menu.in the menu bar
    JMenu fileMenu = new JMenu("File");
    fileMenu.setMnemonic(KeyEvent.VK_F);
    menuBar.add(fileMenu);
    //file new
    JMenuItem newMenuItem = new JMenuItem("New",
                                                 new ImageIcon("images/new.jpg"));
    newMenuItem.setMnemonic(KeyEvent.VK_N);
    newMenuItem.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_N, ActionEvent.CTRL_MASK));
    fileMenu.add(newMenuItem);
    newMenuItem.addActionListener (new ActionListener() {
              public void actionPerformed (ActionEvent e) {
              doNewCommand();
    //file open
    JMenuItem openMenuItem = new JMenuItem("Open",
                                                 new ImageIcon("images/open.jpg"));
              openMenuItem.setMnemonic(KeyEvent.VK_O);
    openMenuItem.setAccelerator(KeyStroke.getKeyStroke(
                        KeyEvent.VK_O, ActionEvent.CTRL_MASK));
    fileMenu.add(openMenuItem);
    openMenuItem.addActionListener (new ActionListener() {
              public void actionPerformed (ActionEvent e) {
              //file close
    JMenuItem closeMenuItem = new JMenuItem("Close");
                   closeMenuItem.setMnemonic(KeyEvent.VK_C);
    fileMenu.add(closeMenuItem);
    closeMenuItem.addActionListener (new ActionListener() {
              public void actionPerformed (ActionEvent e) {
              doCloseCommand (0);
    //menu items separator
    fileMenu.addSeparator();
         //file save
              JMenuItem saveMenuItem = new JMenuItem("Save"
                                                           ,new ImageIcon("images/save.jpg"));
                   saveMenuItem.setMnemonic(KeyEvent.VK_S);
                        saveMenuItem.setAccelerator(KeyStroke.getKeyStroke(
                                  KeyEvent.VK_S, ActionEvent.CTRL_MASK));
    fileMenu.add(saveMenuItem);
    saveMenuItem.addActionListener (new ActionListener() {
              public void actionPerformed (ActionEvent e) {
              saveFile(fileName);
    //file save as
              JMenuItem saveAsMenuItem = new JMenuItem("Save As...");
              saveAsMenuItem.setMnemonic(KeyEvent.VK_A);
              saveAsMenuItem.addActionListener (new ActionListener() {
                        public void actionPerformed (ActionEvent e) {
                        saveAs();
    fileMenu.add(saveAsMenuItem);
    //menu items separator
    fileMenu.addSeparator();
    //file print
              JMenuItem printMenuItem = new JMenuItem("Print...",
                                                           new ImageIcon("images/print.jpg"));
                        printMenuItem.setMnemonic(KeyEvent.VK_P);
                        printMenuItem.setAccelerator(KeyStroke.getKeyStroke(
                                            KeyEvent.VK_P, ActionEvent.CTRL_MASK));
    fileMenu.add(printMenuItem);
              //menu items separator
    fileMenu.addSeparator();
    //file exit
              JMenuItem exitMenuItem = new JMenuItem("Exit");
                        exitMenuItem.setMnemonic(KeyEvent.VK_X);
              fileMenu.add(exitMenuItem);
              exitMenuItem.addActionListener (new ActionListener() {
                        public void actionPerformed (ActionEvent e) {
                                  if (!promptToSave())
                                  return;
                                  System.exit(0);
    //Build Edit menu in the menu bar.
    JMenu editMenu = new JMenu("Edit");
         editMenu.setMnemonic(KeyEvent.VK_E);
    menuBar.add(editMenu);
    //edit cut
              JMenuItem cutMenuItem = new JMenuItem("Cut",
                                                      new ImageIcon("images/cut.jpg"));
                        cutMenuItem.setMnemonic(KeyEvent.VK_T);
                        cutMenuItem.setAccelerator(KeyStroke.getKeyStroke(
                        KeyEvent.VK_X, ActionEvent.CTRL_MASK));
         editMenu.add(cutMenuItem);
    //edit copy
              JMenuItem copyMenuItem = new JMenuItem("Copy",
                                                      new ImageIcon("images/copy.jpg"));
                        copyMenuItem.setMnemonic(KeyEvent.VK_C);
                        copyMenuItem.setAccelerator(KeyStroke.getKeyStroke(
                                  KeyEvent.VK_C, ActionEvent.CTRL_MASK));
              editMenu.add(copyMenuItem);
    //edit paste
              JMenuItem pasteMenuItem = new JMenuItem("Paste",
                                                           new ImageIcon("images/paste.jpg"));
                        pasteMenuItem.setMnemonic(KeyEvent.VK_P);
                        pasteMenuItem.setAccelerator(KeyStroke.getKeyStroke(
                        KeyEvent.VK_V, ActionEvent.CTRL_MASK));
              editMenu.add(pasteMenuItem);
    //menu items separator
    editMenu.addSeparator();
    //edit delete
              JMenuItem deleteMenuItem = new JMenuItem("Delete",
                                                      new ImageIcon("images/delete.jpg"));
                        deleteMenuItem.setMnemonic(KeyEvent.VK_D);
                        deleteMenuItem.setAccelerator(KeyStroke.getKeyStroke(
                        KeyEvent.VK_DELETE, ActionEvent.CTRL_MASK));
    editMenu.add(deleteMenuItem);
              //Build Tool menu in the menu bar.
              JMenu toolMenu = new JMenu("Tool");
                   toolMenu.setMnemonic(KeyEvent.VK_T);
    menuBar.add(toolMenu);
    //tool generate code
              JMenuItem genCodMenuItem = new JMenuItem("Generate Code...");
                        genCodMenuItem.setMnemonic(KeyEvent.VK_C);
                        genCodMenuItem.setAccelerator(KeyStroke.getKeyStroke(
                             KeyEvent.VK_G, ActionEvent.CTRL_MASK));
    toolMenu.add(genCodMenuItem);
    genCodMenuItem.addActionListener (new ActionListener() {
         public void actionPerformed (ActionEvent e) {
              /*CodeGenerationWindow CodeGenWin = new CodeGenerationWindow("");
    CodeGenWin.setVisible(true);*/
              //Build Help menu in the menu bar
              JMenu helpMenu = new JMenu("Help");
              helpMenu.setMnemonic(KeyEvent.VK_H);
    menuBar.add(helpMenu);
    //help content
              JMenuItem ctntMenuItem = new JMenuItem("Contents",
                                                 new ImageIcon("images/help.jpg"));
                   ctntMenuItem.setMnemonic(KeyEvent.VK_C);
              helpMenu.add(ctntMenuItem);
              ctntMenuItem.addActionListener (new ActionListener() {
         public void actionPerformed (ActionEvent e) {
              /*SystemHelp help = new SystemHelp("");
    help.setVisible(true);*/
              //menu items separator
              helpMenu.addSeparator();
              //help about code generator for java
              final JFrame frame1 = new JFrame();
              JMenuItem abtMenuItem = new JMenuItem("About Code Generator for Java");
                        abtMenuItem.setMnemonic(KeyEvent.VK_A);
              helpMenu.add(abtMenuItem);
              abtMenuItem.addActionListener (new ActionListener() {
         public void actionPerformed (ActionEvent e) {
              JOptionPane.showMessageDialog(frame1,
         "Code Generator for Java v1.0.\nBy Prayag Kamal\n"+
         " Mahmaud Nazeemah Begum",
         "Information", JOptionPane.INFORMATION_MESSAGE,
                                                 new ImageIcon("images/abt.jpg"));
    // Setup Toolbar/Tool Tips
    // Create a button New, tool tip "New File"
    // Have it call doNewCommand when selected
    //new button
                   JButton newButton=new JButton(new ImageIcon("images/new.jpg"));
                   newButton.setToolTipText("New Document");
                   toolBar.add(newButton);
         newButton.addActionListener (new ActionListener() {
         public void actionPerformed (ActionEvent e) {
    doNewCommand();
    // Create a button Open, tool tip "Open File"
    // Have it call doOpenCommand when selected
    //open button
                   JButton openButton=new JButton(new ImageIcon("images/open.jpg"));
                   openButton.setToolTipText("Open Document");
                   toolBar.add(openButton);
         openButton.addActionListener (new ActionListener() {
         public void actionPerformed (ActionEvent e) {
    // Create a button Save, tool tip "Save File"
    // Have it call doSaveCommand when selected
              JButton saveButton=new JButton(new ImageIcon("images/save.jpg"));
                   saveButton.setToolTipText("Save Document");
                   toolBar.add(saveButton);
         saveButton.addActionListener (new ActionListener() {
         public void actionPerformed (ActionEvent e) {
    saveFile(fileName);
    // Create a separator
    toolBar.addSeparator();
         //cut button
                   JButton cutButton=new JButton(new ImageIcon("images/cut.jpg"));
                   cutButton.setToolTipText("Cut");
                   toolBar.add(cutButton);
         //copy button
                   JButton copyButton=new JButton(new ImageIcon("images/copy.jpg"));
                   copyButton.setToolTipText("Copy");
                   toolBar.add(copyButton);
         //paste button
                   JButton pasteButton=new JButton(new ImageIcon("images/paste.jpg"));
                   pasteButton.setToolTipText("Paste");
                   toolBar.add(pasteButton);
         // Create a separator
         toolBar.addSeparator();
    //print button
                   JButton printButton=new JButton(new ImageIcon("images/print.jpg"));
                   printButton.setToolTipText("Print Document");
                   toolBar.add(printButton);
         //create a separator
         toolBar.addSeparator();
         // Create a button help, tool tip "Help"
              JButton helpButton=new JButton(new ImageIcon("images/help.jpg"));
                   helpButton.setToolTipText("Help");
                   toolBar.add(helpButton);
              helpButton.addActionListener (new ActionListener() {
         public void actionPerformed (ActionEvent e) {
         /*SystemHelp help = new SystemHelp("");
    help.setVisible(true);*/
    /////////////////////////creating the toolbox///////////////////////////////
    JPanel control = new JPanel();
    JToolBar controlBar = new JToolBar();
    controlBar.setLayout(new GridLayout(0,2));
    JButton classButton=new JButton(new ImageIcon("images/Class.gif"));
    classButton.setToolTipText("Class");
    classButton.addActionListener (new ButtonListener());
    controlBar.add(classButton);
    JButton intfButton=new JButton(new ImageIcon("images/Interface.gif"));
    intfButton.setToolTipText("Interface");
    intfButton.addActionListener (new ActionListener() {
              public void actionPerformed (ActionEvent e) {
    controlBar.add(intfButton);
    JButton packButton=new JButton(new ImageIcon("images/Package.gif"));
    packButton.setToolTipText("Package");
    packButton.addActionListener (new ActionListener() {
              public void actionPerformed (ActionEvent e) {
    controlBar.add(packButton);
    JButton objButton=new JButton(new ImageIcon("images/Object.gif"));
    objButton.setToolTipText("Object");
    objButton.addActionListener (new ActionListener() {
              public void actionPerformed (ActionEvent e) {
    controlBar.add(objButton);
    JButton adNameButton=new JButton(new ImageIcon("images/AddName.jpg"));
    adNameButton.setToolTipText("Add Class Name ");
    adNameButton.addActionListener (new ActionListener() {
              public void actionPerformed (ActionEvent e) {
    controlBar.add(adNameButton);
    JButton adAttrButton=new JButton(new ImageIcon("images/AddAttribute.gif"));
    adAttrButton.setToolTipText("Add Attribute");
    adAttrButton.addActionListener (new ActionListener() {
              public void actionPerformed (ActionEvent e) {
    controlBar.add(adAttrButton);
    JButton adOpButton=new JButton(new ImageIcon("images/AddOperation.gif"));
    adOpButton.setToolTipText("Add Method");
    adOpButton.addActionListener (new ActionListener() {
              public void actionPerformed (ActionEvent e) {
    controlBar.add(adOpButton);
    JButton asscButton=new JButton(new ImageIcon("images/Association.gif"));
    asscButton.setToolTipText("Association");
    asscButton.addActionListener (new ActionListener() {
              public void actionPerformed (ActionEvent e) {
    controlBar.add(asscButton);
    JButton depdcyButton=new JButton(new ImageIcon("images/Dependency.gif"));
    depdcyButton.setToolTipText("Dependency");
    depdcyButton.addActionListener (new ActionListener() {
              public void actionPerformed (ActionEvent e) {
    controlBar.add(depdcyButton);
    JButton genButton=new JButton(new ImageIcon("images/Generalization.gif"));
    genButton.setToolTipText("Generalization");
    genButton.addActionListener (new ActionListener() {
              public void actionPerformed (ActionEvent e) {
    controlBar.add(genButton);
    JButton realButton=new JButton(new ImageIcon("images/Realization.gif"));
    realButton.setToolTipText("Realization");
    realButton.addActionListener (new ActionListener() {
              public void actionPerformed (ActionEvent e) {
    controlBar.add(realButton);
    JButton noteButton=new JButton(new ImageIcon("images/Note.gif"));
    noteButton.setToolTipText("Note");
    noteButton.addActionListener (new ActionListener() {
              public void actionPerformed (ActionEvent e) {
    controlBar.add(noteButton);
    JButton adMsgButton=new JButton(new ImageIcon("images/AddMessage.gif"));
    adMsgButton.setToolTipText("Add Message");
    adMsgButton.addActionListener (new ActionListener() {
              public void actionPerformed (ActionEvent e) {
    controlBar.add(adMsgButton);
    control.add(controlBar);
    content.add(control, BorderLayout.WEST);
    WindowListener wndCloser = new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        if (!promptToSave())
                             return;
                        System.exit(0);
              addWindowListener(wndCloser);
              setSize(WIDTH, HEIGHT);
    }//end constructor
    public JViewport getViewport()
              JViewport jv = drawingPane.getViewport();
              return jv;
    public String getDocumentName() {
              return m_currentFile==null ? "Untitled" :
                   m_currentFile.getName();
    public void saveAs()
              JFileChooser chooser = new JFileChooser("*");
              PjtFilter pjt = new PjtFilter();
              chooser.setFileFilter(pjt);
              JButton saveAsButton = new JButton();
              int returnVal = chooser.showSaveDialog(saveAsButton);
              if (returnVal == JFileChooser.APPROVE_OPTION)
                   fileName = chooser.getCurrentDirectory() + "\\" +
                        chooser.getSelectedFile().getName();
                   int i = fileName.lastIndexOf('.');
                   if (i > 0 && i < fileName.length()-1)
                        if (fileName.substring(i).compareToIgnoreCase(".pjt") != 0)
                             fileName += ".pjt";
                   else if (i == fileName.length()-1)
                        fileName += "pjt";
                   else
                        fileName += ".pjt";
                   System.out.println("You chose to save data as: " + fileName);
                   saveFile(fileName);
              m_fileChanged = false;
    protected boolean promptToSave() {
              if (!m_fileChanged)
                   return true;
              int result = JOptionPane.showConfirmDialog(this,
                   "Save changes to "+getDocumentName()+"?",
                   APP_NAME, JOptionPane.YES_NO_CANCEL_OPTION,
                   JOptionPane.INFORMATION_MESSAGE);
              switch (result) {
              case JOptionPane.YES_OPTION:
                   saveAs();
              case JOptionPane.NO_OPTION:
                   return true;
              case JOptionPane.CANCEL_OPTION:
                   return false;
              return true;
    /* public static void main (String args[]) {
         //Make sure we have nice window decorations.
         MainMenu.setDefaultLookAndFeelDecorated(true);
         //Create and set up the window.
              MainMenu frame = new MainMenu(this,"t",doc);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(WIDTH, HEIGHT);
    frame.setVisible(true);
    void doNewCommand () {
    //pane.setText ("");
    void doCloseCommand (int status) {
    System.exit (status);
         public void saveFile(String fname)
              try
                   BufferedWriter out = new BufferedWriter(new FileWriter(fname));
                   out.close();
                             catch (IOException e)
                                  System.out.println("Exception in saveFile");
    class ButtonListener implements ActionListener {
    public void actionPerformed(ActionEvent e){
         classView.setControlMode(doc.ADD_CLASS);
         modeDisplay.setText("Add class");
    ////udgp
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Vector;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.plaf.metal.*;
    import javax.swing.filechooser.FileFilter;
    public class udgp
         static udgp appMain;
         AppFrame mainWindow;
         public static void main(String[] args)
              appMain = new udgp();
              appMain.init();
         public void init()
              mainWindow = new AppFrame("UML Diagram Generation Program");
              //mainWindow.pack();
              mainWindow.setSize(250, 300);
              mainWindow.addWindowListener(new WindowHandler());
              mainWindow.show();
         // Handler class for window events
         class WindowHandler extends WindowAdapter
              public void windowClosing(WindowEvent e)
                   if (e.getID() == WindowEvent.WINDOW_CLOSING)
                        mainWindow.dispose();
                        System.exit(0);
    class AppFrame extends JFrame implements ActionListener
         JTree projTree;
         JPanel treePanel = new JPanel();
         private JButton newFileButton =
              new JButton(new ImageIcon("images/new.gif"));
         private JButton openFileButton =
              new JButton(new ImageIcon("images/open.gif"));
         private JButton saveFileButton =
              new JButton(new ImageIcon("images/save.gif"));
         private JButton saveAsButton =
              new JButton(new ImageIcon("images/saveas.gif"));
         private JMenuBar menuBar;
         private JToolBar toolBar;
         //private ClassDiagramBox classBox;
         private MainMenu mMenu;
         private Vector seqBoxList;     // created in buildTreeDisplay
         private DefaultTreeModel treeModel;
         private DefaultMutableTreeNode top;
         private DefaultMutableTreeNode cd;
         private DefaultMutableTreeNode sd;
         //private DefaultMutableTreeNode f;
         private DefaultMutableTreeNode d;
         private String fileName = "noname.pjt";
         protected ProjectDoc doc;
         //public Parser parser = new Parser();
         public AppFrame(String t)
              super(t);
              JMenuItem menuItem;
              getContentPane().setLayout(new BorderLayout());
              menuBar = new JMenuBar();
              setJMenuBar(menuBar);
              //Build the menu
              JMenu menu = new JMenu("File");
              menu.setMnemonic(KeyEvent.VK_F);
              menuBar.add(menu);
              menuItem = new JMenuItem("New", KeyEvent.VK_N);
              menuItem.setAccelerator(KeyStroke.getKeyStroke(
                   KeyEvent.VK_1, ActionEvent.ALT_MASK));
              menuItem.addActionListener(this);
              menu.add(menuItem);
              menuItem = new JMenuItem("Open", KeyEvent.VK_O);
              menuItem.setAccelerator(KeyStroke.getKeyStroke(
                   KeyEvent.VK_2, ActionEvent.ALT_MASK));
              menuItem.addActionListener(this);
              menu.add(menuItem);
              menuItem = new JMenuItem("Save", KeyEvent.VK_S);
              menuItem.setAccelerator(KeyStroke.getKeyStroke(
                   KeyEvent.VK_3, ActionEvent.ALT_MASK));
              menuItem.addActionListener(this);
              menu.add(menuItem);
              menuItem = new JMenuItem("Save As", KeyEvent.VK_A);
              menuItem.setAccelerator(KeyStroke.getKeyStroke(
                   KeyEvent.VK_4, ActionEvent.ALT_MASK));
              menuItem.addActionListener(this);
              menu.add(menuItem);
              menu.addSeparator();
              menuItem = new JMenuItem("Exit", KeyEvent.VK_X);
              menuItem.setAccelerator(KeyStroke.getKeyStroke(
                   KeyEvent.VK_0, ActionEvent.ALT_MASK));
              menuItem.addActionListener(this);
              menu.add(menuItem);
              menu = new JMenu("Help");
              menu.setMnemonic(KeyEvent.VK_H);
              menuBar.add(menu);
              menuItem = new JMenuItem("About", KeyEvent.VK_T);
              menuItem.setAccelerator(KeyStroke.getKeyStroke(
                   KeyEvent.VK_1, ActionEvent.ALT_MASK));
              menuItem.addActionListener(this);
              menu.add(menuItem);
              toolBar = new JToolBar();
              toolBar.add(newFileButton);
              newFileButton.setToolTipText("New");
              toolBar.add(openFileButton);
              openFileButton.setToolTipText("Open");
              toolBar.add(saveFileButton);
              saveFileButton.setToolTipText("Save");
              toolBar.add(saveAsButton);
              saveAsButton.setToolTipText("Save As");
              getContentPane().add("North", toolBar);
              treePanel.setLayout(new BorderLayout());
              buildTreeDisplay(); // tree display and new ProjectDoc
              getContentPane().add("Center", treePanel);
              newFileButton.addActionListener(new ButtonListener());
              openFileButton.addActionListener(new ButtonListener());
              saveFileButton.addActionListener(new ButtonListener());
              saveAsButton.addActionListener(new ButtonListener());
    public void actionPerformed(ActionEvent e)
              JMenuItem source = (JMenuItem)(e.getSource());
              String s = source.getText();
              if (s.equals("New"))
                   newFile();
              /*else if (s.equals("Open"))
                   loadFile();
              /*else if (s.equals("Save"))
                   saveFile(fileName);
              else if (s.equals("Save As"))
                   saveAs();
              else if (s.equals("About"))
                   JOptionPane.showMessageDialog(
                        null, "UDGP 1.0",
                        "INFO", JOptionPane.INFORMATION_MESSAGE);
              else if (s.equals("Exit"))
                   System.exit(0);
         public void buildTreeDisplay()
              // make sure we are clean =)
              if (doc != null)
                   doc = null;
                   if (mMenu != null)
                        mMenu.dispose();
                   /*if (seqBoxList != null)
                        for (int i=0; i < seqBoxList.size(); i++)
                             ((SeqDiagramBox)seqBoxList.elementAt(i)).dispose();*/
              seqBoxList = new Vector();
              if (projTree != null)
                   treePanel.remove(projTree);
                   projTree = null;
              treeModel = null;
              top = new DefaultMutableTreeNode("Project");
              treeModel = new DefaultTreeModel(top);
              projTree = new JTree(treeModel);
              cd = new DefaultMutableTreeNode("Class Diagram");
              sd = new DefaultMutableTreeNode("Sequence Diagrams");
              d = new DefaultMutableTreeNode("_New Diagram_");
              sd.add(d);
              top.add(cd);
              top.add(sd);
              doc = new ProjectDoc(this);
              projTree.setRootVisible(true);
              projTree.expandRow(0);
              projTree.expandRow(2);
              MouseListener ml = new MouseAdapter()
                   public void mouseClicked(MouseEvent e)
                        int selRow = projTree.getRowForLocation(e.getX(), e.getY());
                        TreePath selPath = projTree.getPathForLocation(e.getX(), e.getY());
                        if (selRow != -1)
                             System.out.println("selRow = "+ selRow);
                             System.out.println("Path = " + selPath.toString());
                             if (selRow == 1)
                                  //classDiagramBox();
                                  mainMenu();
                             /*else if (selRow == 3)
                                  newSequenceDiagramBox(null);
                             else if (selRow > 3)
                                  showSequenceDiagramBox(selRow - 4);*/
              projTree.addMouseListener(ml);
              treePanel.add(projTree);
              treePanel.setVisible(true);
              // without this line, i would have problem showing the tree panel
              // should be a better way to fix this....
              // will look into this again =)
              treePanel.updateUI();
         public void mainMenu()
              { if (mMenu==null)
         mMenu = new MainMenu(this, "Code Generator for Java",doc);
                        mMenu.show();
                        mMenu.repaint();
         /*public void classDiagramBox()
              if (classBox == null)
                   classBox = new ClassDiagramBox(this, "Class Diagram", doc);
              classBox.show();
              classBox.repaint();
         /*public void loadFile()
              String line = new String();
              boolean EOF = false;
              int mode = 0;
              umlClass c;
              Relation r;
              SeqCall seqc;
              Integer idx;
              JFileChooser chooser = new JFileChooser("*");
              PjtFilter pjt = new PjtFilter();
              chooser.setFileFilter(pjt);
              int returnVal = chooser.showOpenDialog(openFileButton);
              if (returnVal == JFileChooser.APPROVE_OPTION)
                   String f = chooser.getSelectedFile().getName();
                   System.out.println("You chose to open this file: "+f);
                   try
                        File myFile = new File(f);
                        BufferedReader myIn =
                             new BufferedReader(new FileReader(myFile));
                        fileName = f;
                        buildTreeDisplay();
                        if (classBox != null)
                             classBox.dispose();
                             classBox = null;
                        classDiagramBox();
                        while(!EOF)
                             try
                                  line = myIn.readLine();
                                  if (line==null)
                                       EOF = true; continue;
                                  System.out.println(line);
                                  if (line.equals("[CD]"))
                                       mode = 1;
                                  else if (line.equals("[CD_REL]"))
                                       mode = 2;
                                  else if (line.equals("[SD]"))
                                       mode = 3;
                                  else if (line.equals("[SD_CALLS]"))
                                       mode = 4;
                                  else
                                       System.out.println("Data line....");
                                       if (mode==1)
                                            System.out.println("CDLine");
                                            c = parser.parseCDLine(line, doc.classDiagram);
                                            if (c != null)
                                                 doc.classDiagram.addClass(c);
                                       else if (mode==2)
                                            System.out.println("CDRelLine");
                                            r = parser.parseCDRel(line, doc.classDiagram);
                                            if (r != null)
                                                 doc.classDiagram.addRelation(r);
                                       else if (mode==3)
                                            System.out.println("SD");
                                            newSequenceDiagramBox(line);
                                       else if (mode==4)
                                            System.out.println("SD Calls");
                                            // this parsing routine behaves a little
                                            // diff from the others....
                                            // it's parse and add
                                            parser.parseSDCallLine(
                                                 line, doc.classDiagram, doc.sequenceDiagrams);
                             catch(EOFException e)
                                  EOF = true;
                   catch(FileNotFoundException e)
                        System.err.println(e);
                        return;
                   catch(IOException e)
                        System.out.println("Error reading input file: " + e);
                        return;
         public void newFile()
              System.out.println("newFile()");
              buildTreeDisplay();
              if (mMenu != null)
                   mMenu.dispose();
                   mMenu = null;
         /*public void newSequenceDiagramBox(String nameStr)
              if (nameStr == null)
                   TextDialog textDlg =
                        new TextDialog(this, "Sequence Diagram Description");
                   textDlg.setVisible(true);
                   nameStr = textDlg.getString();
                   textDlg.dispose();
              if (nameStr != null)
                   SequenceDiagram seqD =
                        new SequenceDiagram(nameStr);
                   doc.addSeqDiagram(seqD);
                   SeqDiagramBox s = new SeqDiagramBox(this, nameStr, doc);
                   DefaultMutableTreeNode f =
                        new DefaultMutableTreeNode(nameStr);
                   System.out.println("seqBoxList size (before)= "+seqBoxList.size());
                   seqBoxList.add(s);
                   System.out.println("seqBoxList size (after)= "+seqBoxList.size());
                   System.out.println("sd.getChildCount() (1)= "+sd.getChildCount());
                   treeModel.insertNodeInto(f, sd, sd.getChildCount());
                   System.out.println("sd.getChildCount() (2)= "+sd.getChildCount());
                   // too many windows are being opened at the same time
                   // let's comment this in order to show only the main window
                   // and the class diagram (if available)
                   //showSequenceDiagramBox(seqBoxList.size()-1);
         public void saveAs()
              JFileChooser chooser = new JFileChooser("*");
              PjtFilter pjt = new PjtFilter();
              chooser.setFileFilter(pjt);
              int returnVal = chooser.showSaveDialog(saveAsButton);
              if (returnVal == JFileChooser.APPROVE_OPTION)
                   fileName = chooser.getCurrentDirectory() + "\\" +
                        chooser.getSelectedFile().getName();
                   int i = fileName.lastIndexOf('.');
                   if (i > 0 && i < fileName.length()-1)
                        if (fileName.substring(i).compareToIgnoreCase(".pjt") != 0)
                             fileName += ".pjt";
              

    Do you actually expect somebody to read all that unformatted code. When you have a problem post a SMALL working example of formatted code. Click on the 'Formatting Link' for more information.
    Use a JPanel. Here is a simple example:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=416916

  • JTextPane Problem on MacOs 10.2+

    Hi everyone,
    I have a problem using JtextPane on MacOsX with JVM 1.4x installed.
    All worked good on MacOs X with ONLY jvm 1.3.x installed. If also jvm 1.4.x is installed then the problem I'm reporting appears, whether runs on 1.3.x or 1.4.x (using the JVMVersion key on related Info.plist files to switch between versions).
    I have more than one JTextPane on a JPanel. Each JTextPane has its own MouseListener with a mousePressed handler. This handler simply displays a JOptionPane with another JTextPane. Clicking on OK or on CANCEL the JOptionPane disappears.
    Running the program, when I click on a JTextPane, the JOptionPane correctly appears. Clicking on OK/Cancel it correctly disappears. The problem begins now: clicking on any point in the program window (therefore not only in the JTextPane) the JOptionPane appears, and no other action is possible (you can only close the program by clicking on X-button).
    Is this behaviour a known bug?
    I don't know where to start for fixing this bug!!!!
    Please, help me!!!
    Thanks in advance for any suggestion!!!
    Edoardo
    PS: This is the piece of code relatives to the problem:
    public class DidaBoxArea extends JTextPane {
      public DidaBoxArea () {
        super ();
        this.addMouseListener(new java.awt.event.MouseAdapter() {
          public void mousePressed(MouseEvent e) {
            onMouseClicked();
        this.addInputMethodListener(new java.awt.event.InputMethodListener() {
          public void caretPositionChanged(InputMethodEvent e) {
            onMouseClicked();
          public void inputMethodTextChanged(InputMethodEvent e) {
        this.setDropTarget(null);
        this.setOpaque(false);
        this.setEditable(false);
      void onMouseClicked() { // void onMouseClicked(MouseEvent e)
        // formatting code...
        popupTextPane = new JTextPane();
        popupScrollPane = new JScrollPane();
        popupScrollPane.getViewport().add(popupTextPane, null);
        JPanel contentPane = new JPanel();
        contentPane.add(popupScrollPane, new XYConstraints(0, 0, (int) size.getWidth() + 2, (int) size.getHeight() + 2));
        final JOptionPane optionPane = new JOptionPane(
            contentPane,
            JOptionPane.PLAIN_MESSAGE,
            JOptionPane.OK_CANCEL_OPTION);
        final JDialog dialog = new JDialog(autoImpaginaClass.frame,
                                           "Title",
                                           true);
        dialog.setModal(true);
        dialog.getContentPane().add(optionPane);
        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)))
              //If you were going to check something
              //before closing the window, you'd do
              //it here.
              dialog.setVisible(false);
        dialog.pack();
        dialog.setVisible(true);
        try {
          int value = ((Integer)optionPane.getValue()).intValue();
          if (value == JOptionPane.OK_OPTION) {
             // OK Actions....
          } else if (value == JOptionPane.CANCEL_OPTION) {
             // cancel actions
        } catch (Exception exc) {}
        popupTextPane.removeKeyListener(keyAdapter);
        keyAdapter = null;
      }----------------------------------------------------------------------------------

    Hi all,
    It works now!
    The only thing is that I reinstalled jdk.
    In fact, I had jdk on my machine and I removed it a time ago before installing Oracle. I reinstalled it without any modification to environment variables and isqlplus works.
    But I am surprised because AFAIK, Oracle installs its own jdk. so what could it be?
    Message was edited by:
    Michel

  • Repainting the frame

    Hi all,
    I have put the source code (modified from http://java.sun.com/docs/books/tutorial/uiswing/learn/example6.html) of a simple swing application. I ve added a sleep method under my comment /* My modification */
    Please run this program selecting "Canditate1" (radio button) and click the "Vote" button. You will get a gray background (in my theme) until this sleep method finishes its execution. Is there any way of avoiding this gray background so that even when the sleep method is executing, my window should be repainted, without forming a gray background. Even i tried by calling repaint() method, but still it is not working. Can anybody help me on this issue??????????
    * VoteDialog.java is a 1.4 example that requires
    * no other files.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class VoteDialog extends JPanel {
    JLabel label;
    JFrame frame;
    String simpleDialogDesc = "The candidates";
    public VoteDialog(JFrame frame) {
    super(new BorderLayout());
    this.frame = frame;
    JLabel title;
    //Create the components.
    JPanel choicePanel = createSimpleDialogBox();
    System.out.println("passed createSimpleDialogBox");
    title = new JLabel("Click the \"Vote\" button"
    + " once you have selected a candidate.",
    JLabel.CENTER);
    label = new JLabel("Vote now!", JLabel.CENTER);
    label.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
    choicePanel.setBorder(BorderFactory.createEmptyBorder(20,20,5,20));
    //Lay out the main panel.
    add(title, BorderLayout.NORTH);
    add(label, BorderLayout.SOUTH);
    add(choicePanel, BorderLayout.CENTER);
    void setLabel(String newText) {
    label.setText(newText);
    private JPanel createSimpleDialogBox() {
    final int numButtons = 4;
    JRadioButton[] radioButtons = new JRadioButton[numButtons];
    final ButtonGroup group = new ButtonGroup();
    JButton voteButton = null;
    final String defaultMessageCommand = "default";
    final String yesNoCommand = "yesno";
    final String yeahNahCommand = "yeahnah";
    final String yncCommand = "ync";
    radioButtons[0] = new JRadioButton(
    "<html>Candidate 1: <font color=red>Sparky the Dog</font></html>");
    radioButtons[0].setActionCommand(defaultMessageCommand);
    radioButtons[1] = new JRadioButton(
    "<html>Candidate 2: <font color=green>Shady Sadie</font></html>");
    radioButtons[1].setActionCommand(yesNoCommand);
    radioButtons[2] = new JRadioButton(
    "<html>Candidate 3: <font color=blue>R.I.P. McDaniels</font></html>");
    radioButtons[2].setActionCommand(yeahNahCommand);
    radioButtons[3] = new JRadioButton(
    "<html>Candidate 4: <font color=maroon>Duke the Java<font size=-2><sup>TM</sup></font size> Platform Mascot</font></html>");
    radioButtons[3].setActionCommand(yncCommand);
    for (int i = 0; i < numButtons; i++) {
    group.add(radioButtons);
    //Select the first button by default.
    radioButtons[0].setSelected(true);
    voteButton = new JButton("Vote");
    voteButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    String command = group.getSelection().getActionCommand();
    //ok dialog
    if (command == defaultMessageCommand) {
    JOptionPane.showMessageDialog(frame,
    "This candidate is a dog. Invalid vote.");
                             /* My modification */
                             try
                                  //System.out.println("Going inside");
         //repaint();                         java.lang.Thread.sleep(5000);
                             catch(InterruptedException ie)
                                  System.out.println("Exp --------------<<<<<<<<<<<");
    //yes/no dialog
    } else if (command == yesNoCommand) {
    int n = JOptionPane.showConfirmDialog(frame,
    "This candidate is a convicted felon. \nDo you still want to vote for her?",
    "A Follow-up Question",
    JOptionPane.YES_NO_OPTION);
    if (n == JOptionPane.YES_OPTION) {
    setLabel("OK. Keep an eye on your wallet.");
    } else if (n == JOptionPane.NO_OPTION) {
    setLabel("Whew! Good choice.");
    } else {
    setLabel("It is your civic duty to cast your vote.");
    //yes/no (with customized wording)
    } else if (command == yeahNahCommand) {
    Object[] options = {"Yes, please", "No, thanks"};
    int n = JOptionPane.showOptionDialog(frame,
    "This candidate is deceased. \nDo you still want to vote for him?",
    "A Follow-up Question",
    JOptionPane.YES_NO_OPTION,
    JOptionPane.QUESTION_MESSAGE,
    null,
    options,
    options[0]);
    if (n == JOptionPane.YES_OPTION) {
    setLabel("I hope you don't expect much from your candidate.");
    } else if (n == JOptionPane.NO_OPTION) {
    setLabel("Whew! Good choice.");
    } else {
    setLabel("It is your civic duty to cast your vote.");
    //yes/no/cancel (with customized wording)
    } else if (command == yncCommand) {
    Object[] options = {"Yes!",
    "No, I'll pass",
    "Well, if I must"};
    int n = JOptionPane.showOptionDialog(frame,
    "Duke is a cartoon mascot. \nDo you "
    + "still want to cast your vote?",
    "A Follow-up Question",
    JOptionPane.YES_NO_CANCEL_OPTION,
    JOptionPane.QUESTION_MESSAGE,
    null,
    options,
    options[2]);
    if (n == JOptionPane.YES_OPTION) {
    setLabel("Excellent choice.");
    } else if (n == JOptionPane.NO_OPTION) {
    setLabel("Whatever you say. It's your vote.");
    } else if (n == JOptionPane.CANCEL_OPTION) {
    setLabel("Well, I'm certainly not going to make you vote.");
    } else {
    setLabel("It is your civic duty to cast your vote.");
    return;
    System.out.println("calling createPane");
    return createPane(simpleDialogDesc + ":",
    radioButtons,
    voteButton);
    private JPanel createPane(String description,
    JRadioButton[] radioButtons,
    JButton showButton) {
    int numChoices = radioButtons.length;
    JPanel box = new JPanel();
    JLabel label = new JLabel(description);
    box.setLayout(new BoxLayout(box, BoxLayout.PAGE_AXIS));
    box.add(label);
    for (int i = 0; i < numChoices; i++) {
    box.add(radioButtons[i]);
    JPanel pane = new JPanel(new BorderLayout());
    pane.add(box, BorderLayout.NORTH);
    pane.add(showButton, BorderLayout.SOUTH);
    System.out.println("returning pane");
    return pane;
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    JDialog.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("VoteDialog");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Set up the content pane.
    Container contentPane = frame.getContentPane();
    contentPane.setLayout(new GridLayout(1,1));
    contentPane.add(new VoteDialog(frame));
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();

    Yours is the King of the FAQ for the Java GUI programming, i.e. the most recurring one.
    Java GUI runs as a single thread. If you are doing a time-consuming non-GUI task on a GUI thread,
    typically in an event handler code, GUI is blocked until your long task completes.
    Solution is that you do your long task as a separate thread. If you need to update GUI from within
    the thread, you should use SwingUtilities.invokeLater() or invokeAndWait() method(*) to do it. Read
    the API documentation for the methods and other documentations linked from there.
    (*)Or, java.awt.EventQueue.invokeLater() or invokeAndWait() method.

Maybe you are looking for

  • How to send messages in iChat in plain text? (no html)

    How to send messages in iChat in plain text? I don't need any formatting nor hiding links in achor tags.

  • Viewing iphone pictures on Win 7

    I backed up pictures from an iphone 4 and 4S to a CD, because I ran out of phone space.  I tried to view those photos on my Windows 7 desktop, but it says it can't open them.  How do I see what I backed up? Thank you

  • Error on iTunes library file after installing and uninstalling 8.1

    I downloaded 8.1 after being prompted. After installing 8.1, I could not synch my IPod. I uninstalled 8.1, reinstalled 8.02, and now I am getting this error. Does anyone have any ideas on how to correct this? I have about 39 Gigs of music, and will h

  • Automatic acknowledgement of sent email ?

    We have an imac OS10.6.8 ( I know, an old OS) and apple mail 4.6 A microsoft user friend said that she could get her email to send an acknowledgement back when the email was received at the other end. Can apple mail do the same, get a 'received' mess

  • DYNPRO_NOT_FOUND runtime error in O4F2

    Hi,   I am getting DYNPRO_NOT_FOUND runtime error while call screen statement is executed in t-code O4F2 in production. I checked the screen that is being called. The screen is active and there are no differences in the screen in dev and prod systems