JOptionPane, EventQueue & WToolkit Problem

I have a swing 1.2 application where I have a customized EventQueue which checks to see how long something proceses. If the event is too long, it turns the cursor to an hourglass and then turns it back to the default cursor when complete. The problems comes in whenever I have a JOptionPane (and JDialog for that matter).
If I'm processing a button event and I throw up a JOptionPane to ask a question, I want to continue processing the original button logic. This works fine. However, I notice I get a
sun.awt.windows.WToolkit object in my SystemEventQueue. I really need to get the component instead so I can set the hourglass. Does anyone have an idea on how to do this? TIA!

First of all, thanks for taking the time to look at my problem.
Here's some answers to the previous questions.
1. The hourglass cursor is displayed until the JOptionPane or JDialog is displayed. Then the default cursor is displayed. Once a user clicks on a yes/no/cancel button, my program will do some tasks like updating and reading records. During this updating and reading process, I want to display the hourglass. Since I know I get an object back to the event queue, I can time the actions and set the cursor - well, in every case but JOptionPane & JDialog. I really hate the thought of having to code the cursor logic in every method that calls a JOptionPane/JDialog. Just goes against the grain. There has to be a better way.
2. Usually, I get component objects sent back to the event queue. However, whenever a JDialog or JOptionPane is displayed, I get a WToolkit object. I have no idea why. Anything else will send back components like the button,etc.
FYI... my event queue is very similar to the one listed in Java World Tip #87 (see link http://www.javaworld.com/javatips/jw-javatip87.html). I just modified it to use a glasspane.

