JOptionPane troubles

Hey, I am trying to make a list using JOptionPane so that the user is able to select a string in this list, press ok, and then have that string returned to me. This works fine, and the line of code I've used is....
removeItem = (String)JOptionPane.showInputDialog(null, "Choose the word you want to remove", "Remove word",
                  JOptionPane.QUESTION_MESSAGE, null, sortedList, "");...the problem is, I have just changed the sortedList input to increase my code efficiency, and now rather than displaying...about 8 list items on screen at one time, it now only displays one. Has anyone got any suggestions on how to increase this?
Thanks in advance.

Tom101 wrote:
I'm having some real trouble trying to replicate this problem. As the program stands at the moment, it reads in a text file and places words into an array list along with an int. The program then copies the strings from the array list into an array, sorts them (using arrays.sort), and then sends them to the output. Now if I enter strings manually to the array it works perfectly. and if I modify my current code so it doesn't include arrays.sort it works perfectly when reading them from a file. Is arrays.sort doing something to it, that triggers JOptionPane to work incorrectly? If you want I can post the method up, however without the rest of the program it wont work the same.Perhaps you could create a new program that goes through the above steps, all of them, and nothing more, and also post the smallest text file to demonstrate the problem. It really should be compilable though, not just a naked method.
This program could be quite simple. The pseudocode could look something like this:
begin
   open text file
   read strings into arraylist
   sort arraylist
   convert arraylist to array
   show input dialog and put result into a string
   show string
endEdited by: petes1234 on Dec 19, 2007 5:57 AM

