JOptionpane Problem

Hey all
I have a query on the following code i hope some one can help with. In the following code when it executes a frame is displayed with three buttons, when you click the first button it brings up an JOptionpane which is all working fine its just the System.exit(0) i cant seem to get it to work. I dont know where to put in in realtion the switch
Thanks for all help
Ambrose
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
public class Switching extends JFrame implements ActionListener
     private JTextArea ta1;
     private JButton b1;
     private JButton b2;
     private JButton b3;
     private JLabel l1;
     //private JTextField t1;
     double number1;
     double number2;
     int productId = 1;
     double product1 = 0, product2 = 0, product3 = 0, product4 = 0, product5 = 0;
     public Switching(String str)
          super(str);
         //Container need to hold all the components
         Container c = getContentPane();
         c.setLayout(null);
          //Size and location
          setSize(507,550);
          setLocationRelativeTo(null);
          //Declared
          b1 = new JButton ("Start the Application");
          b2 = new JButton ("Print");
          b3 = new JButton ("Exit Application");
          ta1 = new JTextArea (5, 5);
          //t1 = new JTextField (5);
        //Scroll Pane needed for the text area
            JScrollPane scrollPane =  new JScrollPane(ta1,
        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
        JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        //Label added
        l1 = new JLabel(
        "Mail order House", SwingConstants.CENTER );
        //l7.setForeground( colorValues[ 0 ] );
           l1.setFont(
        new Font( "Comic Sans MS", Font.BOLD, 40 ) );
        //Components added to the container
        c.add (b1);
        c.add (b2);
        c.add (b3);
        c.add (scrollPane);
        c.add (l1);
        //c.add (t1);
        //Tool tips for accessibility options
        b1.setToolTipText ("Click to Calculate Start the Program");
          ta1.setText("Please use the Button Calculate to Interest Rates");
        //Locations of all the variables
        b1.setBounds (165, 390, 185, 25);
        b2.setBounds (165, 440, 185, 25);
        b3.setBounds (165, 490, 185, 25);
        //t1.setBounds (10, 120, 100, 25);
        scrollPane.setBounds (10, 170, 300, 100);
        l1.setBounds (36, 45, 465, 40);
        //Action Listener added to the buttons
        b1.addActionListener(this);
        b2.addActionListener(this);
        b3.addActionListener(this);
     public void actionPerformed( ActionEvent e )
                 //Target Source Needed
                 Object Target = e.getSource();
       if ( Target ==b1)
                 while (productId != 0)
                      String inputString = JOptionPane.showInputDialog
                      ("Enter product number ( 1-5 ) ( 0 to stop ):" );    
                      //String inputString = JOptionPane.showInputDialog( "Enter first integer:" );
                      productId = Integer.parseInt( inputString );
                      /*System.exit( 0 );*/ 
                 if ( productId >= 1 && productId <= 5 )    
                    String inputString1 = JOptionPane.showInputDialog( "Enter quantity sold:" );
                  int quantity = Integer.parseInt( inputString1 );        
                  switch ( productId )
                          case 1: product1 += quantity * 2.98; 
                            break;     
                         case 2: product2 += quantity * 4.50;   
                           break;      
                         case 3: product3 += quantity * 9.98;          
                               break;          
                        case 4: product4 += quantity * 4.49;            
                          break;        
                        case 5: product5 += quantity * 6.87;    
                          break;      
              else if ( productId != 0 )
                       String output = "Incorrect Number Entered\n Please Enter Again ! ";
                    JOptionPane.showMessageDialog(null, output, "Attempt One ",
                    JOptionPane.WARNING_MESSAGE);
                 if ( Target == b2)
                      System.out.println("ee");     
                      ta1.setText("");
                      ta1.setText("Product One:"+"    "+product1 +
                      "\nProduct Two:"+"    "+product2 +
                      "\nProduct Three: "+"  "+product3 +
                      "\nProduct Four:"+"    "+product4 +
                      "\nProduct Five:"+"    "+product5);
     public static void main ( String args [])
          //Create an new Instance of the Form
          Switching In = new Switching("Shop Form");
          //In.setDefaultLookAndFeelDecorated(true);
          In.show();
}