Similar Messages

  • 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

  • JOptionPane and Applet problem

    Hi folks,
    I have an applet, I want to display a pop up dialog whenever the user
    does something. SO i used JOptionPane:
    int userIn=JOptionPane.showInternalConfirmDialog(this,"Do you wish to generate xml for each ics/ids files pair in this data set?", "information",JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
    //repaint();
    The dialog just doesn't show up, I tried repaint(), tried JApplet, nothing works, what am I missing? I'm pretty sure the above code gets called.
    thanks

    A. Are you sure this code is executing?
    B. Are you sure you aren't getting an error, possibly something like
    java.lang.RuntimeException: JOptionPane: parentComponent does not have a valid parent
    at javax.swing.JOptionPane.createInternalFrame(JOptionPane.java:1161)
    at javax.swing.JOptionPane.showInternalOptionDialog(JOptionPane.java:1025)
    at javax.swing.JOptionPane.showInternalConfirmDialog(JOptionPane.java:967)
    at javax.swing.JOptionPane.showInternalConfirmDialog(JOptionPane.java:931)

  • Creating GUI + EventQueue.invokeAndWait problem

    Hi,
    Currently I am creating GUI to my application ,thanks to NetBeans Graphic Editor ,I created simple grame with one buton.Now i am trying to add action to this button listener.Generally i want to make that if this button is pressed,new frame with game itself is opening.Firstly I tried with following code:
      java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    a = new NewJFrame1();
                           a.setVisible(true);
            });Everything seemed to be fine apart form the fact that when the new frame has opened,key listenesr in this new game frame weren't working.I read a liitle and I decided to modify my code a bit:
      java.awt.EventQueue.invokeAndWait(new Runnable() {
                public void run() {
                    a = new NewJFrame1();
                           a.setVisible(true);
            });Unfortunately I got error message from complier:
    ava:154: unreported exception java.lang.InterruptedException; must be caught or declared to be thrown
    java.awt.EventQueue.invokeAndWait(new Runnable() {
    I thought that i need to add try block with catching InterruptedException but still doesn't work.
    Please help my please.I would be grateful if someone could correct this short code so it is working propoerly

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) throws InterruptedException {
           try{ 
            java.awt.EventQueue.invokeAndWait(new Runnable() {
                public void run() {
            //     try{
                     new ramka().setVisible(true);
                        //  if(a.isVisible()==false){b.setVisible(false);}
          //        catch(InterruptedException e){}
           catch(InterruptedException e){}
    }

  • Updating records in the database problem...

    hi, hello to all members, my problem is this, i can't update my records, my table name is UsrTable with a two fields only, which UsrName and Password. all i want to do is when the user wants to sign up and enters there username and password the database will be updated of the new record. i paste the sorce code in here to make it precise co'z i cant figure out how to update the database, sorry if the coding is too long and not good , im just a beginner in JAVA especially using JDBC.
    ****START CODE*****
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.sql.*;
    public class SignIn extends JFrame
    private JPanel jInput;
    private JPanel jButton;
    private JButton Savebtn,Exitbtn;
    private JLabel userlbl,passlbl,connectionLabel;
    private JTextField Usertxt;
    private JPasswordField Passtxt;
    public static final String DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver";
    public static final String url = "jdbc:odbc:UserInfo";
    public static final String DATABASE = "\\User.mdb";
    private Connection connect ;
    public String tmpUser,tmpPass,query;
    public SignIn()
    super("Create your Account..");
    setResizable(false);
    ImageIcon imgIcon = new ImageIcon("c:/JavaCourseware/Images/cdicon.jpg");
    this.setIconImage(imgIcon.getImage());
    addWindowListener(new WindowAdapter()
    { // Opens addWindowListener method
    public void windowClosing(WindowEvent e)
    { // Opens windowClosing method
    int result;
    result = JOptionPane.showConfirmDialog( null,"Are you sure you want to exit?",
    "Confirmation Required...", JOptionPane.YES_NO_OPTION );
    if(result == JOptionPane.YES_OPTION)
    System.exit(0);
    else
    return;
    } // Closes windowClosing method
    }); // Closes addWindowListener method
    try
    InitComp();
    catch(Exception e)
    public void InitComp() throws Exception
    Usertxt = new JTextField(15);
    Passtxt = new JPasswordField(15);
    connectionLabel = new JLabel();
    userlbl = new JLabel("Enter your username: ");
    passlbl = new JLabel("Enter your password: ");
    Savebtn = new JButton("Save");
    Exitbtn = new JButton("Exit");
    this.setSize(new Dimension(320,150));
    this.setLocationRelativeTo(null);
    this.getContentPane().setBackground(Color.blue);
    connectionLabel.setForeground(Color.YELLOW);
    connectionLabel.setBackground(Color.BLUE);
    connectionLabel.setFont(new Font("Arial", Font.PLAIN , 12));
    buildTxtInput();
    buildBtn();
    this.getContentPane().add(connectionLabel,BorderLayout.NORTH);
    this.getContentPane().add(jInput,BorderLayout.CENTER);
    this.getContentPane().add(jButton,BorderLayout.SOUTH);
    //make a connection
    try
    //url = "jdbc:odbc:UserInfo";
    Class.forName(DRIVER);
    connect = DriverManager.getConnection(url);
    connectionLabel.setText("You have made a successful connection to: " + DATABASE);
    catch(ClassNotFoundException cnfx)
    cnfx.printStackTrace();
    connectionLabel.setText("Connection unsuccessful" + cnfx.toString());
    catch (SQLException sqlx)
    sqlx.printStackTrace();
    connectionLabel.setText("Connection unsuccessful" + sqlx.toString());
    catch (Exception ex)
    ex.printStackTrace();
    connectionLabel.setText("Connection unsuccessful" + ex.toString());
    Savebtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    try
    Statement state = connect.createStatement();
    if (Usertxt.getText().equals("") && Passtxt.getText().equals(""))
    connectionLabel.setText("Invalid Input!");
    JOptionPane.showMessageDialog( null, "Invalid Entry", "Saving Abort...", JOptionPane.INFORMATION_MESSAGE );
    state.close();
    else
    state.executeUpdate("INSERT INTO UsrTable" +
    "VALUE UsrName = '" +
    Usertxt.getText() +"' AND Password = '" +
    Passtxt.getText() +"'");
    JOptionPane.showMessageDialog(null, "Your account is already created!","Thank you...",
    JOptionPane.INFORMATION_MESSAGE);
    state.close();
    catch (SQLException sqlex)
    sqlex.printStackTrace();
    connectionLabel.setText(sqlex.toString());
    });//end of Save Listener
    public static void main(String args[])
    SignIn Signfrm = new SignIn();
    Signfrm.show();
    private void buildTxtInput()
    jInput = new JPanel();
    jInput.setLayout( new GridLayout(2, 2, 0, 10) );
    //user.setForeground(Color.yellow);
    jInput.setBorder(BorderFactory.createTitledBorder(""));
    //pass.setForeground(Color.yellow);
    jInput.add(userlbl);
    jInput.add(Usertxt);
    jInput.add(passlbl);
    jInput.add(Passtxt);
    private void buildBtn()
    jButton = new JPanel();
    jButton.setLayout( new GridLayout(1, 1, 10, 10) );
    jButton.setBorder(BorderFactory.createRaisedBevelBorder());
    jButton.add(Savebtn);
    jButton.add(Exitbtn);
    }//end of class
    ***END PROGRAM***
    im hoping there's someone can help me with this, co'z im badly need it.thanks..again,

    hi! i followed your code, but i get a different error i dont know what is the meaning of error, first heres my code i write...thanks for the fast reply co'z i badly need it.
    Savebtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
                   String password = new String (Passtxt.getPassword());
    if (IDtxt.getText().equals ("")) {
                        JOptionPane.showMessageDialog (null, "Member's Id not Provided.");
                        IDtxt.requestFocus();
    else if (Usertxt.getText().equals ("")) {
                        Usertxt.requestFocus();
                        JOptionPane.showMessageDialog (null, "Username not Provided.");
                   else if (password.equals ("")) {
                        Passtxt.requestFocus();
                        JOptionPane.showMessageDialog (null, "Password not Provided.");
                   else {
                        try {     //INSERT Query to Add Book Record in Table.
                             String q = "UPDATE UsrTable "+"SET UsrName = '"+Usertxt.getText() + "' " +
    "AND Password = '" + password + "'"+"WHERE ID = '" + ID + "'";
                             int result = st.executeUpdate(q);                              if (result == 1) {               .
                                  JOptionPane.showMessageDialog (null, "New User has been Created.");
                                  Usertxt.setText ("");
                                  Passtxt.setText ("");
                                  Usertxt.requestFocus ();
                             else {                                                        JOptionPane.showMessageDialog   (null, "Problem while Creating the User.");
                                  Usertxt.setText ("");
                                  Passtxt.setText ("");
                                  Usertxt.requestFocus ();
                        catch (SQLException sqlex) { }
    and heres the error...
    java.lang.NullPointerException
    at CreateAcc$3.actionPerformed(CreateAcc.java:179)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1786)
    at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:1839)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:245)
    at java.awt.Component.processMouseEvent(Component.java:5100)
    at java.awt.Component.processEvent(Component.java:4897)
    at java.awt.Container.processEvent(Container.java:1569)
    at java.awt.Component.dispatchEventImpl(Component.java:3615)
    at java.awt.Container.dispatchEventImpl(Container.java:1627)
    at java.awt.Component.dispatchEvent(Component.java:3477)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3483)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3198)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3128)
    at java.awt.Container.dispatchEventImpl(Container.java:1613)
    at java.awt.Window.dispatchEventImpl(Window.java:1606)
    at java.awt.Component.dispatchEvent(Component.java:3477)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:456)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)

  • Output Problem with my problem help please

    Here is the Instruction to the problem:
    An interesting problem in number theory is sometimes called the ?necklace problem.? This problem begins with two single-digit numbers. The next number is obtained by adding the first two numbers together and saving only the ones-digit. This process is repeated until the ?necklace? closes by returning to the original two numbers. For example, if the starting numbers are 1 and 8, the output would look like:
    18976392134718
    and below is my program:
    public class Necklace
         public static void main(String[] args)
              int f, s, sum, n, p;
              String first = JOptionPane.showInputDialog ("Enter first number:");
              String second = JOptionPane.showInputDialog ("Enter second number:");
              f = Integer.parseInt (first);
              s = Integer.parseInt (second);
              sum = f + s;
              n = sum % 10;
              p = s;
              while (!(p == f && n ==s))
                   sum = n + p;
                   p = n;
                   n = sum % 10;
              String output = f +""+ s +""+ ++n+"";
              JOptionPane.showMessageDialog (null, output, "Necklace", JOptionPane.INFORMATION_MESSAGE);
    My problem is that I don't know or have any idea how to make the output so it will show all the numbers in between, my ouput it only show the first 3 number, 1 8 and 9

    My problem is that I don't know or have any idea how to make the output so it will show all the numbers in between, my ouput it only show the first 3 number, 1 8 and 9Hello and welcome to the forum. First and foremost, please use code tags when posting code here so that your code will retain its formatting and thus will be readable -- after all, your goal is to get as many people to read your post and understand your code as possible, right?
    To do this, highlight your pasted code (please be sure that it is already formatted when you paste it into the forum; the code tags don't magically format unformatted code) and then press the code button, and your code will have tags.
    Another way to do this is to manually place the tags into your code by placing the tag [code] above your pasted code and the tag [code] below your pasted code like so:
    [code]
      // your code goes here
      // notice how the top and bottom tags are different
    [/code]For instance, here is your code with tags:
    import javax.swing.JOptionPane;
    public class Necklace {
       public static void main(String[] args) {
          int f, s, sum, n, p;
          String first = JOptionPane.showInputDialog("Enter first number:");
          String second = JOptionPane.showInputDialog("Enter second number:");
          f = Integer.parseInt(first);
          s = Integer.parseInt(second);
          sum = f + s;
          n = sum % 10;
          p = s;
          while (!(p == f && n == s))
             sum = n + p;
             p = n;
             n = sum % 10;
          String output = f + "" + s + "" + ++n + "";
          JOptionPane.showMessageDialog(null, output, "Necklace",
                   JOptionPane.INFORMATION_MESSAGE);
    }Next, you can declare your output String before the while loop, and then concatonate a new int on to this inside the loop. Perhaps an even better way is to use a StringBuilder object.

  • JOptionPane goes behind browser window (Help PLEASE!)

    I apologize if this is not the best place to post this question.
    I have an applet that open a JOptionPane using the following:
    int rc = JOptionPane.showConfirmDialog(null,
    "Do you want to save the changes you made to " + appInfo.getName() + "?", ProductInfo.ProductName,
    JOptionPane.YES_NO_CANCEL_OPTION,
    JOptionPane.WARNING_MESSAGE);
    THE PROBLEM I'm seeing is that this JOptionPane pops up for a second and then goes behind the applet browser window.
    I have 2 html files (index.html and product.html). index.html opens product.html in a new browser window (minus the toolbar and menu) using a small javascript (see below for code).
    I only see this problem when I open product.html via index.html. When I open product.html by itself this problem does not occur.
    Please help if you can - thanks ahead of time!!
    INDEX.HTML
    ===============================
    <html>
    <head><title>ProductName&trade;, Version 2.0</title></head>
    <body>
    <script>
    <!--
    /*Full screen window opener script: Written by JavaScript Kit (www.javascriptkit.com) More free scripts here*/
    function winopen(){
    var targeturl="./product.html"
    newwin=window.open("","","scrollbars")
    if (document.all){
    newwin.moveTo(0,0)
    newwin.resizeTo(screen.width,screen.height)
    newwin.location=targeturl
    //-->
    </script>
    <script>winopen()</script>
    </body>
    </html>

    Solved my own problem!!
    I modified index.html (see below) and it now works - the JOptionPane stays on top. Still don't know why though.
    INDEX.HTML
    =============================
    <html>
    <head><title>SwitchView&trade;, Version 2.0</title>
    <SCRIPT>
    function fullWindow(url) {
    var str = "left=0,screenX=0,top=0,screenY=0,resizable";
    if (window.screen) {
    var ah = screen.availHeight - 30;
    var aw = screen.availWidth - 10;
    str += ",height=" + ah;
    str += ",innerHeight=" + ah;
    str += ",width=" + aw;
    str += ",innerWidth=" + aw;
    win=window.open(url, "w", str);
    </SCRIPT>
    </head>
    <body>
    <script>fullWindow('./product.html')</script>
    </body>
    </html>

  • Oracle Driver / JAR problem

    Hi,
    Here is the troublesome code.....
    public void connect()throws Exception{
              //set up the Driver
              try     {     
                   //Problem here when running in a JAR
                   DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
                   JOptionPane.showMessageDialog(null, "Conencted to database!", "Connected",JOptionPane.ERROR_MESSAGE);
              catch(Exception e){
                   System.out.println("Driver initialisation failed");
                   JOptionPane.showMessageDialog(null, "Unable to locate OracleDriver()", "Error in connection",JOptionPane.ERROR_MESSAGE);
              //Make a connection to the database     
              try {
                   theConnection = DriverManager.getConnection(c.getDbUrl(), c.getUserName(), c.getPassword());
              catch(Exception e) {
                   System.out.println("failed to make a connection");
                   JOptionPane.showMessageDialog(null, "Problem in connection. Please check database connection settings and re-try.", "Error in connection",JOptionPane.ERROR_MESSAGE);
         }This code works fine when running via Eclipse, but, when I put it into an executatble JAR, it fails. I know it fails at the line DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver()); (as you can see in the code above)
    Any ideas?
    liktid

    I replaced
    DriverManager.registerDriver (new
    oracle.jdbc.driver.OracleDriver());with
    Driver driver =
    (Driver)Class.forName("oracle.jdbc.driver.OracleDriver
    ").newInstance();
    DriverManager.registerDriver( (java.sql.Driver)
    er) driver);now an error gets caught on EVERY occasion (as seen
    in the code in the first post), even in eclipse. The
    previous version was ok. any further suggestions?
    litkidNone of that stuff is necessary. This is sufficient:
    Class.forName("oracle.jdbc.driver.OracleDriver");This works in production for me.
    Your problem is that your executable JAR manifest Class-Path doesn't include the ojdbc14.jar OR that JAR isn't where your Class-Path says it should be relative to your executable JAR.
    %

  • JOptionPane.showMessageDialog() help

    I am trying to do a search on names inwhich i input into a file and then show them on a joptionpane. My problem is that I can't get it to run b/c it says that i have incompatable types. Please help if at all possible.
    String name, custid, num, result;
    int id, element;
    public void search(){
    num = JOptionPane.showInputDialog("Enter Customer ID:");
    id = Integer.parseInt(num);
    name = tree.lookUp(id);
    result = JOptionPane.showMessageDialog(null,new JTextArea(name));
    }

    result = JOptionPane.showMessageDialog(null,new JTextArea(name));your wrong if the JOptionPane.showMessageDialog()'return type is void,it means it hasn't a return value and you want to put a value to "result",you should use like this
    JOptionPane.showMessageDialog(null,new JTextArea(name));

  • Focus Problem (Java 6)

    Hallo guys,
    I am sorry that I cannot provide a running application but just a method. What I wanted to do is to compare two formatted text field and if they don't have valid values it throws a JOptionPane. My problem is that I see this Joptionpane at least 3-4 times. Can anyone help me? Actually as I debugged it, I saw that whenever I lose the focus from the first component, it doesn't only run the focus event of the first component, but it also runs the focus events of the second component. That's what I actually DON'T want to have. If anyone can help me I will be glad.
    private void initValues(String value) {
            MaskFormatter mask = new MaskFormatter();
            mask.setValidCharacters("0123456789");
            componentFrom.setFormatterFactory(new DefaultFormatterFactory(new RangeNumberFormatter(new Integer(0),
                    new Integer(999999),
                    new DecimalFormat("######"))));
            componentTo.setFormatterFactory(new DefaultFormatterFactory(new RangeNumberFormatter(new Integer(0),
                    new Integer(999999),
                    new DecimalFormat("######"))));
            getContentPanel().setLayout(gridBagLayout);
            getContentPanel().add(new JLabel(" " + res.getString("DynamicFromTo.from")), new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 10), 0, 0));
            getContentPanel().add(componentFrom, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 10), 0, 0));
            getContentPanel().add(new JLabel(res.getString("DynamicFromTo.to")), new GridBagConstraints(2, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 10), 0, 0));
            getContentPanel().add(componentTo, new GridBagConstraints(3, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 5), 0, 0));
            getContentPanel().add(new JLabel(value), new GridBagConstraints(4, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 5), 0, 0));
            componentFrom.addFocusListener(new FocusListener() {
                public void focusGained(FocusEvent e) {
                    if (componentFrom.getText().equals("") && componentTo.getText().equals("")) {
                        if (isCommentable()) {
                            comment.setEnabled(false);
                    } else {
                        if (isCommentable()) {
                            comment.setEnabled(true);
                public void focusLost(FocusEvent e) {
                    StringBuffer temp = new StringBuffer(componentFrom.getText());
                    componentFrom.setText(temp.toString());
                    if (!e.isTemporary()) {
                        if (!isNumeric(componentFrom.getText())) {
                            componentFrom.setText(componentFrom.getText());
                        } else {
                            String fromStr = ((JTextField) (e.getSource())).getText();
                            String fromStr2 = fromStr.replace(',', '.');
                            String toStr = componentTo.getText().trim();
                            String toStr2 = toStr.replace(',', '.');
                            if (!fromStr2.equals("") && (!toStr2.equals("")) && isNumeric(toStr2) && isNumeric(fromStr2)) {
                                double to = Double.parseDouble(toStr2);
                                double from = Double.parseDouble(fromStr2);
                                if (from > to) {
                                    JOptionPane.showMessageDialog(null, res.getString("DynamicFromTo.error"));
                                   componentFrom.requestFocus();
            componentTo.addFocusListener(new FocusAdapter() {
                public void focusGained(FocusEvent e) {
                    if (componentFrom.getText().equals("") && componentTo.getText().equals("")) {
                        if (isCommentable()) {
                            comment.setEnabled(false);
                    } else {
                        if (isCommentable()) {
                            comment.setEnabled(true);
                public void focusLost(FocusEvent e) {
                    StringBuffer temp = new StringBuffer(componentTo.getText());
                    componentTo.setText(temp.toString());
                    if (((JTextField) (e.getSource())).getText().trim().equals("")) {
                        if (isCommentable()) {
                            comment.setEnabled(false);
                    } else {
                        if (isCommentable()) {
                            comment.setEnabled(true);
                    String toStr = ((JTextField) (e.getSource())).getText();
                    String toStr2 = toStr.replace(',', '.');
                    String fromStr = componentFrom.getText().trim();
                    String fromStr2 = fromStr.replace(',', '.');
                    if (!toStr2.equals("") && (!fromStr2.equals("")) && isNumeric(toStr2) && isNumeric(fromStr2)) {
                        double to = Double.parseDouble(toStr2);
                        double from = Double.parseDouble(fromStr2);
                        if (from > to) {
                            JOptionPane.showMessageDialog(null, res.getString("DynamicFromTo.error"));
            componentFrom.addKeyListener(new KeyAdapter() {
                public void keyReleased(KeyEvent e) {
                    if ((componentFrom.getText() + ((JTextField) e.getComponent()).getText()).length() == 0) {
                        if (componentTo.getText().trim().equals("")) {
                            if (isCommentable()) {
                                comment.setEnabled(false);
                    } else {
                        if (isCommentable()) {
                            comment.setEnabled(true);
            componentTo.addKeyListener(new KeyAdapter() {
                public void keyReleased(KeyEvent e) {
                    if ((componentFrom.getText() + ((JTextField) e.getComponent()).getText()).length() == 0) {
                        if (isCommentable()) {
                            comment.setEnabled(false);
                    } else {
                        if (isCommentable()) {
                            comment.setEnabled(true);
            components.add(componentFrom);
            components.add(componentTo);
            registerComponent(componentFrom);
            registerComponent(componentTo);
        }Edited by: NEO1976 on Sep 5, 2008 10:04 AM

    I am sorry that I cannot provide a running application but just a method.Well then sorry that I cannot provide an aswer, just a sarcastic response.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.

  • Chart builder finish but some threads are still alive ?!?!?!?

    Hello all,
    I'm using oracle chart builder for presenting data in my
    application. I use it after supplying its data for gif file
    generation. The chart is stacked bar but I don't think this is the
    problem.
    The problem is that it generates the gif file successfully but my
    application is still running after the main method is finished, I
    debugged it and I found about three threads are up:
    Thread[AWT-EventQueue-0]
    Thread[SunToolkit.PostEventQueue-0]
    Thread[AWT-Windows]
    I doubted my code - but I'm taking it copy paste from developer's
    guide - and I debugged another Java file from a sample that comes with
    the kit and the same problem happened ?!?!?
    Does anyone know y?
    I saw lots of SunToolkit.PostEventQueue-0 & AWT-EventQueue-0 problems, but I don't find matching my situation, nearly some mentioned problem in native threads or something, but I think the problem is related to AWT more
    I used in testing both Oracle JDeveloper 9i release 3, and IBM
    WebSphere Studio Application Developer 4.0.3 ( both JDK 1.3)
    Thankx

    I used ctrl-break to display all threads working and the following was printed:
    "Thread-6" prio=5 tid=0x2349f8 nid=0x9e0 waiting on monitor [0..0x6fb38]
    "AWT-Windows" prio=5 tid=0x8a07e50 nid=0x894 runnable [0xba9f000..0xba9fdc4]
    at sun.awt.windows.WToolkit.eventLoop(Native Method)
    at sun.awt.windows.WToolkit.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
    "SunToolkit.PostEventQueue-0" prio=5 tid=0x8a07878 nid=0x88 waiting on monitor [
    0xba5f000..0xba5fdc4]
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Unknown Source)
    at sun.awt.PostEventQueue.run(Unknown Source)
    "AWT-EventQueue-0" prio=7 tid=0x8acbe30 nid=0x980 waiting on monitor [0xba1f000.
    .0xba1fdc4]
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Unknown Source)
    at java.awt.EventQueue.getNextEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    "Thread-4" daemon prio=5 tid=0x8ad6be8 nid=0x90c waiting on monitor [0x99bf000..
    0x99bfdc4]
    at java.lang.Thread.sleep(Native Method)
    at org.apache.log4j.helpers.FileWatchdog.run(FileWatchdog.java:95)
    "Thread-3" daemon prio=5 tid=0x8ad6aa0 nid=0x8c0 waiting on monitor [0x8f5f000..
    0x8f5fdc4]
    at java.lang.Thread.sleep(Native Method)
    at org.apache.log4j.helpers.FileWatchdog.run(FileWatchdog.java:95)
    "Thread-2" daemon prio=5 tid=0x8a37008 nid=0x900 waiting on monitor [0x8f1f000..
    0x8f1fdc4]
    at java.lang.Thread.sleep(Native Method)
    at org.apache.log4j.helpers.FileWatchdog.run(FileWatchdog.java:95)
    "Thread-1" daemon prio=5 tid=0x8b63c0 nid=0x948 waiting on monitor [0x8edf000..0
    x8edfdc4]
    at java.lang.Thread.sleep(Native Method)
    at org.apache.log4j.helpers.FileWatchdog.run(FileWatchdog.java:95)
    "Thread-0" daemon prio=5 tid=0x8b64a8 nid=0x9c0 waiting on monitor [0x8e7f000..0
    x8e7fdc4]
    at java.lang.Thread.sleep(Native Method)
    at org.apache.log4j.helpers.FileWatchdog.run(FileWatchdog.java:95)
    "Signal Dispatcher" daemon prio=10 tid=0x7fdf28 nid=0x72c waiting on monitor [0.
    .0]
    "Finalizer" daemon prio=9 tid=0x7fabb8 nid=0x560 waiting on monitor [0x8c5f000..
    0x8c5fdc4]
    at java.lang.Object.wait(Native Method)
    at java.lang.ref.ReferenceQueue.remove(Unknown Source)
    at java.lang.ref.ReferenceQueue.remove(Unknown Source)
    at java.lang.ref.Finalizer$FinalizerThread.run(Unknown Source)
    "Reference Handler" daemon prio=10 tid=0x7f9368 nid=0x9a8 waiting on monitor [0x
    8c1f000..0x8c1fdc4]
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Unknown Source)
    at java.lang.ref.Reference$ReferenceHandler.run(Unknown Source)
    "VM Thread" prio=5 tid=0x23f638 nid=0xa28 runnable
    "VM Periodic Task Thread" prio=10 tid=0x8a4f48 nid=0x92c waiting on monitor

  • Java code to get integer values from a gridLayout to put into an array?

    I am writing a tictactoe game for a programming class. I made a grid of 3x3 layout and it alternates between putting an X when clicked and an O. I need to know how to retrieve what button off the grid was picked so I can create an array to check for win conditions...Or how to access the rowIndex and columnIndex of a selected button on the grid
    Thanks in advance
    Edited by: ryAnOnFire on May 23, 2010 6:10 PM

    import java.awt.*;
    import java.awt.Container;
    import javax.swing.*;
    import java.awt.event.*;
    public class TicTacToe
         JFrame theWindow;
         JButton theButton;
         Container thePane;
         JTextField theText;
         MyListener theListener;
         public JButton[][] grid = new JButton[3][3];
         public TicTacToe()
              theWindow = new JFrame("Tic Tac Toe");
              theWindow.setSize(250, 250);
              String empty = " ";
             theListener = new MyListener();
              JFrame frame = new JFrame("TicTacToe");
              Container thePane = theWindow.getContentPane();
              thePane.setLayout(new GridLayout (3,3,5,5));
              for(int i = 0; i < 3; i++)
                   for(int j =0; j < 3; j++)
                        grid[i][j] = new JButton(empty);
                        thePane.add(grid[i][j]);
                        grid[i][j].addActionListener(theListener);
              JButton blankSpot = new JButton(empty);
              blankSpot.setFont(new Font("Papyrus", Font.BOLD, 35));
              theWindow.setVisible(true);
         public static void main(String[] args)
              new TicTacToe();
    class MyListener implements ActionListener
              String[][] spots1 = new String[3][3];
              String[][] spots2 = new String[3][3];
              static int playerTurnCounter = 0;
               JButton[][] grid; // !! added
                // !! added
                public MyListener(JButton[][] grid)
                     this.grid = grid;
              public void actionPerformed(ActionEvent e)
                   JButton jb = (JButton)e.getSource();
                   if(playerTurnCounter % 2 == 0)
                        jb.setText("X");
                        for(int i = 0; i < grid.length; i++)
                             for(int j = 0; j < grid.length; j++)
                                  spots1[i][j] = grid[i][j].getText();
                        if((spots1[0][0].equals("X")))
                             JOptionPane.showMessageDialog(null, "TICTACTOE", "WIN", JOptionPane.PLAIN_MESSAGE);
                        //The problem seems to be occuring in the above block commented area
                   else
                        jb.setText("O");
                   jb.setEnabled(false);
                   playerTurnCounter ++;
    Compiler Error:
    C:\Documents and Settings\HP_Administrator\My Documents\TicTacToe.java:24: cannot find symbol
    symbol  : constructor MyListener()
    location: class MyListener
             theListener = new MyListener();
                           ^
    1 error
    Tool completed with exit code 1
    I'm just going to let you ponder over this as I do too...
    I have no idea...my minimal experience with ActionListeners is doing me nothing for this one.
    Edited by: ryAnOnFire on May 23, 2010 8:12 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • ConnectException when using Tomcat 4.1

    Hi,
    I'm trying to run my web application with Tomcat 4.1 (until now I worked with Tomcat 3.2, and didn't have problems).
    In my application I have an applet that reads from a file (the file is located on the web server.)
    When I try to do it (using Url.openStream()) I get:
    java.net.ConnectException: Connection refused.
    I guess I have to configure some kind of permissions in the tomcat configuration files or something like that, but I didn't find anything.
    (In my Java policy tool I made sure to give java.security.AllPermission, but I'm not sure that it's connected).
    Can you please help me?...
    Thanks,
    Efrat

    The code the I use is:
    // With a URL now available, try to esatablish a read
    // mechanism and read in the file as a series of String lines
    try
    InputStream is = sourceUrl.openStream();
    InputStreamReader isr = new InputStreamReader (is);
    BufferedReader d = new BufferedReader (isr);
    return (readLines(d));
    catch (java.io.FileNotFoundException iof)
    Debug.err ("FileNotFoundException: " + iof);
    JOptionPane.showMessageDialog(applet, "Problems with web server were discovered. Device image will not be shown.\nPlease check server and device status and correct, then try to login again.");
    return null;
    catch (IOException e)
    Debug.err ("exception in fetchLines: " + e);
    e.printStackTrace();
    return null;
    The exception that I get is:
    exception in fetchLines: java.net.ConnectException: Connection refused: connect
    java.net.ConnectException: Connection refused: connect
         at java.net.PlainSocketImpl.socketConnect(Native Method)
         at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:305)
         at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:171)
         at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:158)
         at java.net.Socket.connect(Socket.java:426)
         at sun.net.NetworkClient.doConnect(NetworkClient.java:137)
         at sun.plugin.net.protocol.http.HttpClient.doConnect(HttpClient.java:93)
         at sun.net.www.http.HttpClient.openServer(HttpClient.java:386)
         at sun.net.www.http.HttpClient.openServer(HttpClient.java:602)
         at sun.net.www.http.HttpClient.<init>(HttpClient.java:303)
         at sun.net.www.http.HttpClient.<init>(HttpClient.java:264)
         at sun.plugin.net.protocol.http.HttpClient.<init>(HttpClient.java:39)
         at sun.plugin.net.protocol.http.HttpClient.New(HttpClient.java:66)
         at sun.plugin.net.protocol.http.HttpURLConnection.privBlock(HttpURLConnection.java:116)
         at sun.plugin.net.protocol.http.HttpURLConnection$PrivilegedBlockAction.run(HttpURLConnection.java:460)
         at java.security.AccessController.doPrivileged(Native Method)
         at sun.plugin.net.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:167)
         at sun.plugin.net.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:375)
         at java.net.URL.openStream(URL.java:960)
         at pic1.AtricaFetchConfig.fetchLines(AtricaFetchConfig.java:30)
         at pic1.AtricaDeviceObj.buildConfig(AtricaDeviceObj.java:105)
         at pic1.AtricaDeviceObj.buildDevice(AtricaDeviceObj.java:39)
         at pic1.nicApplet.fetchDevice(nicApplet.java:110)
         at pic1.nicApplet.init(nicApplet.java:49)
         at sun.applet.AppletPanel.run(AppletPanel.java:347)
         at java.lang.Thread.run(Thread.java:536)
    I get the exception when doing: InputStream is = sourceUrl.openStream();
    Thanks a lot,
    Efrat

  • Forcing events to happen

    Hello,
    I created a JFileChooser (meCreateChooser) which shows up when the user clicks on a JMenuItem. The user has to type a name for his file and the program checks to see if that name already exists.
    If the typed file name already exists, the program must produce a JOptionPane and prompt the user to type a different name.
         private void myCreateChooserActionPerformed(ActionEvent e) {
              if(e.getActionCommand().equals(JFileChooser.APPROVE_SELECTION)) {
                      // Check if the dictionary name is valid (if it already exists
                   // or not)
                   // true = validation pass, false = validation failure
                   if(true) {
                                     do some things
                   else {
                        // Inform the user that the dictionary name he typed already exists).
                        int response;
                        response = JOptionPane.showConfirmDialog(null, "This file name already exists! Type another.", "File Already Exists", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE);
                                    // My problem is here. How can I force my JFileChooser to show up again?
                        // Force myCreateChooser Listener to listen!!
                        myCreateChooser.showOpenDialog(this); // this is working but
                        // it causes unwanted exceptions!
         }Thank you

    You don't have to force any events. You can just wrap the behavior in a do-while loop, and see whether the resulting file already exists. If it does, repeat. If not, you're done with the loop.
    Something like this should work:
              File f;
              do{
                   int jfcResponse = myCreateChooser.showOpenDialog(this);
                   if(jfcResponse != JFileChooser.APPROVE_OPTION)//If the user clicks cancel or anything else like that, exit from method
                        return;
                   f = myCreateChooser.getSelectedFile();
                   if(f.exists())//if the file chooser's file already exists, show the dialog
                        JOptionPane.showConfirmDialog(null, "This file name already exists! Type another.", "File Already Exists", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE);
              while(f.exists());//repeat until the user inputs a filename of a non-existing file

  • Opening a VHDL file

    In part of my GUI I'm trying to open a file and display the contents in a scrollpane. It is working for .txt and .java files, but when I try to open other text files like .vhd, .vhdl, and .html files it throws an exception. Anyone know how to get around this

    Hey,
    here is some code. VHDL files are for making ASICs. Just a text file that describes the internal logic gates of integrated circuits. I need to parse through them to do key word searches.
    Daniel
    package synopsys;
    import java.awt.*;
    import javax.swing.*;
    import java.io.*;
    import java.awt.event.*;
    public class OpenRoot extends JPanel implements ActionListener{
         static private final String newline = "\n";
         private JPanel mainPanel;
         private JTextArea viewer;
         private JLabel lrootFile, blank;
         private JButton openButton, clearButton;
         private JScrollPane scrollpane;
         private String str, fileName;
         private BufferedReader buffRead;
         private File openFile;
         private JFileChooser chooser;
         private int option;
         private final JLabel statusbar;
         public OpenRoot(){
              statusbar = new JLabel("Output of your selection will be shown below");
              blank = new JLabel("");
              lrootFile = new JLabel("Please open the root VHDL file of your layout");
              lrootFile.setFont(new Font("Times-Roman", Font.PLAIN, 12));
              statusbar.setFont(new Font("Times-Roman", Font.PLAIN, 12));
              mainPanel = new JPanel();
              mainPanel.setLayout(new FlowLayout());
              mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
              mainPanel.setBorder(BorderFactory.createTitledBorder("Open The Top Level Design"));
              viewer = new JTextArea("",30,55);
              viewer.setLineWrap(true);
              viewer.setWrapStyleWord(true);
         viewer.setEditable(false);
              scrollpane = new JScrollPane(viewer);
              scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
              clearButton = new JButton("Clear");
              clearButton.addActionListener(this);
              openButton = new JButton("Open");
              openButton.addActionListener(this);
              mainPanel.add(lrootFile);
              mainPanel.add(blank);
              mainPanel.add(statusbar);
              mainPanel.add(scrollpane);
              mainPanel.add(openButton);
              mainPanel.add(clearButton);
              add(mainPanel);
         public void actionPerformed(ActionEvent e) {
              if((e.getSource() == openButton)){
                   viewer.setText("");
                   chooser = new JFileChooser();
                   option = chooser.showOpenDialog(OpenRoot.this);
                   if (option == JFileChooser.APPROVE_OPTION) {
                        openFile = chooser.getSelectedFile();
                        fileName = openFile.getName();
                        statusbar.setText("You selected: " + fileName);
                        readFileIntoTextArea(fileName);
                   else {
                        statusbar.setText("You canceled.");
              if((e.getSource() == clearButton)){
                   viewer.setText("");
                   statusbar.setText("Output of your selection will be shown below");
         private void readFileIntoTextArea(String readOut){
              try {
                   File f = new File(readOut);
                   buffRead = new BufferedReader (new FileReader(f));
                   while ((str = buffRead.readLine()) != null) {
                        viewer.append(str + newline);
              catch (FileNotFoundException fnfe){
                   JOptionPane.showMessageDialog( null, "File not found.", null, JOptionPane.ERROR_MESSAGE );
                   System.out.println(fnfe);
              catch (IOException ioe){
                   JOptionPane.showMessageDialog( null, "Problem reading file", null, JOptionPane.ERROR_MESSAGE );
                   System.out.println(ioe);
              finally{
                   if (buffRead != null){
                        try{
                   buffRead.close();
              catch (Exception ignored){

Maybe you are looking for

  • How can I get EDGE to publish audio correctly?

    Hi there, I'm new to Adobe EDGE and any sort of HTML5, so please forgive my general ignorance. Also, I've looked through all the open questions on the forum about audio and not found any that relate to my issue I'm trying to work out how to include a

  • Importing Video From a Sony HVR-Z5E into Adobe Premiere CS5

    Hi, I am importing video from the Sony HVR-Z5E straight into Premiere using the capture option off the file menu but the colour looks completely different to what it looks like on the camera. Why should this be? When I preview the video in the captur

  • Streaming BLOBS

    Using JDeveloper2 (production) I can stream BLOBS out of a BLOB column to a buffer, but I can't stream them in. The following is a code snippet attempting to stream a BufferedImage into a BLOB column. When run I get "ORA 1461 can bind a LONG value on

  • IR - Prompting for Year Dimension and using CurrMth Substition Variable

    There's 2 questions. How do I set IR so it prompts up for choosing year dimension (essbase)? I've put year in Column Query and set it as a variable. However, when I put this on workspace it doesn't prompt the user for selection. How do I resolve this

  • Question on SDN (general not abap)

    Hi....     Sorry for wasting your time with general question... Please tell me how to open the diffenrent blogs in SDN? like... The SQL Trace (ST05) – Quick and Easy is for to study ST05... Thanks, Naveen.I