Similar Messages

  • Joptionpane trouble

    hi,
    i was wondering if some could help me wih a few problems i'm having.
    i would like the joptionpane input dialog box only able to enter numbers and if you don't,then i want it to throw up another joptionpane showing that your not allowed to enter alpha numeric values.
    the other thing is when i use joptionpane anywhere except "static void main(String[] args)" how would i prevent the cancel button from crashing the program. also when i do press cancel it allows to take the user back to a previous menu by calling a method i.e "menu();"
    import javax.swing.JOptionPane;
    public class joptionpane
         public static void main(String[] args)
              joptionpane();
         public void joptionpane()
              String result;
              int res;
              result = JOptionPane.showInputDialog("Enter your answer to the question");
              res = Integer.parseInt(result);
    }thanks in advance
    Slice909

    This is not the right way to do it, but it should answer your questions
    import javax.swing.JOptionPane;
    class Testing
      public Testing()
        int[] num = {1,2,3,4,5,6,7,8,9};
        boolean again = true;
        while(again)
          JOptionPane.showMessageDialog(null,"What is "+
          num[(int)(Math.random()*num.length)]+" + "+num[(int)(Math.random()*num.length)]);
          again = menu();
        JOptionPane.showMessageDialog(null,"Cancelled - program terminated");
        System.exit(0);
      public boolean menu()
        boolean validData = false;
        while(!validData)
          String result = JOptionPane.showInputDialog("Enter your answer to the question");
          if(result == null) return false;
          try
            int res = Integer.parseInt(result);
            validData = true;
          catch(Exception e){JOptionPane.showMessageDialog(null,"Invalid Data, try again");}
        return true;
      public static void main(String[] args){new Testing();}
    }

  • Troubles with JOptionPane

    Why am I getting:
    "GUI.java:283: cannot resolve symbol
    symbol: variable frame
    location: class GUI
    frame,
    with this code:
    <code>
    String s = (String)JOptionPane.showInputDialog(
    frame,
    "New",
    JOptionPane.PLAIN_MESSAGE,
    null,
    null,
    "write here");
    </code>

    Ensure you have defined the variable frame (Component). If yes, Check the scope of declaration of variable "frame".
    --Mars
    Why am I getting:
    "GUI.java:283: cannot resolve symbol
    symbol: variable frame
    location: class GUI
    frame,
    with this code:
    <code>
    String s = (String)JOptionPane.showInputDialog(
    frame,
    "New",
    JOptionPane.PLAIN_MESSAGE,
    null,
    null,
    "write here");
    </code>

  • Still having trouble with the checkWinner

    it's making it so that every empty array spot is equal so the checkWinner method is screwing up, any ideas on how to fix this?
    import javax.swing.*;
    import java.text.*;
    import java.applet.*;
    import java.io.*;
    import java.awt.*;
    import java.lang.*;
    import java.util.*;
    import java.math.*;
    import java.sql.*;
    import java.security.*;
    import java.beans.*;
    import javax.crypto.*;
    import javax.net.*;
    import org.omg.CORBA.*;
    import java.awt.color.*;
    import java.util.jar.*;
    public class TwoDArray
         String [] [] board=new String [3] [3];
         int x;
         public TwoDArray()
              for(int x=0;x<3;x++)
                   for(int y=0;y<3;y++)
                        board[x][y]="";
         public void getMove(int row, int col, String letter)
              if(board[row][col].equalsIgnoreCase(""))
                   board[row][col]=letter;
              x++;
         public void printBoard()
              for(int x=0;x<3;x++)
                   System.out.print("|");
                   for(int y=0;y<3;y++)
                        System.out.print(board[x][y]);
                   System.out.println("|");
         public boolean checkWinner()
              boolean win=false;
              if(x>=3)
                   if(board[0][0].equalsIgnoreCase(board[0][1])&&board[0][0].equalsIgnoreCase(board[0][2]))
                        win=true;
                        return win;
                   if(board[0][0].equalsIgnoreCase(board[1][0])&&board[0][0].equalsIgnoreCase(board[2][0]))
                        win=true;
                        return win;
                   if(board[0][1].equalsIgnoreCase(board[1][1])&&board[0][1].equalsIgnoreCase(board[2][1]))
                        win=true;
                        return win;
                   if(board[0][2].equalsIgnoreCase(board[1][2])&&board[0][2].equalsIgnoreCase(board[2][2]))
                        win=true;
                        return win;
                   if(board[1][0].equalsIgnoreCase(board[1][1])&&board[1][0].equalsIgnoreCase(board[1][2]))
                        win=true;
                        return win;
                   if(board[2][0].equalsIgnoreCase(board[2][1])&&board[2][0].equalsIgnoreCase(board[2][2]))
                        win=true;
                        return win;
                   if(board[0][0].equals(board[1][1])&&board[0][0].equalsIgnoreCase(board[2][2]))
                        win=true;
                        return win;
                   if(board[2][0].equals(board[1][1])&&board[2][0].equalsIgnoreCase(board[0][2]))
                        win=true;
                        return win;
              return win;     
         public static void main(String[] args)
              boolean winner=false;     
              String player1="X";
              String player2="O";
              String instructions="Welcome to Tic-Tac-Toe.";
              for (int i = 0;i<instructions.length() ;i++ )
                    System.out.print(instructions.charAt(i));
              try
              Thread.sleep(99);
              }catch(InterruptedException e) {e.printStackTrace();}
              System.out.println();
              TwoDArray board=new TwoDArray();
              String input1=JOptionPane.showInputDialog("Enter the row you wish to move in.");
              int rowmove=Integer.parseInt(input1);
              String input2=JOptionPane.showInputDialog("Enter the column you wish to move in.");
              int colmove=Integer.parseInt(input2);
              board.getMove(rowmove,colmove,player1);
              board.printBoard();
              while(winner==false)
                   String input3=JOptionPane.showInputDialog("Enter the row you wish to move in.");
                   int rowmove2=Integer.parseInt(input3);
                   String input4=JOptionPane.showInputDialog("Enter the column you wish to move in.");
                   int colmove2=Integer.parseInt(input4);
                   board.getMove(rowmove2,colmove2,player2);
                   board.printBoard();
                   board.checkWinner();
                   if(board.checkWinner()==true)
                        System.out.println("O WINS");
                        System.exit(0);
    String input5=JOptionPane.showInputDialog("Enter the row you wish to move in.");
              int rowmove3=Integer.parseInt(input5);
    String input6=JOptionPane.showInputDialog("Enter the column you wish to move in.");
              int colmove3=Integer.parseInt(input6);
              board.getMove(rowmove3,colmove3,player1);
                   board.printBoard();
                   board.checkWinner();
                   if(board.checkWinner()==true)
                   System.out.println("X WINS");
                        System.exit(0);
    }

    if(board.checkWinner()==true)can be:
    if(board.checkWinner())
    if(winner==false)can be:
    if(!winner)It isn't actually causing trouble right now, but the "x" in the constructor and in printBoard hide the member variable "x". If you aren't careful, you will use the wrong "x" somewhere and confuse yourself. Besides, the member variable "x" is a bad name. It should be "numberOfMoves" or something like that.
    Once you fix what scsi-boy said with checkWinner, take out all but the last "return winner;" line, and change it to "if...else if...else if...else if..." It is cleaner to have only one return statement. And, once one "if" is true, you don't need to check the rest.

  • I am currently having trouble with an attached PDF fill-able form...Help Please

    Hello, I was wondering if you would be able to help me out?
    I am having trouble with my attached PDF fill-able form, I am creating a form that has a limit of one page so in order for more room in a certain field I have added a Hyperlink to an additional fill-able(secondary) form within the Parent document (primary fill-able form. The secondary form is inserted as an attachment into the Primary form. My problem is when I open this document up in Adobe Reader, the Primary fill-able form is savable but the attached Secondary form for which the hyperlink leads to is non-savable and is a must print only. Is there a way to make the Secondary form savable as well within the same document? or is there another way I could execute what it is I am trying to achieve?
    Help would be greatly appreciated please and thank you!

    Here is the code, thought I had put it in the first time, guess not heh. Anyway, I converted the arrayList(accountList) to a String so that I could see the that element I am trying to index is in there, which it is. I also checked the file that i'm populating the arrayList from and it also has the element in it.
    public static void getAccountNumbers() {
              accountList = LoadStoreAccounts.readCollectionObject();     
              accountInfo = accountList.toString();
              JOptionPane.showMessageDialog(null, accountInfo);
              acctNumIndex = accountList.indexOf(accountNumber);
              acctIndex = String.valueOf(acctNumIndex);
              JOptionPane.showMessageDialog(null, "Index of accountNumber    is: " + acctIndex);

  • JOptionPane: not disappearing properly on seleting "Cancel"

    /*takes SQL statement input SQL Input Window, shows table in Center-Right,Tree in Center-Left,
    and gives number of records returned in South text field.
    import java.awt.*;
    import java.awt.event.*;  
    import javax.swing.*;                    
    import javax.swing.text.BadLocationException;
    import javax.swing.table.*;     
    import javax.swing.tree.*;
    import java.sql.*;   
    import java.util.Vector;
    public class DataBaseAppCombined
      static DataBaseBrowse1 window;  
      public static void main(String[] args)
        window = new DataBaseBrowse1();    
        Toolkit theKit = window.getToolkit(); 
        Dimension wndSize = theKit.getScreenSize();
        window.setBounds(0, 0,
         wndSize.width,
         wndSize.height);                  
        window.setVisible(true);
    class DataBaseBrowse1 extends JFrame implements ActionListener
      public DataBaseBrowse1()
       super("Visual Data");
    //This dialog box doesn't respond appropriately to "Cancel" or "No"
       addWindowListener(new WindowAdapter(){
              public void windowClosing(WindowEvent e)
                   if (JOptionPane.showConfirmDialog(null,"Do you really want to quit now?")
                   == JOptionPane.YES_OPTION)
                        dispose();
                        System.exit(0); 
              // Create the menubar from the menu items
              JMenu fileMenu = new JMenu("File");
              fileMenu.setMnemonic('F');
              fileMenu.add(connectItem);
              connectItem.addActionListener(this);
              fileMenu.add(clearQueryItem);
              clearQueryItem.addActionListener(this);
              fileMenu.add(exitItem);
              exitItem.addActionListener(this);
              menuBar.add(fileMenu);   
        setJMenuBar(menuBar);        
        JPanel commandPane = new JPanel(); //holds label and textArea for SQL queries
        commandPane.setLayout(new BorderLayout());
        commandPane.add(new JLabel("Enter SQL query here: ", JLabel.LEFT),BorderLayout.WEST);
        command.setToolTipText("Key SQL commmand and press Enter");
        command.setLineWrap(true);
        command.setWrapStyleWord(true);
        command.addKeyListener(new KeyHandler());     
        commandPane.add(command, BorderLayout.CENTER);
        getContentPane().add(commandPane, BorderLayout.NORTH);
        // Add the status reporting area at the bottom
        status.setLineWrap(true);
        status.setWrapStyleWord(true);
        status.setEditable(false);
        getContentPane().add(status, BorderLayout.SOUTH);
              // Create a table model to go in right splitPane
              tableModel = new ResultsModel();
              JTable table = new JTable(tableModel);
              table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);  
              tablePane = new JScrollPane(table);
              tablePane.setBorder(BorderFactory.createLineBorder(Color.darkGray));
              //create tree to go in left splitPane
              dbNode = new DefaultMutableTreeNode("No Database");
              dbTreeModel = new DefaultTreeModel(dbNode);
              dbTree = new JTree(dbTreeModel);
              treePane = new JScrollPane(dbTree);
              treePane.setBorder(BorderFactory.createLineBorder(Color.darkGray));
              JSplitPane splitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                       true,        //continuous relayout
                       treePane,    //Left pane content
                       tablePane);  //Right pane content
              getContentPane().add(splitpane, BorderLayout.CENTER);
              splitpane.setDividerLocation(400);
        pack();
        //setVisible(true);
         //get variables out of User object
         //and connect to driver
         public void initializeUser(User _user)
              driver = _user.getDriver();
              url = _user.getURL();
              password = _user.getPassword();
              user = _user.getUser();
              try
                   Class.forName(driver);                          
                   connection = DriverManager.getConnection(url, user, password);
                   statement = connection.createStatement();
                   catch(ClassNotFoundException cnfe)
                   System.err.println(cnfe);
                   catch(SQLException sqle)
                   System.err.println(sqle);
      public void actionPerformed(ActionEvent e)
        Object source = e.getSource();
              if(source == clearQueryItem)
              try
               command.getDocument().remove(0,len);
              catch (BadLocationException ex)
                             System.err.println(ex);
        else if(source == exitItem)                
    //This dialog box does respond appropriately to "Cancel" and "No".
                   if (JOptionPane.showConfirmDialog
                   (null,"Do you really want to quit now?")
                   == JOptionPane.YES_OPTION)
                        dispose();
                        System.exit(0); 
        else if (source ==connectItem)
             showPasswordDialog();
         public void showPasswordDialog()
               // if first time, construct dialog
               if (dlgPanel == null)
                        dlgPanel = new PasswordChooser();
               // pop up dialog
               if (dlgPanel.showDialog(null,
                        "Connect"))
                        // if accepted, retrieve user input as a User object
                        User u = dlgPanel.getUser();
                        DataBaseBrowse1.this.initializeUser(u);
      public void executeSQL()
        //retrieve the text from the JTextField as SQL statement
        try
                   len = command.getDocument().getLength();
                   stringIn = command.getDocument().getText(0,len);
                   query = stringIn.trim();
                   if(query == null) 
          return;
              catch (BadLocationException e)
                   System.err.println(e + "bad location");
        try
          tableModel.setResultSet(statement.executeQuery(query));
          status.setText("Resultset has " + tableModel.getRowCount() + " rows.");
        catch (SQLException sqle)
          status.setText(sqle.getMessage());
         class KeyHandler extends KeyAdapter
              //Handler for Enter key events
              public void keyPressed(KeyEvent e)
                   int keyCode = e.getKeyCode();
                   if (keyCode == e.VK_ENTER)
                   executeSQL();
         private DefaultMutableTreeNode dbNode;
         private DefaultTreeModel dbTreeModel;
         private JTree dbTree;
         private JScrollPane tablePane,
                             treePane;
      private JTextArea command = new JTextArea(2,1); // Input area for SQL
      private JTextArea status = new JTextArea(3,1); 
      private String stringIn,query,user, driver,url;
      private String password;
      private int len;
      private PasswordChooser dlgPanel;
      private User u;
      JMenuBar menuBar = new JMenuBar();
      JMenuItem connectItem = new JMenuItem("Connect");
      JMenuItem clearQueryItem = new JMenuItem("Clear query");
      JMenuItem exitItem = new JMenuItem("Exit");
      Connection connection;
      Statement statement;                        
      ResultsModel tableModel;
       A password chooser that is shown inside a dialog
    class PasswordChooser extends JPanel
       public PasswordChooser()
              // panel conaining the panel holding the JLabels
              //and the panel holding the JComboBoxes
              panel = new JPanel();
              panel.setLayout(new BorderLayout());
              //panel for textfields
              tfPanel = new JPanel();
              tfPanel.setLayout(new GridLayout(4,1,5,5));
              tfPanel.add(new JLabel("Driver:"));
              tfPanel.add(new JLabel("URL"));
              tfPanel.add(new JLabel("User name:"));
              tfPanel.add(new JLabel("Password:"));
              panel.add(tfPanel,BorderLayout.WEST);
              //panel for comboboxes
              cbPanel = new JPanel();
              cbPanel.setLayout(new GridLayout(4,1,5,5));
              //drivers
              String[] driverChoices ={"sun.jdbc.odbc.JdbcOdbcDriver","other"};
              driverFields =new JComboBox(driverChoices);
              driverFields.setEditable(true);
              cbPanel.add(driverFields);
              //urls
              String[] urlChoices = {"jdbc:odbc:technical_library", "other"};
              urlFields = new JComboBox(urlChoices);
              urlFields.setEditable(true);
              cbPanel.add(urlFields);
              //user and password
              cbPanel.add(userName = new JTextField(""));
              cbPanel.add(password = new JTextField(""));
              panel.add(cbPanel, BorderLayout.CENTER);
              // create Ok and Cancel buttons that terminate the dialog
              JButton okButton = new JButton("Ok");
              okButton.addActionListener(new
                   ActionListener()
                        public void actionPerformed(ActionEvent event)
                              ok = true;
                              dialog.setVisible(false);
          JButton cancelButton = new JButton("Cancel");
          cancelButton.addActionListener(new
                    ActionListener()
                        public void actionPerformed(ActionEvent event)
                         dialog.setVisible(false);
          // add buttons to southern border
          buttonPanel = new JPanel();
          buttonPanel.add(okButton);
          buttonPanel.add(cancelButton);
          panel.add(buttonPanel, BorderLayout.SOUTH);
          this.add(panel);
       public User getUser()
          return new User((String)driverFields.getSelectedItem(),
                    (String)urlFields.getSelectedItem(),
                    userName.getText(),
                    password.getText());
          Show the chooser panel in a dialog
          @param parent a component in the owner frame or null
          @param title the dialog window title
       public boolean showDialog(Component parent, String title)
          ok = false;
          // locate the owner frame
          Frame owner = null;
          if (parent instanceof Frame)
             owner = (Frame) parent;
          else
             owner = (Frame)SwingUtilities.getAncestorOfClass(
                Frame.class, parent);
          // if first time, or if owner has changed, make new dialog
          if (dialog == null || dialog.getOwner() != owner)
             owner = null;
             dialog = new JDialog(owner, true);
             dialog.getContentPane().add(this);
             dialog.pack();
          // set title and show dialog
          dialog.setTitle(title);
          dialog.setVisible(true);
          return ok;
       private JTextField userName,password;
       private JComboBox driverFields,urlFields;
       private boolean ok;
       private JDialog dialog;
       private JPanel panel,tfPanel,cbPanel, buttonPanel;
       A user has a driver, url, name and password.
    class User
       public User(String aDriver, String aURL, String aUser, String aPassword)
                 driver =aDriver;
                 URL =aURL;
          user = aUser;
          password = aPassword;
       public String getDriver() {return driver;}
       public String getURL() {return URL;}
       public String getUser() { return user; }
       public String getPassword() { return password; }
       private String user,URL,driver;
       private String password;
    ResultsModel takes a resultset and draws a table
    class ResultsModel extends AbstractTableModel
      String[] columnNames = new String[0];
      Vector dataRows;              // Empty vector of rows
      public void setResultSet(ResultSet results)
        try
          ResultSetMetaData metadata = results.getMetaData();
          int columns =  metadata.getColumnCount();    // Get number of columns
          columnNames = new String[columns];           // Array to hold names
          // Get the column names
          for(int i = 0; i < columns; i++)
            columnNames[i] = metadata.getColumnLabel(i+1);
          // Get all rows.
          dataRows = new Vector();                  // New Vector to store the data
          String[] rowData;                         // Stores one row
          while(results.next())                     // For each row...
            rowData = new String[columns];          // create array to hold the data
            for(int i = 0; i < columns; i++)        // For each column
               rowData[i] = results.getString(i+1); // retrieve the data item
            dataRows.addElement(rowData);           // Store the row in the vector
          fireTableChanged(null);           // Signal the table there is new model data
        catch (SQLException sqle)
          System.err.println(sqle);
      public int getColumnCount()
        return columnNames.length;
      public int getRowCount()
        if(dataRows == null)
          return 0;
        else
          return dataRows.size();
      public Object getValueAt(int row, int column)
        return ((String[])(dataRows.elementAt(row)))[column];
      public String getColumnName(int column)
        return columnNames[column] == null ? "No Name" : columnNames[column];
    }

    I posted the code before clearly restating my question.
    I have two JOptionPanes, noted in the code with comments, which appear on closing the program. The first one is in response to a widow event, the second in response to a File>>Exit event. The code for both is identical, but the first one does not function properly when "Cancel" or No" is pressed. Instead of the dialog diasappearing, the program window disappears, but the program does not exit.I'm not sure quite how to implement DO_NOTHING_ON_CLOSE to solove this, as was suggested.
    BTW, the formatting is giving me troubles, despite my efforts to use only necessary tabs and remove comments. I reposted in order to make my listing more readable, but don't think I succeeded.

  • Changing background in a JOptionPane

    This is probably very simple, but I'm having some trouble. I simply want to change the background of the message in my JOptionPane dialog box (and also change the font of the message, but I think I figured that one out). Here's the code....
    JLabel label1 = new JLabel("the first part of message");
    JLabel label2 = new JLabel("the second part of the message");
    label1.setFont(Utils.courierBold12);
    label2.setFont(Utils.courierBold12);
    JPanel panel = new JPanel();
    panel.setBackground(Color.white);
    panel.setLayout(new BorderLayout());
    panel.add(label1, BorderLayout.NORTH);
    panel.add(label2, BorderLayout.CENTER);
    JOptionPane pane = new JOptionPane(panel,JOptionPane.WARNING_MESSAGE);
    pane.setBackground(Color.white);
    // pane.setOpaque(true);
    JDialog dialog = pane.createDialog(this, "Error Message");
    dialog.setBackground(Color.white);
    dialog.show();
    first I tried to set the pane.setOpaque(false) but that left only the panel background white (the rest is that boring gray color). When I set the pane.setOpaque(true) the panel background is white as well as the top and bottom of the dialog box, but not the Icon or the container the has the ok button in it. How can I set the entire dialog box background to white??? Thanks for any and all help....

    Please provide more information about what you are trying to do.

  • JTable Trouble

    I have trouble with the following code. This method could place the data it receives in information onto a JTable but it does not work. The code compiles perfect and the values that information has are correct. I have commented the lines where the data is actually put onto the table. Its about two thirds way down. I would appreciate any help.
    Thanks
    Michael
    public void place_info_table(String information[][])
    if(!(information.length > 1))
    JOptionPane.showMessageDialog(this,"Sorry, there is no server at present to satisfy your request. ","Peer 2 Peer Client",JOptionPane.ERROR_MESSAGE);
    client_open.setEnabled(false);
    client_refresh.setEnabled(false); //all buttons except refresh are disabled.
    client_search.setEnabled(false);
    client_view_files.setEnabled(false);
    client_quit.setEnabled(true);
    else
    client_open.setEnabled(true);
    client_refresh.setEnabled(true);
    client_search.setEnabled(true);
    client_view_files.setEnabled(false); //else all the buttons except view files are enabled
    client_quit.setEnabled(true);
    int j=0;
    for(int i=0;i<information.length;i++) // Here is where the info is added
    client_listing.setValueAt(information[0],j,0);
    j++;
    client_quit.setEnabled(true);
    client_refresh.setEnabled(true);
    System.out.println(information[i][0]);
    client_open.addActionListener(this);
    client_refresh.addActionListener(this);
    client_search.addActionListener(this);
    client_view_files.addActionListener(this);
    client_quit.addActionListener(this);

    I have trouble with the following code. This method could place the data it receives in information onto a JTable but it does not work. The code compiles perfect and the values that information has are correct. I have commented the lines where the data is actually put onto the table. Its about two thirds way down. I would appreciate any help.
    Thanks
    Michael
    public void place_info_table(String information[][])
    if(!(information.length > 1))
    JOptionPane.showMessageDialog(this,"Sorry, there is no server at present to satisfy your request. ","Peer 2 Peer Client",JOptionPane.ERROR_MESSAGE);
    client_open.setEnabled(false);
    client_refresh.setEnabled(false); //all buttons except refresh are disabled.
    client_search.setEnabled(false);
    client_view_files.setEnabled(false);
    client_quit.setEnabled(true);
    else
    client_open.setEnabled(true);
    client_refresh.setEnabled(true);
    client_search.setEnabled(true);
    client_view_files.setEnabled(false); //else all the buttons except view files are enabled
    client_quit.setEnabled(true);
    int j=0;
    for(int i=0;i<information.length;i++) // Here is where the info is added
    client_listing.setValueAt(information[0],j,0);
    j++;
    client_quit.setEnabled(true);
    client_refresh.setEnabled(true);
    System.out.println(information[i][0]);
    client_open.addActionListener(this);
    client_refresh.addActionListener(this);
    client_search.addActionListener(this);
    client_view_files.addActionListener(this);
    client_quit.addActionListener(this);

  • Array Trouble

    So I am new to Java, and took my first semester of a java course. It was hard for me at first, but I am slowly improving. My professor posted this as our last assignment for the semester, and I am having trouble with it as it involves arrays. I do not really know where to start, and any help would be greatly appreciated. I will post the assignment below, followed by the small bit of code I have so far. By no means do I want the answers to this, as I actually do enjoy learning, but any type of help, input, suggestions, etc are greatly appreciated. Thanks in advance!
    Write a program which prompts the user to input a series of characters, one at a time. The program will stop prompting the user for characters once the user enters an exclamation point ('!').
    Using an array, count the number of occurrences of each letter (regardless of whether it is upper or lower case (so for example, an 'A' and an 'a' both count for the first letter of the alphabet). In a separate counter, also count the total number of "other" characters ('.', '?', ' ', '2', etc.). The final exclamation point does not count.
    Print out the count for each letter found (but not for those which where not found!)
    Print the count of the non-letter characters.
    List the characters that were not found (e.g. "The following letters were not found: t, z, c.").
    By inspecting the array, print out the total number of all of the vowels, and the total number of all of the consonants.
    Finally, print out which letter was found the most times. (Note there may be more than one letter which has the maximum count attached to it.) Also, print out which letter (or letters) was found the least number of times, but make certain to exclude letters which were not found at all.
    This is the small amount of code I have thus far.
    import javax.swing.JOptionPane;
    public class asgn6 {
       public static void main( String[] args )
          int character;
           String letter = JOptionPane.showInputDialog("Please enter a letter (Type ! when finished) ");
           character = Integer.parseInt (letter);
         if(letter.equals("!"))
         System.exit(0);
    }

    derajfast wrote:
    char letter;
    do {
    String input = JOptionPane.showInputDialog("Please enter a letter (Type ! when finished) ");
    letter= input.charAt(0);
    }while (letter != '!');So I figured out the loop!Exellent, that's exactly right.
    Now I need a lot of assistance for the arrays part, as that is what I understand least with this assignment.The easiest way I see it is to make an array of ints 128 elements long. Each element is the counter for the character that indexes it.
    For instance, 'A' is ASCII 65. So array[65] is the counter for how many times 'A' has been seen. You can use chars like you would use ints, so you can do this: array['A'] and it will convert it to it's ASCII value. Each time you read an input char, increment array[letter].
    Then when you're done with input, you can print out each one like this
    for each element i in the array
       print out (char)i followed by array                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Trouble updating variables

    Hi guys,
    This is proabably a really easy answer that i'm missing, but I've been staring at this code for several hours now, and am not making much progress. It is suppossed to be a simple game of craps. I am having trouble getting the variable amount to update. Here are the bits of the code dealing with amount. Please let me know if you need anything else.
    Also, I know the code is really messy, I just started learning java, and am still trying to wrap my head around the basics. Any suggestions you have would be appreciated.
    public void begin(String name, int amount, final int GOAL){//start begin method
         getBet(amount); //calls the method to get the player's bet
         playGame(bet, amount);
         dispMessage(win, bet, amount, name);
         System.exit(1);
    } // end begin method
    public void getBet(int amount){//start getBet
        JOptionPane.showMessageDialog(null,"You currently have "+amount+
        " dollars.  Your goal is 300 dollars.", "Current Money", JOptionPane.INFORMATION_MESSAGE);//tells player current amount of money and the goal they are trying to reach
              String input = JOptionPane.showInputDialog (null,        //prompts for the amount of the bet
           "Please enter the amound you wish to bet",
           "Place Bet", JOptionPane.QUESTION_MESSAGE);
            bet = Integer.parseInt(input);
         if(bet>amount) //error checks the bet amount
         JOptionPane.showMessageDialog(null, "You do not have enough money to place that bet. Please enter another amount.",
         "Error Message", JOptionPane.ERROR_MESSAGE);
         getBet(amount);
    else
         return;     
         }//end method getBet
    private void dispMessage(boolean win, int bet, int amount, String name) {
         if (win == true){          
             winBet(bet, amount);
              JOptionPane.showMessageDialog(null, ""+name+" you won "+bet+
              " dollars. You now have "+(amount)+ " dollars.   To play again, press enter", "Winner", JOptionPane.INFORMATION_MESSAGE);
              playGame(bet, amount);
         else
              if((win == false)&&(amount>=0)){
             loseBet(bet, amount);
              JOptionPane.showMessageDialog(null, "You lost the game. You now have "+amount+
              ". To play again, press enter.", "Loser", JOptionPane.INFORMATION_MESSAGE);
              playGame(bet, amount);
         else
         JOptionPane.showMessageDialog(null, "You are out of money", "Loser", JOptionPane.INFORMATION_MESSAGE);
         playGame(bet, amount);
         }//end dispMessage method
         public int winBet(int bet, int amount){//start winBet method
                   amount = amount +bet;
                   return amount;
                   }//end winBet method
         public int loseBet(int bet, int amount){//start loseBet method
                   amount = amount-bet;
                   return amount;
                        }//end loseBet method
         class DicePlayer{// DicePlayer class
        String name = JOptionPane.showInputDialog (null,//prompts for the amount of the bet
           "Please enter your name",
           "Enter Name", JOptionPane.QUESTION_MESSAGE);
        int amount = 100;//player starts with 100 dollars
        final int GOAL = 300;  //player needs to reach 300 dollars          
    } //end of DicePlayer class
    [\code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    And to help you one step further (feeling generous), make your
    winBet method like this:
    private int winBet(int bet, int amount){
        return amount + bet;
    }then the call the jfbriere gave you will work.
    amount = winBet(bet, amount);
    But maybe you figured all this out already?

  • JOptionPane Confusion!

    Hi,
    Im having a real difficult time with JOptionPanes! Im still a newbie to Swing and I just cant seem to get my head around how to make the JOptionPanes do what you want them to! I've read the tutorials and manuals but im still stuck.
    Basically, I have a JButton that brings up a JOptionPane. In this, the user types in the name of a camera. This is then added to a combobox (cameralist).
    cameralist.addItem((JOptionPane.showInputDialog("Enter Camera Name")));
    The problem is, how do I get the JOptionPane to close without doing anything else? Where do I add the code? At the moment it still adds the user's entry when you select cancel or the x in the top right hand corner.
    Thanks for any help and Im sorry if I seem abit stupid!
    Rach

    First, trying to write a complex statement like that on a single line is bound to get you in trouble. Split the code up into several lines to make it readable, understandable and much easier to debug.
    The showInputDialog will return null if the user cancels the dialog (I suppose). You should write something like this:
    String result = JOptionPane.showInputDialog("Enter Camera Name");
    if( result != null && !result.equals("") )
      cameralist.addItem( result );
    }

  • JOptionPane hangs console app

    I'm having some trouble with JOptionPane. Yesterday I posted about this, but the post disappeared.
    On Win2000, j2sdk 1.4.2-b28, the following program never ends:
    import javax.swing.*;
    class test1
         public static void main(String[] args)
              int result = JOptionPane.showConfirmDialog(null, "choose one", "choose one", JOptionPane.YES_NO_OPTION);
              System.out.println("Result of button push = " + result);
              return;
    The dialog disappears and it prints the results of the button push, but the program never exits.
    I tried to put the JOptionPane on the event thread
    import javax.swing.*;
    class test
         public static void main(String[] args)
              //Schedule a job for the event-dispatching thread:
              //creating and showing this application's GUI.
              javax.swing.SwingUtilities.invokeLater(new Runnable()
                   public void run() { createAndShowGUI(); }
         public static void createAndShowGUI()
              int result = JOptionPane.showConfirmDialog(null, "choose one", "choose one", JOptionPane.YES_NO_OPTION);
              System.out.println("Result of button push = " + result);
              return;
    but this shows the same behaviour.
    I'm having related problems when invoking JOptionPane in Jython: there the dialog never appears.
    Thanks for any help!
    Gerry

    import javax.swing.*;
    class test
    public static void main(String[] args)
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable()
    public void run() { createAndShowGUI(); }
    public static void createAndShowGUI()
    int result = JOptionPane.showConfirmDialog(null, "choose one", "choose one", JOptionPane.YES_NO_OPTION);
    System.out.println("Result of button push = " + result);
    if(result == JOptionPane.YES_OPTION)
              System.exit(0);
    return;
    }

  • JOptionPane keeps popping up behind windows

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

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

  • JOptionPane and Threads

    I have a Class called Execute which runs as a thread. If this fails, then I want to show a JOptionPane from the main thread saying it failed (this works), but also I want to create a JOptionPane within the run() method of Execute stating the reason for the failure.
    I can not put a JOptionPane directly inside the run method 'cos it doesn't get rendered correctly, so I run this in it own thread. Only trouble is that now I have two modal dialog boxes appearing simultaneously; what I want is to have them appear consecutively. I have tried to join the thread that creates the pop-up but then it does not get rendered. Any ideas? I have posted an extract of the code below for testing
    public class Execute implements Runnable {
         File success = new File ("/ukirtdata/orac_data/deferred/.success");
         File failure = new File ("/ukirtdata/orac_data/deferred/.failure");
         success.delete();
         failure.delete();
         try {
             success.createNewFile();
             failure.createNewFile();
         catch (IOException ioe) {
             logger.error("Unable to create success/fail file", ioe);
             return;
         SpItem itemToExecute;
         if (!isDeferred) {
             itemToExecute = ProgramTree.selectedItem;
             logger.info("Executing observation from Program List");
         else {
             itemToExecute = DeferredProgramList.currentItem;
             logger.info("Executing observation from deferred list");
         SpItem inst = (SpItem) SpTreeMan.findInstrument(itemToExecute);
         if (inst == null) {
             logger.error("No instrument found");
             success.delete();
             return;
         String tname = QtTools.translate(itemToExecute, inst.type().getReadable());
         // Catch null sequence names - probably means translation
         // failed:
         if (tname == null) {
             //new ErrorBox ("Translation failed. Please report this!");
             logger.error("Translation failed. Please report this!");
             new PopUp ("Translation Error",
                     "An error occurred during translation",
                     JOptionPane.ERROR_MESSAGE).start();
             success.delete();
             return;
         else{
             logger.info("Trans OK");
             logger.debug("Translated file is "+tname);
                failure.delete()
                return;
        public class PopUp extends Thread implements Serializable{
         String _message;
         String _title;
            int    _errLevel;
         public PopUp (String title, String message, int errorLevel) {
             _message=message;
             _title = title;
             _errLevel=errorLevel;
         public void run() {
             JOptionPane.showMessageDialog(null,
                               _message,
                               _title,
                               _errLevel);

    Comeon,
    Someone must have some idea. I have tried making popup extend JOptionPane and implement Runnable, added a window listener which sets a boolean popDisplayed on windowOpen and windowClose, but this gets me nowhere (I have a Thread.sleep in the code as well)

  • JOptionPane in Synchronised Method

    Hi,
    I'm having a bit of trouble using JOptionPane in a synchronised method. The GUI maintains a list of allowed and blocked sites.
    Many threads access these lists to check if an access to a site should be allowed or not. If the new access does not match an entry in either list then a JOptionPane is displayed to ask the user for the action to take.
    The lists need to be synchronised so the GUI class looks like this:
    public class Console extends JFrame{
         private JTextArea allowedHosts;     
         private JTextArea blockedHosts;
         public Console()
         {...creates and displays GUI...     }
         public synchronized boolean isRequestAllowed(Request request)
         { ...//code to check if the request is in allowed or blocked list
              else
    //Pop up a JDialog to ask the user for the next action to take
              return promptForAction(request);     
         private boolean promptForAction(Request request)
              ...//creates options for JOptionPane          
              try
                   SwingUtilities.invokeAndWait( new Runnable() {
         public void run()
         actionCode[0] = JOptionPane.showOptionDialog(frame, message, "Access Attempt",
                             JOptionPane.DEFAULT_OPTION,
                             JOptionPane.QUESTION_MESSAGE,
                             null, options, options[0]);
              catch (InterruptedException ignore){}
              catch (InvocationTargetException ignore) {}     
    ...//checks actionCode[0] to specify next action
    The need for synchronisation is that I don't want one thread checking the allowed or blocked lists while the user is being prompted for input about a previous request.
    The JOptionPane works fine for first request and will return. A second request is then attempted and the JOptionPane displays but will not respond to any inputs or clicks on buttons.
    My experience of Java is very limited and I might be making alot of mistakes but I have read the tutorials on the java website and any other related sites.
    Any help would be much appreciated,
    Mark

    moc02 wrote:
    The class doesn't really need to extend JFrame. Just the way I done it. I'll change it round and see if that sorts it.Even if it doesn't, it's almost always better to avoid inheritance unless it is necessary. In other words, I agree with Darryl: don't extend JFrame.
    On the other point, I'm not really sure what you are talking about, showing my lack of knowledge there. I don't know what you mean by separating model from view so if you could explain a little more I'd really appreciate it. The model is the data and the non-GUI code necessary to manipulate the data. The view is the graphical representation of it.
    I have to wonder if you may be trying to bite more than you can chew here.

Maybe you are looking for

  • How can I include a jsf page?

    I need to include a jsp page that contains jsf code, I try with: <c:import url="faces/include.jsp" var="prova" /> but the server response: javax.servlet.ServletException: Cannot find FacesContext There something that is wrong? Thank's Teo

  • Aperture 3.0.2 Time Machine Backup Question

    So I recently imported my entire iPhoto Library into aperture and chose to have everything in the Aperture Library not referencing from the iPhoto Library. Either way everything went great and I'm loving it. My question has to do with when I recently

  • Run C program compiled for Linux on Mac x11?

    Hi, Is it possible to run a c-code program compiled for Linux on x11? If this is not possible, is there a way to have a linux platform runninn os 10.6.8 so I can use these programs? I knew little about Linux or X11, so I don't know if it is possible

  • Re:Role of an Abaper in support projects

    Hi, What can be the role of an abaper in support projects and moreover what is production support and development support.How do we handle issues in production supoort i.e., we directly login to the production server and solve or we copy the code in

  • Adobe XI processes left open with no threads to a valid process

    Processes are being left open after attempts to generate PDF's. The system is using the latest update for Acrobat XI.  This was not an issue with this version before about February, January for sure. Windows 7 Professional 16G memory XEON processor D