Add something like
if (target == b3) {
    System.exit(0);
}To your ActionListener. Make sure it's outside of the other if statements. Also, you can use JFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) to have the application exit when a user closes your window using the normal OS method (the X in windows).

Similar Messages

  • JOptionPane Problem, pls reply

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

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

  • JOptionPane. problems

    i am trying to do a program. i need to accept two numbers using two seperate dialog box and then add these numbers and present the result using an another dialog box . i am a new user to java. can somebody please help me out. PLease

    Hmmph - shudder and yuk!You're right, just showing the components to use and asking the OP to implement his own method for their use is not good.
    Here's a (perhaps) better version for the OP.
    import javax.swing.JOptionPane;
    class Testing
      public Testing()
        String sNum1, sNum2;
        int iNum1, iNum2, numsAdded = 0;
        boolean numbersValid = false;
        while(!numbersValid)
          try
            sNum1 = JOptionPane.showInputDialog("enter a number");
            iNum1 = Integer.parseInt(sNum1);
            sNum2 = JOptionPane.showInputDialog("enter another number");       
            iNum2 = Integer.parseInt(sNum2);
            numsAdded = iNum1 + iNum2;
            numbersValid = true;
          catch(Exception e){JOptionPane.showMessageDialog(null,"error in numbers, try again");}
        JOptionPane.showMessageDialog(null, "numbers added = " + numsAdded);
        System.exit(0);
      public static void main(String[] args) {new Testing();}
    }

  • JDialog & JOptionPane Problems

    I want to display a message(propably JOptionPane) which doesn't have the default answers such as "YES", "NO" or "CANCEL". Bu i want to add my options. I try with JDialog but the owner is a JInternalFrame and not a JFrame as it must be.
    What i must do?
    Any help is appreciated?

    Object[] options = {"java", "C++", "C#"};
    int option =JOptionPane.showOptionDialog(null,"Which language do you like best?","PROGRAM CHOICE",
    JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null,options,options[0]);
    if(option==0) System.out.println("Youchose java");
    else if(option==1) System.out.println("Youchose C++");
    else System.out.println("Youchose C#");

  • JOptionPane Problem Plz help me

    I want to add an image button on JOptionPane
    how can i do?
    Means change the default button For JOptionPane.OK_OPTION
    Thanks in advance

    set your FORMS60_PATH on the client to Formspath;libpath;menupath so it looks in every dir named in the path.

  • JOptionPane Problem: Pl Help

    I am trying to change the default selected option of showConfirmDialog to cancel instead of ok. Please suggest how i can do it.

    Hi,
    You can't change that with showConfirmDialog.
    Use showOptionDialog instead.
    One of the overloaded function takes the available options (say ok, cancel) and u can specify the default selection as well.
    Regards,
    [email protected]

  • Problem in Displaying JOptionpane Message Dialog (JRE 1.5.0_04 or later)

    Hi! All,
    I am getting a deadlock kind a situation while displaying JOptionpane message dialog. It's very rare to simulate also. I am also posting the Thread dump which i have taken programmatically, when this situation arises.
    For your Information, I am using JRE 1.5.0_04 or later version on Windows XP.
    We searched on Java.sun.com site, & we got that two bugs are related to our problem, but there are arises in JRE 1.4.2 or before version & have been fixed at JRE 1.5 .
    Follwing are the bugs ID in Sun Bugs Database: 4978089, 4828019.
    Can anyone suggest me which is the stable JRE 1.5 version to avoid this problem. Also can anyone suggest me the workaround of this problem. I want to fix this in our application ASAP.
    following is My Thread Dump :
    Thread[Finalizer,8,system]
         java.lang.Object.wait(Native Method)
         java.lang.ref.ReferenceQueue.remove(Unknown Source)
         java.lang.ref.ReferenceQueue.remove(Unknown Source)
         java.lang.ref.Finalizer$FinalizerThread.run(Unknown Source)
    Thread[Java2D Disposer,10,javawsApplicationThreadGroup]
         java.lang.Object.wait(Native Method)
         java.lang.ref.ReferenceQueue.remove(Unknown Source)
         java.lang.ref.ReferenceQueue.remove(Unknown Source)
         sun.java2d.Disposer.run(Unknown Source)
         java.lang.Thread.run(Unknown Source)
    Thread[JCIL_Sess(813251)_EvtThd(24880015),5,main]
         java.lang.Object.wait(Native Method)
         java.lang.Object.wait(Unknown Source)
         java.awt.EventQueue.invokeAndWait(Unknown Source)
         javax.swing.SwingUtilities.invokeAndWait(Unknown Source)
         in.co.netsol.telecom.desktop.CallAppearanceTable$EventAdapter.OnCallEstablished(CallAppearanceTable.java:982)
         in.co.netsol.telecom.ctios.events.EventSinkAdapter.OnEvent(EventSinkAdapter.java:142)
         com.cisco.cti.ctios.cil.EventPublisher.PostEvent(EventPublisher.java:175)
         com.cisco.cti.ctios.cil.EventPublisher.FireEvent(EventPublisher.java:142)
         com.cisco.cti.ctios.cil.CtiOsSession.FireEvent(CtiOsSession.java:1849)
         com.cisco.cti.ctios.cil.Call.FireEvent(Call.java:254)
         com.cisco.cti.ctios.cil.Call.OnCallEstablishedEvent(Call.java:1136)
         com.cisco.cti.ctios.cil.Call.OnEvent(Call.java:943)
         com.cisco.cti.ctios.cil.CtiOsSession.OnEvent(CtiOsSession.java:2107)
         com.cisco.cti.ctios.cil.CilServiceEvent.ReceiverThread(CilServiceEvent.java:256)
         com.cisco.cti.ctios.cil.CilServiceEvent$1.run(CilServiceEvent.java:173)
    Thread[pool-1-thread-5,5,main]
         java.lang.Object.wait(Native Method)
         java.lang.Object.wait(Unknown Source)
         java.awt.EventQueue.invokeAndWait(Unknown Source)
         javax.swing.SwingUtilities.invokeAndWait(Unknown Source)
         in.co.netsol.telecom.desktop.command.MakeAgentReadyCommand$EventAdapter$1.run(MakeAgentReadyCommand.java:190)
         java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
         java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
         java.lang.Thread.run(Unknown Source)
    Thread[DestroyJavaVM,5,main]
    Thread[AWT-Shutdown,5,javawsApplicationThreadGroup]
         java.lang.Object.wait(Native Method)
         java.lang.Object.wait(Unknown Source)
         sun.awt.AWTAutoShutdown.run(Unknown Source)
         java.lang.Thread.run(Unknown Source)
    Thread[JCIL_Conn(18096534)_Watchdog,5,main]
         java.lang.Object.wait(Native Method)
         com.cisco.cti.ctios.util.UnNamedEvent.WaitForSingleObject(UnNamedEvent.java:147)
         com.cisco.cti.ctios.cil.CilConnection.WatchdogThread(CilConnection.java:527)
         com.cisco.cti.ctios.cil.CilConnection$1.run(CilConnection.java:1071)
    Thread[AWT-EventQueue-0,6,main]
         java.awt.Container.getComponents_NoClientCode(Unknown Source)
         java.awt.Container.getComponents(Unknown Source)
         javax.swing.JToolBar.getComponentAtIndex(Unknown Source)
         javax.swing.plaf.basic.BasicToolBarUI.navigateFocusedComp(Unknown Source)
         javax.swing.plaf.basic.BasicToolBarUI$Actions.actionPerformed(Unknown Source)
         javax.swing.SwingUtilities.notifyAction(Unknown Source)
         javax.swing.JComponent.processKeyBinding(Unknown Source)
         javax.swing.JComponent.processKeyBindings(Unknown Source)
         javax.swing.SwingUtilities.processKeyBindings(Unknown Source)
         javax.swing.UIManager$2.postProcessKeyEvent(Unknown Source)
         java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
         java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
         java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
         java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
         java.awt.Component.dispatchEventImpl(Unknown Source)
         java.awt.Container.dispatchEventImpl(Unknown Source)
         java.awt.Window.dispatchEventImpl(Unknown Source)
         java.awt.Component.dispatchEvent(Unknown Source)
         java.awt.EventQueue.dispatchEvent(Unknown Source)
         java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         java.awt.EventDispatchThread.run(Unknown Source)
    Thread[AWT-Windows,6,main]
         sun.awt.windows.WToolkit.eventLoop(Native Method)
         sun.awt.windows.WToolkit.run(Unknown Source)
         java.lang.Thread.run(Unknown Source)
    Thread[Timer-0,5,javawsApplicationThreadGroup]
         java.lang.Thread.dumpThreads(Native Method)
         java.lang.Thread.getAllStackTraces(Unknown Source)
         in.co.netsol.telecom.log.ThreadDumpLoggingTask.getStackTraces(ThreadDumpLoggingTask.java:47)
         in.co.netsol.telecom.log.ThreadDumpLoggingTask.run(ThreadDumpLoggingTask.java:36)
         java.util.TimerThread.mainLoop(Unknown Source)
         java.util.TimerThread.run(Unknown Source)
    Thread[JCIL_Conn(18096534)_Rcvr,5,main]
         java.net.SocketInputStream.socketRead0(Native Method)
         java.net.SocketInputStream.read(Unknown Source)
         com.cisco.cti.ctios.cil.NetPort.ReceiveData(NetPort.java:405)
         com.cisco.cti.ctios.cil.NetPort.ReceiveData(NetPort.java:363)
         com.cisco.cti.ctios.cil.CilPacket.ReadFromPort(CilPacket.java:649)
         com.cisco.cti.ctios.cil.CilConnection.ReadPacket(CilConnection.java:670)
         com.cisco.cti.ctios.cil.Connection.ReceiverThread(Connection.java:398)
         com.cisco.cti.ctios.cil.Connection$1.run(Connection.java:472)
    Thread[pool-1-thread-2,5,main]
         java.lang.Object.wait(Native Method)
         java.lang.Object.wait(Unknown Source)
         java.awt.EventQueue.invokeAndWait(Unknown Source)
         javax.swing.SwingUtilities.invokeAndWait(Unknown Source)
         in.co.netsol.telecom.desktop.command.SupervisorAssistCommand$EventAdapter$1.run(SupervisorAssistCommand.java:152)
         java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
         java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
         java.lang.Thread.run(Unknown Source)
    Thread[pool-1-thread-1,5,main]
         java.lang.Object.wait(Native Method)
         java.lang.Object.wait(Unknown Source)
         java.awt.EventQueue.invokeAndWait(Unknown Source)
         javax.swing.SwingUtilities.invokeAndWait(Unknown Source)
         in.co.netsol.telecom.desktop.command.ConferenceCallCommand$EventAdapter$1.run(ConferenceCallCommand.java:144)
         java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
         java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
         java.lang.Thread.run(Unknown Source)
    Thread[JCIL_Svc(5450181)_TxQThd(3083604),5,main]
         java.lang.Object.wait(Native Method)
         java.lang.Object.wait(Unknown Source)
         com.cisco.cti.ctios.util.QueueThread.GetQItem(QueueThread.java:152)
         com.cisco.cti.ctios.util.QueueThread.run(QueueThread.java:259)
    Thread[pool-2-thread-1,5,main]
         java.lang.Object.wait(Native Method)
         java.lang.Object.wait(Unknown Source)
         java.awt.Dialog.show(Unknown Source)
         javax.swing.JOptionPane.showOptionDialog(Unknown Source)
         javax.swing.JOptionPane.showMessageDialog(Unknown Source)
         javax.swing.JOptionPane.showMessageDialog(Unknown Source)
         in.co.netsol.telecom.desktop.DesktopMainPanel$3.run(DesktopMainPanel.java:1871)
         java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
         java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
         java.lang.Thread.run(Unknown Source)
    Thread[Signal Dispatcher,9,system]
    Thread[Reference Handler,10,system]
         java.lang.Object.wait(Native Method)
         java.lang.Object.wait(Unknown Source)
         java.lang.ref.Reference$ReferenceHandler.run(Unknown Source)
    Thread[TimerQueue,5,javawsApplicationThreadGroup]
         java.lang.Object.wait(Native Method)
         javax.swing.TimerQueue.run(Unknown Source)
         java.lang.Thread.run(Unknown Source)
    Thread[pool-1-thread-4,5,main]
         java.lang.Object.wait(Native Method)
         java.lang.Object.wait(Unknown Source)
         java.awt.EventQueue.invokeAndWait(Unknown Source)
         javax.swing.SwingUtilities.invokeAndWait(Unknown Source)
         in.co.netsol.telecom.desktop.command.MakeAgentNotReadyCommand$EventAdapter$1.run(MakeAgentNotReadyCommand.java:146)
         java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
         java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
         java.lang.Thread.run(Unknown Source)
    Thread[pool-1-thread-6,5,main]
         java.lang.Object.wait(Native Method)
         java.lang.Object.wait(Unknown Source)
         java.awt.EventQueue.invokeAndWait(Unknown Source)
         javax.swing.SwingUtilities.invokeAndWait(Unknown Source)
         in.co.netsol.telecom.desktop.command.TransferCallCommand$EventAdapter$1.run(TransferCallCommand.java:136)
         java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
         java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
         java.lang.Thread.run(Unknown Source)
    Thread[traceMsgQueueThread,5,main]
         java.lang.Object.wait(Native Method)
         java.lang.Object.wait(Unknown Source)
         com.sun.deploy.util.Trace$TraceMsgQueueChecker.run(Unknown Source)
         java.lang.Thread.run(Unknown Source)
    Thread[pool-1-thread-3,5,main]
         java.lang.Object.wait(Native Method)
         java.lang.Object.wait(Unknown Source)
         java.awt.EventQueue.invokeAndWait(Unknown Source)
         javax.swing.SwingUtilities.invokeAndWait(Unknown Source)
         in.co.netsol.telecom.desktop.command.EmergencyCommand$EventAdapter$1.run(EmergencyCommand.java:146)
         java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
         java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
         java.lang.Thread.run(Unknown Source)
    Thanks & Regards,
    Pradeep Gupta

    Update to the latest version 1.5.0_06 available from:
    http://java.sun.com/j2se/1.5.0/download.jsp
    It is advisable to remove previous version(s) installations unless required otherwise for a specfic application.

  • Problem with Enter key and JOptionPane in 1.4

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

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

  • Customized KeyboardFocusManager problems with JOptionPane-Dialogs

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

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

  • JOptionPane blocking problem

    I have the following code in my 1.4.1 applet:
    int response = JOptionPane.showConfirmDialog(NewJabber.mainFrame,"Receive message from unregistered user: "+jid.getName()+" over the "+JID.SHOWNAMES[jid.getHostType()]+" transport. Accept and add user to roster?","Message Received",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE);
    if(response == JOptionPane.YES_OPTION){
    The dialog seems to work like a charm, but after it's been open for about 3 seconds, it somehow enters an infinite loop because IE starts to use 100% of my processor. I don't want users to have their computer DRASTICALLY slow until they respond to the dialog.(which does work and stops the processor usage)
    this only seems to be a problem with showConfirmDialog(). The following code works fine and so do my classes that extend JDialog.
    public static String getInput(String show){
    return JOptionPane.showInputDialog(show);
    }

    I assume you mean: JOptionPane.showConfirmDialog(this, ...)
    problem is that 'this' isn't a Component.

  • 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 showConfirmDialog problem

    Hello everyone,
    I have written my own class that shows a customized confirm dialog (code is pasted below). I need to be able to tell whether the user clicks "YES", "NO" or "CANCEL".
    My main app has a panel with a JButton "Start System". When this button is clicked, the following code instantiates OperatorConfirmDialog:
         public void startNetwork(){
              confirmDialog = new OperatorConfirmDialog("Are you sure you want to start the network?");
              System.out.println("WE MADE IT TO HERE");//problem we do not get to here until confirm dialog acked
         }I referred to the examples for JOptionPane given at:
    http://java.sun.com/j2se/1.5.0/docs/api/index.html
    for examples but it doesn't seem to be working for me.
    Here is the code for OperatorConfirmDialog
    public class OperatorConfirmDialog extends JFrame {
         JOptionPane pane;
         public OperatorConfirmDialog(String message){
              pane = new JOptionPane();
              this.setDefaultLookAndFeelDecorated(true);
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.getContentPane().setLayout(new BorderLayout());
              pack();
              //pane.getSelectionValues()
              pane.showConfirmDialog(this, message, "Confirm", JOptionPane.YES_NO_CANCEL_OPTION);
              Object selectedValue = pane.getValue();  //problem here
              if(selectedValue == null){
                   //do nothing...they just killed window
              }else {
                   for(int counter = 0, maxCounter = pane.getOptions().length; counter < maxCounter; counter++){
                        if(pane.getOptions()[counter].equals(selectedValue)){
                             //do something
              this.dispose();
         public JOptionPane getPane(){
              return pane;
         public static void main(String[] args) {
              OperatorConfirmDialog dialog = new OperatorConfirmDialog("Please enter a valid username.");
    }I put a break point at the line:
    if(selectedValue == null){
    When I run the debugger, confirmDialog prompts me to click "YES", "NO" or "CANCEL". I click "YES" and then arrive at the breakpoint. But, selectedValue doesn't seem to have the right value....the debugger says its value is "uninitializedValue" (literally). Any ideas?
    Thanks!

    Try this. Notice I received an int result from the showConfirmDialog() method.
    import javax.swing.*;
    import java.awt.*;
    public class OperatorConfirmDialog extends JFrame {
        JOptionPane pane;
        public OperatorConfirmDialog(String message) {
            pane = new JOptionPane();
            this.setDefaultLookAndFeelDecorated(true);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.getContentPane().setLayout(new BorderLayout());
            pack();
    // get the response from the user
            int result = pane.showConfirmDialog(this, message, "Confirm", JOptionPane.YES_NO_CANCEL_OPTION);
            if (JOptionPane.YES_OPTION == result) {
                // do what you want on 'yes' clicked
                System.out.println("User Clicked 'Yes'.");
            } else {
    // user clicked 'no' or 'cancel'... you could check result for JOptionPane.NO_OPTION or CANCEL_OPTION
                System.out.println("User Clicked either 'No' or 'Cancel'.");
            this.dispose();
        public JOptionPane getPane() {
            return pane;
        public static void main(String[] args) {
            OperatorConfirmDialog dialog = new OperatorConfirmDialog("Please enter a valid username.");
    }

  • JOptionPane handling problem

    Hi all,
    I'm imlementing a GUI using JPanel and paintComponent(Graphics g).
    When i have to display some data on the screen i use JOptionPane.showMessageDialog(...) and the data are displayed.
    The problem is that, when i close the Message Dialog, it doesn't completely disappear from the screen and so my screen is being messed up. I think it has to do with the graphic environment but i can't figure out what exactly is the problem.
    Thanks,
    John.

    I'm imlementing a GUI using JPanel and
    paintComponent(Graphics g).
    When i have to display some data on the screen i use
    JOptionPane.showMessageDialog(...) and the data are
    displayed.hello John,
    are you invoking JPanel's paintComponent ?public void paintComponent(Graphics g)
          super.paintComponent(g);
          //your painting stuff...
    }Not calling JPanel's paintComponent can cause background-painting problems.
    regards,
    Tim

  • JOptionPane event blocking problem

    Hi,
    JOptionPane is causing me a problem.
    I have a simple frame that contains a text field and a button.
    Pressing the button should write something to the standard output.
    When the text field loses focus a JOptionPane in poped to the user.
    The following scenario is problematic:
    1. The text field owns the focus.
    2. The user presses the button.
    Expected result:
    The JOptionPane appears due to the lost focus event on the text field.
    After closing it some text is written to the standard output due to the action event on the button.
    The actual result:
    The JOptionPane does appears but after closing it nothing is written to the standard output. The button stays in a curious state (when the mouse hovers over the button the button looks pressed, and when the mouse doesn't hover over the button the button looks unpressed).
    Probable reason for this behaviour:
    The JOptionPane blocks all awt/swing events while it is opened. Some of the button code is perfomed due to the button press, but the ActionListener's actionPerformed method is not invoked.
    I need the actionPerfomed method to be invoked.
    Can anyone help me?
    Here is the source code:
    package test;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Test {
    public Test() {
    public static void main(String[] args) {
    //Test test1 = new Test();
    final JFrame f = new JFrame("Test");
    JButton b = new JButton("Click Here");
    JTextField tField = new JTextField("Text", 10);
    f.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    b.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    System.out.println("Button pressed!");
    tField.addFocusListener(new FocusAdapter() {
    public void focusLost(FocusEvent e) {
    if (e.isTemporary()) return;
    JOptionPane.showMessageDialog(f,
    "Focus lost",
    "Title",
    JOptionPane.INFORMATION_MESSAGE);
    JPanel content = (JPanel)f.getContentPane();
    content.setLayout(new BoxLayout(content, BoxLayout.X_AXIS));
    content.add(tField);
    content.add(Box.createHorizontalStrut(5));
    content.add(b);
    f.pack();
    f.show();
    Thanks,
    Shai

    Hello Shai.
    The JOptionPane seems to consume all events when its shown. (Check the stack after JOptionPane is shown.) I've solved a similar problem with the SwingUtilities.invokeLater() method. Maybe the following example will help:
    Runnable doDlgError = new Runnable() {
    public void run() {
    JOptionPane.showMessageDialog(this, "Error", "Error",
    JOptionPane.ERROR_MESSAGE);
    SwingUtilities.invokeLater(doDlgError);
    -Olaf

  • Problems inputing data through JOptionpane to a Access Database

    I am kinda stuck at how to input a new order through JOptionpane's that adds new information into a MS Access Database. I have been fine with coding to get an order through a search JOptionpane as shown below:
    if (e.getSource() == btnCheckOrder)
    String strInput=JOptionPane.showInputDialog("Enter an order number");
    LinkedList Orders = Xenon.findOrders((long)Integer.parseInt(strInput));
    if(Orders==null)
    txtDisplay.setText("No Results Found! Please Try Again!");
    else
    txtDisplay.setText(Orders.toString());
    Any help or advice on how to solve this problem would be great, as im at my wits end.

    So far i have came up with this in my GUI class:
    if (e.getSource()== btnAddOrder)
    String Orders = JOptionPane.showInputDialog(this,"Order Number", "New Order Number",JOptionPane.INFORMATION_MESSAGE);
    if (Orders == null)
    return;
    String strInput = JOptionPane.showInputDialog("Customer Number", "Enter Customer Number");
    long CustNum = 0;
    strInput = JOptionPane.showInputDialog("Part Number", "Enter Part Number");
    long part_Num = 0;
         strInput = JOptionPane.showInputDialog("Number Ordered", "Enter Number Ordered");
    long Num_Ordered = 0;
         strInput = JOptionPane.showInputDialog("Quoted Price", "Enter Quoted Price");
    double Quoted_Price = 0;
         strInput = JOptionPane.showInputDialog("Order Date", "New Order Date");
    long OrderDate = 0;
         strInput = JOptionPane.showInputDialog("Rep Number", "Enter Rep Number");
    long repNum = 0;
    confirmDialog = new JDialog((Frame) null,"Dialog",true);
    Container dialogContentPane = confirmDialog.getContentPane();
    dialogContentPane.setLayout(new FlowLayout());
    JButton okButton = new JButton("OK");
    okButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e ){confirmDialog.dispose();}
    dialogContentPane.add(new JLabel("Confirm New Order"));
    dialogContentPane.add(okButton);
    confirmDialog.setBounds(150,150,150,120);
    confirmDialog.show();
    This seems to work but doesnt add the data i input into the database.

Maybe you are looking for