Optionpane help!!

hi, i need some help with the optionpane component in java gui, in the option pane i need to list the strings in the array called test ( i have labelled the place where they need to go as the word "something"), can anyone assist?
try {
      // Create a FileReader and then wrap it with BufferedReader.
      FileReader file_reader = new FileReader (file);
      BufferedReader buf_reader = new BufferedReader (file_reader);
      do {
         String line = buf_reader.readLine ();
         if (line == null) break;
      if(line.startsWith("busl")){String[] test = line.split(" ");
      //System.out.println(test);
      } while(true);
      Object response = JOptionPane.showInputDialog(null,
            "Select a bus line",
            "Bus line", JOptionPane.QUESTION_MESSAGE,
            null, new String[] { "something", "something",
                "something", "something", "something" },
            "something");
       catch (IOException e) {
        System.out.println ("IO exception =" + e );
       }

    public TestOptionpane() {
        String[] test = null;
        try {
            // Create a FileReader and then wrap it with BufferedReader.
            FileReader file_reader = new FileReader(file);
            BufferedReader buf_reader = new BufferedReader(file_reader);
            do {
                String line = buf_reader.readLine();
                if (line == null) break;
                if(line.startsWith("busl")){test = line.split(" ");
            } while(true);
            Object response = JOptionPane.showInputDialog(null,
                    "Select a bus line",
                    "Bus line", JOptionPane.QUESTION_MESSAGE,
                    null, test, test[0]);
            System.out.println(response);
        catch (IOException e) {
            System.out.println("IO exception =" + e );
    }

Similar Messages

  • Gui optionpane help!!

    hi, i need some help with the optionpane component in java gui, in the option pane i need to list the strings in the array called test ( i have labelled the place where they need to go as the word "something"), can anyone assist?
    try {
          // Create a FileReader and then wrap it with BufferedReader.
          FileReader file_reader = new FileReader (file);
          BufferedReader buf_reader = new BufferedReader (file_reader);
          do {
             String line = buf_reader.readLine ();
             if (line == null) break;
          if(line.startsWith("busl")){String[] test = line.split(" ");
          //System.out.println(test);
          } while(true);
          Object response = JOptionPane.showInputDialog(null,
                "Select a bus line",
                "Bus line", JOptionPane.QUESTION_MESSAGE,
                null, new String[] { "something", "something",
                    "something", "something", "something" },
                "something");
           catch (IOException e) {
            System.out.println ("IO exception =" + e );
           }

    Swing forum: http://forum.java.sun.com/forum.jspa?forumID=57

  • Help Needed with showMessageDialog in awt

    Yes! I'm back with another problem. I'm trying to use showMessageDialog for my about popup. But, all the examples I have looked at use with Swing. I did see in the tutorials that this could work in java.awt.dialog. But, that doesn't seem to be in the docs, though. Anyway, below is my attempt at inserting showMessageDialog in my code. I'm receiving 2 compile errors on the line of code. Can anyone tell me where I have gone wrong?
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    class ChatClient extends Frame
       private TextField tf1 = new TextField("", 50);
        private TextArea ta;
        private Button sendButton;
        private Button quitButton;
        private Button okButton;
        private MenuItem exitMT, aboutMT;
        private Choice choice;
        private String user;
       public ChatClient()
           super("ChatClient");
          addWindowListener(new WindowAdapter()
          {public void windowClosing(WindowEvent e) {System.exit(0); }});
            addWindowListener(new WindowAdapter()
          {public void windowActivated(WindowEvent e)
                    tf1.requestFocusInWindow();
         setTitle("Chat Room");
          Panel p = new Panel(new BorderLayout());
          Panel p1 = new Panel(new BorderLayout());
          Panel p2 = new Panel(new GridLayout(3,1));
          MenuBar mb = new MenuBar ();
          setMenuBar (mb);
          Menu fileMenu = new Menu ("File");
         mb.add(fileMenu);
        Menu helpMenu = new Menu ("Help");
          mb.add(helpMenu);
          fileMenu.add (exitMT= new MenuItem ("Quit"));
         helpMenu.add (aboutMT = new MenuItem ("About"));
         exitMT.addActionListener(new ExitCommand());
          aboutMT.addActionListener(new AboutCommand());
       //creating main panel
       add(p, BorderLayout.NORTH);
          ta = new TextArea(10, 50);
          add(ta, BorderLayout.CENTER);
          ta.setSize(500,300);
          ta.setEditable(false);
        //adding buttons  and choice box to the right side of the window
          sendButton = new Button("Send");
          Panel p3 = new Panel();
          sendButton.setSize(15,15);
          sendButton.setBackground(Color.green);
          p3.add(sendButton);
          p2.add(p3);
         sendButton.addActionListener(new CopyCommand());
        quitButton = new Button("Quit");
         Panel p4 = new Panel();
        quitButton.setSize(15,15);
         quitButton.setBackground(Color.red);
         p4.add(quitButton);
         p2.add(p4);
        quitButton.addActionListener(new ExitCommand());
         Panel p5 = new Panel();
        choice = new Choice();
        choice.addItem("John");
        choice.addItem("Jena");
        choice.addItem("Colleen");
        choice.addItem("Steve");
        user=choice.getItem(0);
        p5.add(choice);
        choice.addItemListener(new CopyCommand());
        p2.add(p5);
         add(p2, BorderLayout.EAST);
       //adding the textfield to the south end of the window
          p1.add(tf1);
          add(p1, BorderLayout.SOUTH);
          tf1.addActionListener(new CopyCommand());
    //handling ActionEvent from buttons and menu items
      class ExitCommand implements ActionListener
        public void actionPerformed (ActionEvent e)
                   tf1.setText("");
                  ta.setText("");
                  choice.select(0);
                  System.exit(0);
      class AboutCommand implements ActionListener
         public void actionPerformed (ActionEvent e)
             OptionPane.showMessageDialog(OptionDialogFrame.this, "ChatClient ver. 1.0 written by Jennifer McAuliffe", "About Screen");
             System.out.print("About menu was pressed!");
      class CopyCommand implements ActionListener, ItemListener
        public void itemStateChanged(ItemEvent e)
        {  if (e.getSource() instanceof Choice)
            user = (String)e.getItem();
        public void actionPerformed (ActionEvent e)
            ta.append(user + ": " + tf1.getText() + "\n");
              tf1.setText("");
                tf1.requestFocus();
         public void keyPressed (KeyEvent ke)
             //figure out if the enter key was pressed
             if (ke.getKeyCode() == KeyEvent.VK_ENTER)
         ta.append(user + ": " + tf1.getText() + "\n");
         tf1.setText("");
         tf1.requestFocus();
         public void keyTyped (KeyEvent ke) { }
         public void keyReleased (KeyEvent ke) { }
       public static void main(String[] args)
       {  Frame f = new ChatClient();
          f.setSize(600, 400);
          f.show();
    }

    they aren't really stupid questions, you need to rely on the api to know exactly what classes you are using and the methods available. here is a really crude example that might give you some ideas. it could use lots of improvements.
    import java.awt.*;
    import java.awt.event.*;
    class DialogExample extends Frame
         public static void main(String[] args)
              Frame f = new Frame();
              //f.setVisible(true);
              Dialog d = new Dialog(f,"About Screen", true);
              d.add(new Label("ChatClient ver. 1.0 written by Jennifer McAuliffe"));
              d.addWindowListener(new WindowAdapter(){
                   public void windowClosing(WindowEvent we) {
                           ((Dialog)(we.getSource())).setVisible(false);
              d.pack();
              d.setLocationRelativeTo(null);
              d.setVisible(true);
              d.dispose();
              System.exit(0);
    }

  • Help with an If Statement for a Message Dialog

    Hello all! I need help yet once again! I would prefer hints and nudges rather then the answer please, as this is for a homework assignment. Okay I am supposed to write a program that has 3 text boxes to enter a number between 0 and 255 (for red green and blue) and then the user should push the show button and the background color should change, which I have all working! But I am supposed to have a " gracefully handle the situation where the user enters an invalid color value (any number less than zero or greater than 255)" and I have the if statement written, but for some reason, whenever I hit the show button it always pops up that window, no matter what the user types in. So I need help figuring out how to make it stop popping up all of the time! Here is the code: Any other ideas on how to make the code better would be much appreciated!!! Thanks in advance!
    import java.awt.GridLayout;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JTextField;
    import javax.swing.JPanel;
    import javax.swing.BorderFactory;
    public class ColorEditor extends JPanel {
         private JLabel labelRed;
         private JLabel labelGreen;
         private JLabel labelBlue;
         private JTextField textFieldRed;
         private JTextField textFieldGreen;
         private JTextField textFieldBlue;
         private JButton showButton;
         private JButton exitButton;
         private JOptionPane optionPane;
         public ColorEditor()
              super(new BorderLayout());
              labelRed = new JLabel("red: ");
              textFieldRed = new JTextField(5);
              labelGreen = new JLabel("green: ");
              textFieldGreen = new JTextField(5);
              labelBlue = new JLabel("blue: ");
              textFieldBlue = new JTextField(5);
              showButton = new JButton("show");
              exitButton = new JButton("exit");
              JPanel labelPane = new JPanel(new GridLayout(0,1));
              labelPane.add(labelRed);
              labelPane.add(labelGreen);
              labelPane.add(labelBlue);
              labelPane.add(showButton);
              JPanel fieldPane = new JPanel( new GridLayout(0,1));
              fieldPane.add(textFieldRed);
              fieldPane.add(textFieldGreen);
              fieldPane.add(textFieldBlue);
              fieldPane.add(exitButton);
              setBorder(BorderFactory.createEmptyBorder(40,40,40,40));
              add(labelPane, BorderLayout.LINE_START);
              add(fieldPane, BorderLayout.CENTER);
              TextFieldHandler handler = new TextFieldHandler();
              textFieldRed.addActionListener(handler);
              textFieldGreen.addActionListener(handler);
              textFieldBlue.addActionListener(handler);
              showButton.addActionListener(handler);
         private class TextFieldHandler implements ActionListener
              public void actionPerformed(ActionEvent event)
                   if (event.getSource() == showButton)
                        String textRed = textFieldRed.getText();
                        String textGreen = textFieldGreen.getText();
                        String textBlue = textFieldBlue.getText();
                        int a = Integer.parseInt(textRed);
                        int b = Integer.parseInt(textGreen);
                        int c = Integer.parseInt(textBlue);
                        if ((a < 0) || (a > 255)||(b<0)||(b>255)||(c<0)||(c>255));
                             optionPane.showMessageDialog(null, "Please enter a number between 0 and 255!");//HERE IS WHERE I NEED THE HELP!!
                        Color colorObject = new Color(a,b,c);
                        setBackground(colorObject);
         public static void main(String args[])
              JFrame frame = new JFrame("Color Editor");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
              frame.add(new ColorEditor());
              frame.pack();
              frame.setVisible(true);
    }

    Okay now Eclipse is giving me a really funky error that I cannot quite figure out (in the compiler) but my program is running fine.... Can you help me with this too?
    Here is what the compiler is giving me....
    Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Color parameter outside of expected range: Green
    +     at java.awt.Color.testColorValueRange(Unknown Source)+
    +     at java.awt.Color.<init>(Unknown Source)+
    +     at java.awt.Color.<init>(Unknown Source)+
    +     at ColorEditor$TextFieldHandler.actionPerformed(ColorEditor.java:80)+
    +     at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)+
    +     at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)+
    +     at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)+
    +     at javax.swing.DefaultButtonModel.setPressed(Unknown Source)+
    +     at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)+
    +     at java.awt.Component.processMouseEvent(Unknown Source)+
    +     at javax.swing.JComponent.processMouseEvent(Unknown Source)+
    +     at java.awt.Component.processEvent(Unknown Source)+
    +     at java.awt.Container.processEvent(Unknown Source)+
    +     at java.awt.Component.dispatchEventImpl(Unknown Source)+
    +     at java.awt.Container.dispatchEventImpl(Unknown Source)+
    +     at java.awt.Component.dispatchEvent(Unknown Source)+
    +     at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)+
    +     at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)+
    +     at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)+
    +     at java.awt.Container.dispatchEventImpl(Unknown Source)+
    +     at java.awt.Window.dispatchEventImpl(Unknown Source)+
    +     at java.awt.Component.dispatchEvent(Unknown Source)+
    +     at java.awt.EventQueue.dispatchEvent(Unknown Source)+
    +     at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)+
    +     at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)+
    +     at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)+
    +     at java.awt.EventDispatchThread.pumpEvents(Unknown Source)+
    +     at java.awt.EventDispatchThread.pumpEvents(Unknown Source)+
    +     at java.awt.EventDispatchThread.run(Unknown Source)+

  • Help with creating a custom table cell editor?

    hi, i was reading up on various tutorials and trying to write codes that pops up a simple calendar when clicked on text of the Date class in a table, so far, i can't seem to get my classes working.. the following is some classes i've written for this task (note, there are alot of commented out lines, those are the modifications done to the tutorial classes in http://java.sun.com/docs/books/tutorial/)
    any help would be appreciated :D
    thanks in advance!
    What i have done so far:
    /** BASIC TABLE CLASS FOR DEMONSTRATION*/
    //import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    public class TableBasic extends JFrame
         public TableBasic()
              String[] columnNames = { "Date", "String", "Integer", "Boolean" };
              Object[][] data =
                   {  { new Date(), "A", new Integer(1), Boolean.TRUE },
                        {new Date(), "B", new Integer(2), Boolean.FALSE },
                        {new Date(), "C", new Integer(9), Boolean.TRUE },
                        {new Date(), "D", new Integer(4), Boolean.FALSE}
              JTable table = new JTable(data, columnNames)
                   //Returning the Class of each column will allow different
                   //renderers to be used based on Class
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
              table.setDefaultRenderer(Date.class, new CalendarRenderer(true));
              table.setDefaultEditor(Date.class, new CalendarEditor());
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollPane = new JScrollPane(table);
              getContentPane().add(scrollPane);
         public static void main(String[] args)
              TableBasic frame = new TableBasic();
              frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
              frame.pack();
              //frame.setLocationRelativeTo(null);
              frame.setVisible(true);
    * CLASS BASED ON ColorRenderer.java at http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/ColorRenderer.java
    import javax.swing.BorderFactory;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.border.Border;
    import javax.swing.table.TableCellRenderer;
    //import java.awt.Color;
    import java.awt.Component;
    public class CalendarRenderer
         extends JLabel
         implements TableCellRenderer
         Border unselectedBorder = null;
         Border selectedBorder = null;
         boolean isBordered = true;
         public CalendarRenderer(boolean isBordered)
              this.isBordered = isBordered; setOpaque(true);
              //MUST do this for background to show up.
         public Component getTableCellRendererComponent(JTable table,
                                                                     Object color,
                                                                     boolean isSelected,
                                                                     boolean hasFocus,
                                                                     int row,
                                                                     int column)
              String newDate = (String)color;
              setText(newDate);
              if (isBordered)
                   if (isSelected)
                        if (selectedBorder == null)
                             selectedBorder = BorderFactory.createMatteBorder(2,5,2,5, table.getSelectionBackground());
                        setBorder(selectedBorder);
                   else
                        if (unselectedBorder == null)
                             unselectedBorder = BorderFactory.createMatteBorder(2,5,2,5, table.getBackground());
                        setBorder(unselectedBorder);
              //setToolTipText("RGB value: " + newColor.getRed() + ", " + newColor.getGreen() + ", " + newColor.getBlue());
              return this;
    * the editor based on ColorEditor.java at http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/ColorEditor.java
    import javax.swing.AbstractCellEditor;
    import javax.swing.table.TableCellEditor;
    import javax.swing.JButton;
    import javax.swing.JColorChooser;
    import javax.swing.JDialog;
    import javax.swing.JTable;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class ColorEditor
         extends AbstractCellEditor
         implements TableCellEditor, ActionListener
         Color currentColor;
         JButton button;
         JColorChooser colorChooser;
         JDialog dialog;
         protected static final String EDIT = "edit";
         public ColorEditor()
              //Set up the editor (from the table's point of view),
              //which is a button.
              //This button brings up the color chooser dialog,
              //which is the editor from the user's point of view.
              button = new JButton();
              button.setActionCommand(EDIT);
              button.addActionListener(this);
              button.setBorderPainted(false);
              //Set up the dialog that the button brings up.
              colorChooser = new JColorChooser();
              dialog = JColorChooser.createDialog(button,
                   "Pick a Color",
                   true, //modal
                   colorChooser,
                   this, //OK button handler
                   null); //no CANCEL button handler
          * Handles events from the editor button and from
          * the dialog's OK button.
         public void actionPerformed(ActionEvent e)
              if (EDIT.equals(e.getActionCommand()))
                   //The user has clicked the cell, so
                   //bring up the dialog.
                   button.setBackground(currentColor);
                   colorChooser.setColor(currentColor);
                   dialog.setVisible(true); //Make the renderer reappear.
                   fireEditingStopped();
              else
                   //User pressed dialog's "OK" button.
                   currentColor = colorChooser.getColor();
         //Implement the one CellEditor method that AbstractCellEditor doesn't.
         public Object getCellEditorValue()
              return currentColor;
         //Implement the one method defined by TableCellEditor.
         public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
              currentColor = (Color)value; return button;
    /** THE SIMPLE CALENDAR WRITTEN TALIORED TO WORK WITH DIALOGS*/
    import javax.swing.*;
    import java.util.Calendar;
    import java.awt.*;
    import java.awt.event.*;
    import java.text.SimpleDateFormat;
    //import java.beans.*; //property change stuff
    public class CalendarDialog
         extends JDialog
         //implements PropertyChangeListener
         private JButton[] btn = new JButton[49];
         private int month = Calendar.getInstance().get(Calendar.MONTH);
         private int year = Calendar.getInstance().get(Calendar.YEAR);
         private JLabel lbl = new JLabel("", JLabel.CENTER);
         private JOptionPane optionPane;
         private String curDate = null;
         private JTextArea output = new JTextArea(curDate, 1, 20);
         private String btnString1 = "Enter";
         private String btnString2 = "Cancel";
         public CalendarDialog()
              //super(aFrame, true);
              setContentPane(buildGUI());
              setDates();
         public JPanel buildGUI()
              JPanel panel = new JPanel();
              String[] header = { "Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat" };
              JPanel midPanel = new JPanel(new GridLayout(7, 7));
              for (int x = 0; x < btn.length; x++)
                   final int selection = x;
                   btn[x] = new JButton();
                   btn[x].setFocusPainted(false);
                   if (x < 7)
                        JLabel lbl = new JLabel(header[x], JLabel.CENTER);
                        lbl.setFont(new Font("Lucida", Font.PLAIN, 10));
                        midPanel.add(lbl);
                   else
                        btn[x].addActionListener(new ActionListener()
                             public void actionPerformed(ActionEvent ae)
                                  displayDatePicked(btn[selection].getActionCommand());
                        midPanel.add(btn[x]);
              JPanel lowPanel = new JPanel(new GridLayout(1, 3));
              JButton prevBtn = new JButton("<< Previous");
              prevBtn.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent ae)
                        month--;
                        setDates();
              lowPanel.add(prevBtn);
              lowPanel.add(lbl);
              lowPanel.add(output);
              JButton nextBtn = new JButton("Next >>");
              nextBtn.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent ae)
                        month++;
                        setDates();
              lowPanel.add(nextBtn);
              JPanel outputPanel = new JPanel();
              Object[] options = { btnString1, btnString2 };
              optionPane =
                   new JOptionPane(
                        output,
                        JOptionPane.QUESTION_MESSAGE,
                        JOptionPane.YES_NO_OPTION,
                        null,
                        options,
                        options[0]);
              outputPanel.add(optionPane);
              panel.setLayout(new BorderLayout());
              panel.add(lowPanel, BorderLayout.NORTH);
              panel.add(midPanel, BorderLayout.CENTER);
              panel.add(outputPanel, BorderLayout.SOUTH);
              return panel;
         public void setDates()
              for (int x = 7; x < btn.length; x++)
                   btn[x].setText("");
              SimpleDateFormat sdf = new SimpleDateFormat("MMMM yyyy");
              Calendar cal = Calendar.getInstance();
              cal.set(year, month, 1);
              int dayOfWeek = cal.get(java.util.Calendar.DAY_OF_WEEK);
              int daysInMonth = cal.getActualMaximum(java.util.Calendar.DAY_OF_MONTH);
              for (int x = 6 + dayOfWeek, day = 1; day <= daysInMonth; x++, day++)
                   btn[x].setText("" + day);
              lbl.setText(sdf.format(cal.getTime()));
         public void displayDatePicked(String day)
              if (day.equals("") == false)
                   SimpleDateFormat sdf = new SimpleDateFormat("EEEE d MMMM, yyyy");
                   Calendar cal = Calendar.getInstance();
                   cal.set(year, month, Integer.parseInt(day));
                   curDate = sdf.format(cal.getTime());
                   //JOptionPane.showMessageDialog(this, "You picked " + sdf.format(cal.getTime()));
                   output.setText(sdf.format(cal.getTime()));
         public String getDate()
              return curDate;
         public void setDate(String date)
              curDate = date;
    }

    well, i have indeed narrowed down my problem after some digging around.. one thing i discovered that i don't need CalendarRenderer.java.. and i found out i don't really know what does
    //Implement the one method defined by TableCellEditor.
         public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
              curDate = (String)value; return button;
         }do, as it seems to be the problem:
    java.lang.ClassCastException
         at CalendarEditor.getTableCellEditorComponent(CalendarEditor.java:78)
         at javax.swing.JTable.prepareEditor(JTable.java:3786)
         at javax.swing.JTable.editCellAt(JTable.java:2531)
         at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.adjustFocusAndSelection(BasicTableUI.java:510)
         at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.mousePressed(BasicTableUI.java:494)
         at java.awt.AWTEventMulticaster.mousePressed(AWTEventMulticaster.java:222)
         at java.awt.Component.processMouseEvent(Component.java:5097)
         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:3195)
         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)
    mmm.. does anyone know what i should modify for that to work?

  • UIManager.getIcon("OptionPane.warningIcon") on Linux

    Hi,
    I'm using
    Icon icon = UIManager.getIcon("OptionPane.warningIcon");to retrieve default icons and use them in my custom dialogs.
    Everything is OK with JVMs since version 1.4.1 on every OSs (Windows 98, 2K and XP and Mac OS X 10.2 and later) except on Linux where icon is null!
    If I use
    JOptionPane.showMessageDialog(component, text, title, JOptionPane.WARNING_MESSAGE);the icon is displayed in the dialog even on Linux.
    The same behaviour is encountered for the 4 icons (warningIcon, errorIcon, informationIcon and questionIcon).
    How could I get the default icons on Linux?
    Thanks in advance for your help.
    Regards,
    Lara.

    henrique.abreu wrote:
    Legend_Keeper wrote:
    The above is probably the case, and whether it is or isn't the case, the String key you're using is probably not the right String key on the Linux platform you're using. I have no idea what the correct one is. Is there a way you can get the list of keys and print it out?Sure you can. The following code is not mine, I got it searching in this forum (a long time ago)
    import java.util.Enumeration;
    import javax.swing.UIDefaults;
    import javax.swing.UIManager;
    public class ListProperties {
    public static void main(String args[]) throws Exception {
    UIManager.LookAndFeelInfo looks[] = UIManager.getInstalledLookAndFeels();
    for (UIManager.LookAndFeelInfo info : looks) {
    UIManager.setLookAndFeel(info.getClassName());
    UIDefaults defaults = UIManager.getDefaults();
    Enumeration newKeys = defaults.keys();
    while (newKeys.hasMoreElements()) {
    Object obj = newKeys.nextElement();
    System.out.printf("%50s : %s\n", obj, UIManager.get(obj));
    Well, I used something similiar to list all strings and found out there are listed on Linux too but I don't understand your syntax in for (UIManager.LookAndFeelInfo info : looks) nor does my Javac :javac ListProperties.java
    ListProperties.java:10: ';' expected
        for (UIManager.LookAndFeelInfo info : looks) {
                                            ^
    ListProperties.java:21: illegal start of expression
      ^
    2 errorsThank you anyway for your answer...
    Regards,
    Lara.
    Edited by: JolieLara on Oct 9, 2008 1:49 AM

  • Help with "simple" JFileChooser problem...

    Hi all,
    how do I set the font in a JFileChooser???
    I have tried everything, but it always uses the Look & Feels default font setting. Can I change the default Look&Feels font setting?
    Greatfully for any suggestions!
    Cheers
    Anders ;-D

    Hello!
    You can use the UIManager, e.g. UIManager.put("FileChooser.font", new Font("Arial",
    Font.BOLD, 14);
    Well, that didn't seem to help with my case either. So I tried something else: I overrided all of the defaults by using UIManager.put(key, value) this way I got all of the Fonts in the JFileChooser to change.
    Correct me if I'm wrong... ;)
    - Cathra -
    Sample Code that performs the requested:
    // Prepare the resources
    FontUIResource font12Arial = new FontUIResource( "Arial", Font.PLAIN, 12 );
    // Put values into UIDefaults (before initializing the JFileChooser)
    UIManager.put( "ToolTip.font", font12Arial );
    UIManager.put( "OptionPane.messageFont", font12Arial );
    // shown for example
    UIManager.put("FileChooser.openButtonText", "OpenUp");
    UIManager.put("Button.font", font12Arial);
    UIManager.put("Label.font", font12Arial);
    UIManager.put("Table.font", font12Arial);
    UIManager.put("TextField.font", font12Arial);
    UIManager.put("ScrollPane.font", font12Arial);
    UIManager.put("ComboBox.font", font12Arial);
    UIManager.put("CheckBox.font", font12Arial);
    UIManager.put("TitledBorder.font", font12Arial);
    UIManager.put("RadioButton.font", font12Arial);
    UIManager.put("ToolTip.font", font12Arial);
    UIManager.put("TextPane.font", font12Arial);
    UIManager.put("TextArea.font", font12Arial);
    UIManager.put("Tree.font", font12Arial);
    UIManager.put("List.font", font12Arial);
    UIManager.put("MenuBar.font", font12Arial);
    UIManager.put("Menu.font", font12Arial);
    UIManager.put("MenuItem.font", font12Arial);
    UIManager.put("TableHeader.font", font12Arial);
    UIManager.put("TabbedPane.font", font12Arial);
    // somewhere in the code:
    JFileChooser c = new JFileChooser();
    c.showOpenDialog(aParentFrame);

  • Strange GUI freezing TrayIcon + PopupMenu, please help

    Can anybody help me ?
    I wrote very simple program demostrating some GUI activities (changing JPanel background color and tray icon). The problem is that my program freez when I popup tray icon menu (right click) ! :(
    I checked it on Windows XP and 2000 on Java 6.0 b105 and u1 b03.
    I also tryed popup menu manually via .show() from new thread, but it still blocks my program GUI.
    Can you just copy & paste this program, run it and tell me behaviour on your computer ???? Thank you very much.
    Maby somebody know what I am doing wrong and how to use PopupMenu without blocking other GUI operations ???
    //====================================
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class IsTrayIconMenuBlocking3
            public static void main( String[] args ) throws Exception
                    // --- JFrame & JPanel section
                    final JPanel jp = new JPanel();
                    JFrame jf = new JFrame();
                    jf.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
                    jf.add( jp );
                    jf.setSize( 300 , 300 );
                    jf.setVisible( true );
                    // --- menu item action
                    ActionListener itemExitAction = new ActionListener()
                            public void actionPerformed( ActionEvent e )
                                    System.out.println( "item action: exit" );
                                    System.exit( 0 );
                    // --- popup menu
                    PopupMenu pm = new PopupMenu( "Tray Menu" );
                    MenuItem mi = new MenuItem( "Exit" );
                    mi.addActionListener( itemExitAction);
                    pm.add( mi );
                    // --- system tray & tray icon
                    final TrayIcon ti = new
              TrayIcon( ((ImageIcon)UIManager.getIcon("OptionPane.questionIcon")).getImage() ,"Tray Icon" , pm );
                    SystemTray st = SystemTray.getSystemTray();
                    ti.setImageAutoSize( true );
                    st.add( ti );
                    // --- color & icon changing loop
                    final Image[] trayIcons = new Image[3];
                    trayIcons[0] = ((ImageIcon)UIManager.getIcon("OptionPane.errorIcon")).getImage();
                    trayIcons[1] = ((ImageIcon)UIManager.getIcon("OptionPane.warningIcon")).getImage();
                    trayIcons[2] = ((ImageIcon)UIManager.getIcon("OptionPane.informationIcon")).getImage();
                    Runnable colorChanger = new Runnable()
                            private int counter = 0;
                            private int icon_no = 0;
                            public void run()
                                    System.out.println( "Hello from EDT " + counter++ );
                                    if( jp.getBackground() == Color.RED )
                                            jp.setBackground( Color.BLUE );
                                    else
                                            jp.setBackground( Color.RED );
                                    ti.setImage( trayIcons[icon_no++] );
                                    if( icon_no == trayIcons.length ) icon_no = 0;
                    while( true )
                            javax.swing.SwingUtilities.invokeLater( colorChanger);
                            try{Thread.sleep( 500 );} catch ( Exception e ){}
    //==================================== Once again, thanks !!
    Artur Stanek, PL

    Yes. It happens to me too.
    I have tried using SwingWorker but nothing changes.
    It seems to me that PopupMenu blocks the EDT, try
    to put on you test frame a popup, probably when pop-up
    your gui stops to change colors.
    package test;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class IsTrayIconMenuBlocking3
       public static void main(String[] args) throws Exception
          final JPanel jp = new JPanel();
          JFrame jf = new JFrame();
          jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          jf.add(jp);
          jf.setSize(300, 300);
          jf.setVisible(true);
          WorkerTray vTray  = new WorkerTray();
          vTray.execute();
          ColorChanger vColor = new ColorChanger(jp, vTray.get());
          vColor.execute();
    package test;
    import java.awt.Color;
    import java.awt.Image;
    import java.awt.TrayIcon;
    import javax.swing.ImageIcon;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    import javax.swing.SwingWorker;
    import javax.swing.UIManager;
    public class ColorChanger extends SwingWorker<Boolean, Void>
       JPanel      jp;
       TrayIcon    ti;
       private int counter   = 0;
       private int icon_no   = 0;
       Image[]     trayIcons = new Image[3];
       public ColorChanger(JPanel aPanel, TrayIcon anIcon)
          jp = aPanel;
          ti = anIcon;
          trayIcons[0] = ((ImageIcon) UIManager.getIcon("OptionPane.errorIcon"))
                .getImage();
          trayIcons[1] = ((ImageIcon) UIManager
                .getIcon("OptionPane.warningIcon")).getImage();
          trayIcons[2] = ((ImageIcon) UIManager
                .getIcon("OptionPane.informationIcon")).getImage();
       @Override
       protected Boolean doInBackground() throws Exception
          boolean vCicle = true;
          while (vCicle)
             System.out.println("Hello from EDT " + counter++);
             if (jp.getBackground() == Color.RED)
                SwingUtilities.invokeLater(new Runnable()
                   public void run()
                      jp.setBackground(Color.BLUE);
             else
                SwingUtilities.invokeLater(new Runnable()
                   public void run()
                      jp.setBackground(Color.RED);
             ti.setImage(trayIcons[icon_no++]);
             if (icon_no == trayIcons.length)
                icon_no = 0;
             Thread.currentThread().sleep(500);
          return new Boolean(true);
    package test;
    import java.awt.MenuItem;
    import java.awt.PopupMenu;
    import java.awt.SystemTray;
    import java.awt.TrayIcon;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.ImageIcon;
    import javax.swing.SwingWorker;
    import javax.swing.UIManager;
    public class WorkerTray extends SwingWorker<TrayIcon, Void>
       TrayIcon wTray;
       public WorkerTray()
       @Override
       protected TrayIcon doInBackground() throws Exception
          PopupMenu pm = new PopupMenu("Tray Menu");
          MenuItem mi = new MenuItem("Exit");
          // mi.addActionListener(itemExitAction);
          pm.add(mi);
          // --- system tray & tray icon
          wTray = new TrayIcon(((ImageIcon) UIManager
                .getIcon("OptionPane.questionIcon")).getImage(), "Tray Icon", pm);
          mi.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent aE)
                      System.out.println("quiquiquiquqi");
                      System.exit(0);
          SystemTray st = SystemTray.getSystemTray();
          wTray.setImageAutoSize(true);
          st.add(wTray);
          return wTray;
    }

  • Help Button in JOptionPane

    Hi all,
    is there any easy way to provide a (possible locale sensitive) Help Button in JOptionPane Dialogs? Are there any libs that extend the Standard Dialogs to provide such a button?
    Many thanks for your ideas!
    bye
    Marcus

    This guy made his own alternative OptionPane that has such a feature:
    [http://javagraphics.blogspot.com/2008/06/joptionpane-making-alternative.html|http://javagraphics.blogspot.com/2008/06/joptionpane-making-alternative.html]

  • Help for .NoClassDefFoundError

    Hi, everyone:
    When I did my Program I encountered some problems: I downloaded the lastest version of SDK 2 from Sun and install it and set path and classpath in autoexec.bat according to instructions of sun and the previous artical about set path and classpath in this forum.(set classpath=%classpath%. path=C:\jdk1.3\bin;C:;C:\jdk1.3\jre\bin;C:\Program Files\JavaSoft\JRE\1.3\bin
    When I compile the program javac works well. But when I use java to intepreter file the system display some error messages.
    They are :
    1)Exception in thread "main"java.lang.NoClassDefFoundError: Hello
    2)Exception in thread "main" java.lang.UnsatisfiedLinkError: C:\jdk1.3.1_01\jre\bi
    n\awt.dll: An attempt was made to load a program with an
    incorrect format
    at java.lang.ClassLoader$NativeLibrary.load(Native Method)
    at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1382)
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1298)
    at java.lang.Runtime.loadLibrary0(Runtime.java:749)
    at java.lang.System.loadLibrary(System.java:820)
    at sun.security.action.LoadLibraryAction.run(LoadLibraryAction.java:53)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.awt.NativeLibLoader.loadLibraries(NativeLibLoader.java:41)
    at sun.awt.DebugHelper.<clinit>(DebugHelper.java:29)
    at java.awt.Component.<clinit>(Component.java:356)
    at Hello.main(Hello.java:9)
    my code is used : javax.swing.JOptionPane. Code is no problem. I tested it on my freind's Computer.
    Some other programs work well on my computer without swing.
    My OS is win98. sdj1.3.1. Would you please tell me what's going on my machine? I need you guys help! Thanks a lot!
    Seine

    Thanks a lot!
    My program just is HelloWorld. It is:
    import javax.swing.JOptionPane; // import class JOptionPane
    public class Hello {
    //Method Main
    public static void main( String args[] ){
    String name; // name entered by user
    // read in name
    name = JOptionPane.showInputDialog( "Enter Your Name" );
    // say "hello"
    JOptionPane.showMessageDialog(null, "Hello, " +name, "Hello World Application",JOptionPane.PLAIN_MESSAGE );
    System.exit( 0 ); // terminate the program
    My autoexec.bat is:
    SET PATH=C:\jdk1.3\bin;C:\jdk1.3\jre\bin
    @set classpath=.;C:\jdk1.3\lib
    After I use javac to compile the program everything is fine. But when use java file name(no extension .class) to interpreter the java bytesource code. Error will be out:
    "Exception in thread "main" java.lang.NoClassDefFoundError: Hello"
    I tried it in J++, but it still can't be run. the error is:
    "undefined package "javax" or"undefined package "javax.swing". I guess my problem is about "javax".
    I installed several versions:sdk1.2.1, sdk1.3.1 from cd or web. They all don't work. I also use "textpad" to do this job. The same error is out: "Exception in thread "main" java.lang.NoClassDefFoundError: Hello". It is really strange! :( I checked error message. It said:
    NoClassDefFoundError (java.lang)
    The definition of a specified class could not be found
    I don't know which class could not be found. Hello? or javax.Swing.Optionpane?
    Could you guys tell me whether I need to set classpath in autoexec.bat. If yes, what should I do? I tried to fix this problem so many time last whole week. :( BTW, do you guys think whether my win98 has some problem. So java can't access or find the right class.
    Thank so much for your help! I really appreciate it
    Have a nice day!
    Seine

  • New to dynamic class loading - could you help me?

    Hi all!
    Thanks so much for taking a minute to read my post.
    I am a rookie at java and programming.
    I have a program that needs to load a class (or java file) dynamically during runtime. (At least I think that is what it needs to do.)
    I want the user of the program to be able to specify a .java or a .class file either somewhere on the local disk or network, but not necessarily in the same location as the program itself. Once that file is selected, I would like the program to be able to use that file as if it were a .class file created in the working directory when the program was compiled and created.
    I have read a lot of the forums, and I think I need to write my own class loader. I tried creating a class loader, and the code is shown below. (I borrowed this code from some of the other forums I've read.)
    Here is my problem.
    1. Should I be trying to extend the ClassLoader class? Am I on the right track?
    2. If I am on the right track, should I require the user of my program to select a previously compiled ".class" file? Or should I ask them to indicate a ".java" file, and try to compile the java file with the program?
    3. I'm sure that if the above two questions are answered, the solution to this problem will become obvious. But for clarity, I should mention that with the current code (below), I keep getting a java.lang.NoClassDefFoundError inside the class FileClassLoader at the line:
    c = defineClass (classname, buff, 0, buff.length); Obviously, I am not providing the right information to this FileClassLoader in order to create the class. Can you help me out?
    Thank you in advance!
    I really appreciate it!
    Best Regards,
    Julia
    class SampleClass
      public void sampleMethod()
       final JFileChooser fc = new JFileChooser();
       int returnVal = fc.showOpenDialog(optionPane);
       if (returnVal == JFileChooser.APPROVE_OPTION) {
         File file = fc.getSelectedFile();
         try
            FileClassLoader loader = new FileClassLoader(file);
               Class cl = loader.loadClass(file.getName(),false);
            }catch ( ClassNotFoundException e ) {
           System.out.println("ClassNotFoundException");
         }catch (IllegalAccessException e) {
           System.out.println("IllegalAccess");      
         }catch( InstantiationException e) {
           System.out.println("Can't Instantiate That");
    class FileClassLoader extends ClassLoader
         private File file;
         public FileClassLoader (File thisFile)
              this.file = thisFile;
         protected synchronized Class loadClass(String s, boolean bool) throws ClassNotFoundException
              Class c = null;
              try {
                   int size = (int)file.length();
                   byte buff[] = new byte[size];
                   FileInputStream fis = new FileInputStream(file);
                   DataInputStream dis = new DataInputStream (fis);
                   dis.readFully (buff);
                   dis.close();
                   String classname = null;
                   String filename = file.getName();
                   int i = filename.lastIndexOf('.');
                   if(i>0 && i<filename.length()-1)
                        classname = filename.substring(0,i);
                   c = defineClass (classname, buff, 0, buff.length);
                   resolveClass (c);
              } catch (java.io.IOException e) {
                   e.printStackTrace();
              return c;
    }

    Hi!
    If you really need to do that, you can give a look at my previous post at:
    http://forum.java.sun.com/thread.jsp?forum=4&thread=285674
    You can play with the code to suit your needs.
    Hope this helps.

  • Question on JFrame, help me plzzzzzzz!!!

    Hi my friend:
    I need your help on JFrame urgently. As we know, we close a JFrame by clicking the close button on the window title pane. Now I want to change this default for my JFrame. So that when someone click the close button, an Joptionpane is pop out to confirm the closing action. The JFrame will only be closed by clicking the "OK" button on the Joptionpane. If click cancel, optionpane disappear. How to do this? Pls guide me.

    close a JFrame by clicking the close button on the
    window title pane. Now I want to change this default
    for my JFrame. 1) http://java.sun.com/j2se/1.3/docs/api/javax/swing/JFrame.html#setDefaultCloseOperation(int)
    So that when someone click the close
    button, an Joptionpane is pop out to confirm the
    closing action. The JFrame will only be closed by
    clicking the "OK" button on the Joptionpane. If click
    cancel, optionpane disappear.2)
    if(JOptionPane.showConfirmDialog(JFrame.this,"Really close?","Confirm Window Closing", JOptionPane.YES_NO_CANCEL_OPTION)==?){
    //do something...
    }the ? means you can figure it out yourself with the documentation...
    http://java.sun.com/j2se/1.3/docs/api/javax/swing/JOptionPane.html

  • Help to solve this Null Ponter Exception

    Hi,
    I have written this crude piece of code(without any exception handling) for user to enter marks in the text box.
    I am implementing ActionListener on my Submit button and want to retrieve the text entered in the TextField by using getText() mothod.
    I am not able to retrieve the same and it give NullPointer Exception. I am new to Swing. Please help me understand this.
    P.S. I am using JDK1.5 and SpringLayout works only on JDK1.5.
    Here's my code
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class SpringApplet1 extends JApplet implements ActionListener {
         Label label1;
         Label label2;     
         Label label3;
         Label label4;
         JTextField text1;
         JTextField text2;
         JTextField text3;
         JTextField text4;
         JTextArea text;
         JButton Submit;
         SpringLayout layout;
    public void init () {
         public void start(){
         label1 = new Label("Data Structures",1);
         label1.setForeground(Color.red);
         label2 = new Label("Compiler Design",1);
         label2.setForeground(Color.red);
         label3 = new Label("Numerical Analysis",1);
         label3.setForeground(Color.red);
         label4 = new Label("Discrete Matehmatics",1);
         label4.setForeground(Color.red);
         JTextField text1 = new JTextField(20);
         text1.setEditable(true);
         JTextField text2 = new JTextField(20);
         text2.setEditable(true);
         JTextField text3 = new JTextField(20);
         text3.setEditable(true);
         JTextField text4 = new JTextField(20);
         text4.setEditable(true);
         JButton Submit = new JButton ("Submit");
         Submit.setVisible(true);
    Submit.addActionListener(this);
         add(label1);
         add(label2);
         add(label3);
         add(label4);
         add(text1);
         add(text2);
         add(text3);
         add(text4);
         add(Submit);
         SpringLayout layout = new SpringLayout ();
         setLayout(layout);     
         layout.putConstraint (SpringLayout.WEST, label1,
    5, SpringLayout.WEST, this);
    layout.putConstraint (SpringLayout.NORTH, label1,
    5, SpringLayout.NORTH, this);
         layout.putConstraint (SpringLayout.WEST, label2,
    5, SpringLayout.WEST, this);
    layout.putConstraint (SpringLayout.NORTH, label2,
    5, SpringLayout.SOUTH, label1);
         layout.putConstraint (SpringLayout.WEST, label3,
    5, SpringLayout.WEST, this);
    layout.putConstraint (SpringLayout.NORTH, label3,
    5, SpringLayout.SOUTH, label2);
         layout.putConstraint (SpringLayout.WEST, label4,
    5, SpringLayout.WEST, this);
    layout.putConstraint (SpringLayout.NORTH, label4,
    5, SpringLayout.SOUTH, label3);
    layout.putConstraint (SpringLayout.WEST, text1,
    150, SpringLayout.WEST, this);
    layout.putConstraint (SpringLayout.NORTH, text1,
    5, SpringLayout.NORTH, this);
    layout.putConstraint (SpringLayout.WEST, text2,
    150, SpringLayout.WEST, this);
    layout.putConstraint (SpringLayout.NORTH, text2,
    5, SpringLayout.SOUTH, text1);
    layout.putConstraint (SpringLayout.WEST, text3,
    150, SpringLayout.WEST, this);
    layout.putConstraint (SpringLayout.NORTH, text3,
    5, SpringLayout.SOUTH, text2);
    layout.putConstraint (SpringLayout.WEST, text4,
    150, SpringLayout.WEST, this);
    layout.putConstraint (SpringLayout.NORTH, text4,
    5, SpringLayout.SOUTH, text3);
         layout.putConstraint (SpringLayout.WEST, Submit,
    250, SpringLayout.WEST, this);
    layout.putConstraint (SpringLayout.NORTH, Submit,
    10,SpringLayout.SOUTH, text4);
         public void paint(Graphics g) {
         //Draw a Rectangle around the applet's display area.
    g.drawRect(0, 0, size().width - 1, size().height - 1);
         public void actionPerformed(ActionEvent event){
         String message = "Are you sure all information is correct";
         String title = "Confirmation";
         String str_text1;
         String str_text2;
         String str_text3;
         String str_text4;
         int n = JOptionPane.showConfirmDialog(null,message,title, JOptionPane.INFORMATION_MESSAGE);
         //optionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION);
         if(n==0)
         str_text1=text1.getText();
         str_text2=text2.getText();
         str_text3=text3.getText();
         str_text4=text4.getText();
    }

    You are declaringlocal instances of the Textfields in start():
    JTextField text1 = new JTextField(20);should be:
    text1 = new JTextField(20);Same for the other Textfields.

  • JOptionPane Help Needed

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

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

  • JWindow closing with ALT F4 leaving child components  help please.....

    Hi all
    I come acrossed one problem i.e i have my main application as JWindow and a button and when i click it iam getting an JOptionPane/JRame/JDialog and set modal if its dialog and set modal through window activate and deactivate if its JFrame the problem is when i click on JWindow and press ALT F4 my JWindow is closing leaving the child Component (i.e JDialog/JOptionPane... etc)now i want to not to close JWindow if there was any dialog,optionpane opened any ideas/views/sugesstions please suggest...
    Kalpana

    Hi!
    How did you created your frames / dialogs?
    You must give the reference of the JWindow instance as owner for your child frames...
    I hope this helps you,
    Taoufik

Maybe you are looking for

  • All office programs crash when I click on the File menu

    I can open files in every program fine but as soon as I go to the File Menu it puts up the "program" is not responding box Excel, Word and PowerPoint all crash when trying for the File Menu. Outlook will let me go to the File Menu but if I click on O

  • IPhoto will not open on my iMac

    I'm a new iMac user and iPhoto will not open or launch. I have tried to re-install iPhoto but this had no affect. iMac OS X Version 10.6.8 iPhoto Version 9.2.1 Any help or assistance would be much appreciated, thanks.

  • Hide application doesn't work

    Think this is an Exposé issue. Command H to hide an application works on every application on my G5 - but not on my G4 or Powerbook - all running the same system (OSX 3.9) and applications. I'm sure I had to do something in preferences or whatever to

  • Computer died...now how can I retrieve keyword tags from my old hard drive?

    I got a new computer and installed Elements 9.0 on it.  I am retrieving the pics from my old hard drive just fine but I seem to have lost the majority of my old keyword tags.  Any help?  Thanks.

  • Reports Demo

    I have Oracle Infrastructure and 9iAS on a Solaris machine. The actual database is on a windows 2000 machine. I am trying to run the Report demonstrations. I get an unable to connect to the specified database error. I assume I need to change the tnsn