Enter in JDialog

Hello friends !
I have JDialog with some JLabels, JSpinners and one JButton.
The JSpinners are numerical, i.e. if I type say "bla bla" in it, I hear a beep. Only when enter a number JSpinner accepts it.
When I click the JButton, loadPicture() called.
I want that if I press Enter after (enter some number in the JSpinner), loadPicture() will be called.
What should I add ?
Below is the code of the JDialog.
Thanks in advance !!!
public class JCRandomCrosswordDialog extends JDialog implements ActionListener {
     private JCFrame mainFrame;
     private JTextField fillingPercentageField;
     private JSpinner rowsSpinner, columnsSpinner;
     private JButton createButton = new JButton("Create random crossword");
     public JCRandomCrosswordDialog(JCFrame mainFrame) {
            super(mainFrame, "Create random crossword", true);
            this.mainFrame = mainFrame;
            rowsSpinner = new JSpinner(new SpinnerNumberModel(mainFrame.getDefaultNumberOfRows(), 1, mainFrame.getMaxNumberOfRows(), 1));
            columnsSpinner = new JSpinner(new SpinnerNumberModel(mainFrame.getDefaultNumberOfColumns(), 1, mainFrame.getMaxNumberOfColumns(), 1));
            fillingPercentageField = new JTextField(String.valueOf(mainFrame.getDefaultPercentageOfFilling()));
            ((JSpinner.DefaultEditor)(rowsSpinner.getEditor())).getTextField().setHorizontalAlignment(JTextField.LEFT);
            ((JSpinner.DefaultEditor)(columnsSpinner.getEditor())).getTextField().setHorizontalAlignment(JTextField.LEFT);
            JCToolkit.setSelectAllFieldText(((JSpinner.DefaultEditor)(rowsSpinner.getEditor())).getTextField());
            JCToolkit.setSelectAllFieldText(((JSpinner.DefaultEditor)(columnsSpinner.getEditor())).getTextField());
            JCToolkit.setSelectAllFieldText(fillingPercentageField);
            Container contentPane = getContentPane();
            JPanel dialogPanel = new JPanel();
         dialogPanel.setLayout(new GridLayout(3, 2));
         dialogPanel.add(new JLabel("  Number of rows:", JLabel.LEFT));
         dialogPanel.add(rowsSpinner);
         dialogPanel.add(new JLabel("  Number of columns:", JLabel.LEFT));
         dialogPanel.add(columnsSpinner);
         dialogPanel.add(new JLabel("  Filling percentage:", JLabel.LEFT));
         dialogPanel.add(fillingPercentageField);
         contentPane.add(dialogPanel, BorderLayout.NORTH);
         createButton.addActionListener(this);
         contentPane.add(createButton, BorderLayout.SOUTH);
            setSize(260, 125);
     public void actionPerformed(ActionEvent e) {
          int numOfRows = getSpinnerValue(rowsSpinner, mainFrame.getDefaultNumberOfRows());
          if ((numOfRows < 1) || (numOfRows > mainFrame.getMaxNumberOfRows())) throw new NumberFormatException();
          int numOfColumns = getSpinnerValue(columnsSpinner, mainFrame.getDefaultNumberOfColumns());
          if ((numOfColumns < 1) || (numOfColumns > mainFrame.getMaxNumberOfColumns())) throw new NumberFormatException();
          try {     
               float percentage = (Float.valueOf(fillingPercentageField.getText())).floatValue();
               if ((percentage < 0.0f) || (percentage > 100.0f)) throw new NumberFormatException();
               dispose();
               ((JCFrame)getOwner()).loadPicture(JCToolkit.getRandomCrossword(numOfRows, numOfColumns, percentage / 100));
          } catch (NumberFormatException nfe) {
               fillingPercentageField.requestFocus();
     private int getSpinnerValue(JSpinner spinner, int defaultValue) {
          try { spinner.commitEdit(); }
          catch (ParseException pe) { spinner.setValue(defaultValue); }
          return ((Integer)(spinner.getValue())).intValue();
}

OK, Michael. Now is much much better !
But still 2 questions:
1) If I type some string on the "Number of rows" spinner, then press Enter, the dialog takes the default value 10 (which I see when I enter the dialog again). But If I enter some string in the "Filling percentage" spinner, then press Enter, the dialog doesn't take the default value (it takes all the string). Why ?
2) I want that if the entered number is out of legal range, i.e. for example ((numOfRows < 1) || (numOfRows > 99)) then pressing Enter will not close the dialog with the default values, and the user will need to enter a legal values. What should I change to add this requirement ?
Many thanks again !!!
Here is the last code:
import javax.swing.*;       
public class Test {
     private static void createAndShowGUI() {       
        JFrame frame = new JFrame("HelloWorldSwing");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        MyDialog dialog = new MyDialog(frame);
            MyMenuBar menuBar = new MyMenuBar(frame);
          frame.setJMenuBar(menuBar);
        frame.pack();
        frame.setVisible(true);
    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
import java.text.ParseException;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyDialog extends JDialog implements ActionListener {
     private JFrame mainFrame;
     private JTextField fillingPercentageField;
     private JSpinner rowsSpinner, columnsSpinner;
     private JButton createButton = new JButton("Create random crossword");
     public MyDialog(JFrame mainFrame) {
            super(mainFrame, "Create random crossword", true);
            this.mainFrame = mainFrame;
            rowsSpinner = new JSpinner(new SpinnerNumberModel(10, 1, 99, 1));
            columnsSpinner = new JSpinner(new SpinnerNumberModel(20, 1, 100, 2));
            fillingPercentageField = new JTextField(String.valueOf(8.7));
            ((JSpinner.DefaultEditor)(rowsSpinner.getEditor())).getTextField().setHorizontalAlignment(JTextField.LEFT);
            ((JSpinner.DefaultEditor)(columnsSpinner.getEditor())).getTextField().setHorizontalAlignment(JTextField.LEFT);
            Container contentPane = getContentPane();
            JPanel dialogPanel = new JPanel();
              dialogPanel.setLayout(new GridLayout(3, 2));
              dialogPanel.add(new JLabel("  Number of rows:", JLabel.LEFT));
              dialogPanel.add(rowsSpinner);
              dialogPanel.add(new JLabel("  Number of columns:", JLabel.LEFT));
              dialogPanel.add(columnsSpinner);
              dialogPanel.add(new JLabel("  Filling percentage:", JLabel.LEFT));
              dialogPanel.add(fillingPercentageField);
              contentPane.add(dialogPanel, BorderLayout.NORTH);
              createButton.addActionListener(this);
              contentPane.add(createButton, BorderLayout.SOUTH);
              KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
                  public boolean dispatchKeyEvent(KeyEvent ke) {
                         if(ke.getID() == KeyEvent.KEY_PRESSED) {
                           if (((KeyEvent) ke).getKeyCode() == KeyEvent.VK_ENTER) {
                                  //createButton.doClick();
                                  if(isVisible()) createButton.doClick();
                         return false;
            setSize(260, 125);
     public void actionPerformed(ActionEvent e) {
          int numOfRows = getSpinnerValue(rowsSpinner, 10);
          if ((numOfRows < 1) || (numOfRows > 99)) throw new NumberFormatException();
          int numOfColumns = getSpinnerValue(columnsSpinner, 20);
          if ((numOfColumns < 1) || (numOfColumns > 100)) throw new NumberFormatException();
          try {     
               float percentage = (Float.valueOf(fillingPercentageField.getText())).floatValue();
               if ((percentage < 0.0f) || (percentage > 100.0f)) throw new NumberFormatException();
          } catch (NumberFormatException nfe) {
               fillingPercentageField.requestFocus();
          } finally {
               dispose();
          JOptionPane.showMessageDialog(mainFrame, "OK", "Important Message", JOptionPane.PLAIN_MESSAGE);
     private int getSpinnerValue(JSpinner spinner, int defaultValue) {
          try { spinner.commitEdit(); }
          catch (ParseException pe) { spinner.setValue(defaultValue); }
          return ((Integer)(spinner.getValue())).intValue();
import javax.swing.*;
import java.awt.event.*;
public class MyMenuBar extends JMenuBar implements ActionListener {
     private JFrame mainFrame;
     private JMenuItem showDialog;
     private MyDialog dialog;
     public MyMenuBar(JFrame mainFrame) {
          this.mainFrame = mainFrame;
          dialog = new MyDialog(mainFrame);
          JMenu menu = new JMenu("Misc");    
          menu.setMnemonic(KeyEvent.VK_M);
          showDialog = new JMenuItem("Show dialog");
          showDialog.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0));
          showDialog.addActionListener(this);
          menu.add(showDialog);
          add(menu);
     public void actionPerformed(ActionEvent e) {
          if (e.getSource() == showDialog) {
               dialog.setVisible(true);
               return;
}

Similar Messages

  • Mouse Drag in JDialog produces Mouse Enter & Mouse Exit events in JFrame.

    Hi, all.
    Do I have a misconception here? When I drag the mouse in a modal JDialog, mouseEntered and mouseExited events are being delivered to JComponents in the parent JFrame that currently happens to be beneath that JDialog. I would not have expected any events to be delivered to any component not in the modal JDialog while that JDialog is displayed.
    I submitted this as a bug many months ago, and have heard nothing back from Sun, nor can I find anything similar to this in BugTraq.
    Here is sample code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    * This class demonstrates what I believe are TWO bugs in Mouse Event handling in Swing
    * 1.1.3_1, 1.1.3_2, 1.1.3_3, and 1.4.0.
    * 1) When a MODAL JDialog is being displayed, and the cursor is DRAGGED from the JDialog
    *    into and across the parent JFrame, Mouse Enter and Mouse Exit events are given to
    *    the parent JFrame and/or it's child components.  It is my belief that NO such events
    *    should be delivered, that modal dialogs should prevent ANY user interaction with any
    *    component NOT in the JDialog.  Am I crazy?
    *    You can reproduce this simply by running the main() method, then dragging the cursor
    *    from the JDialog into and across the JFrame.
    * 2) When a MODAL JDialog is being displayed, and the cursor is DRAGGED across the JDialog,
    *    Mouse Enter and Mouse Exit events are given to the parent JFrame and/or it's child
    *    components.  This is in addition to the problem described above.
    *    You can reproduce this by dismissing the initial JDialog displayed when the main()
    *    method starts up, clicking on the "Perform Action" button in the JFrame, then dragging
    *    the cursor around the displayed JDialog.
    * The Mouse Enter and Mouse Exit events are reported via System.err.
    public class DragTest
        extends JFrame
        public static void main(final String[] p_args)
            new DragTest();
        public DragTest()
            super("JFrame");
            WindowListener l_windowListener = new WindowAdapter() {
                public void windowClosing(final WindowEvent p_evt)
                    DragTest.this.dispose();
                public void windowClosed(final WindowEvent p_evt)
                    System.exit(0);
            MouseListener l_mouseListener = new MouseAdapter() {
                public void mouseEntered(final MouseEvent p_evt)
                    System.err.println(">>> Mouse Entered: " + ((Component)p_evt.getSource()).getName() );
                public void mouseExited(final MouseEvent p_evt)
                    System.err.println(">>> Mouse Exited: " + ((Component)p_evt.getSource()).getName() );
            JPanel l_panel1 = new JPanel();
            l_panel1.setLayout( new BorderLayout(50,50) );
            l_panel1.setName("JFrame Panel");
            l_panel1.addMouseListener(l_mouseListener);
            JButton l_button = null;
            l_button = new JButton("JFrame North Button");
            l_button.setName(l_button.getText());
            l_button.addMouseListener(l_mouseListener);
            l_panel1.add(l_button, BorderLayout.NORTH);
            l_button = new JButton("JFrame South Button");
            l_button.setName(l_button.getText());
            l_button.addMouseListener(l_mouseListener);
            l_panel1.add(l_button, BorderLayout.SOUTH);
            l_button = new JButton("JFrame East Button");
            l_button.setName(l_button.getText());
            l_button.addMouseListener(l_mouseListener);
            l_panel1.add(l_button, BorderLayout.EAST);
            l_button = new JButton("JFrame West Button");
            l_button.setName(l_button.getText());
            l_button.addMouseListener(l_mouseListener);
            l_panel1.add(l_button, BorderLayout.WEST);
            l_button = new JButton("JFrame Center Button");
            l_button.setName(l_button.getText());
            l_button.addMouseListener(l_mouseListener);
            l_panel1.add(l_button, BorderLayout.CENTER);
            JButton l_actionButton = l_button;
            Container l_contentPane = this.getContentPane();
            l_contentPane.setLayout( new BorderLayout() );
            l_contentPane.add(l_panel1, BorderLayout.NORTH);
            JPanel l_panel2 = new JPanel();
            l_panel2.setName("JDialog Panel");
            l_panel2.addMouseListener(l_mouseListener);
            l_panel2.setLayout( new BorderLayout(50,50) );
            l_panel2.add( new JButton("JDialog North Button"),  BorderLayout.NORTH  );
            l_panel2.add( new JButton("JDialog South Button"),  BorderLayout.SOUTH  );
            l_panel2.add( new JButton("JDialog East Button"),   BorderLayout.EAST   );
            l_panel2.add( new JButton("JDialog West Button"),   BorderLayout.WEST   );
            l_panel2.add( new JButton("JDialog Center Button"), BorderLayout.CENTER );
            final JDialog l_dialog = new JDialog(this, "JDialog", true);
            WindowListener l_windowListener2 = new WindowAdapter() {
                public void windowClosing(WindowEvent p_evt)
                    l_dialog.dispose();
            l_dialog.addWindowListener(l_windowListener2);
            l_dialog.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
            l_dialog.getContentPane().add(l_panel2, BorderLayout.CENTER);
            l_dialog.pack();
            Action l_action = new AbstractAction() {
                { putValue(Action.NAME, "Perform Action (open dialog)"); }
                public void actionPerformed(final ActionEvent p_evt)
                    l_dialog.setVisible(true);
            l_actionButton.setAction(l_action);
            this.addWindowListener(l_windowListener);
            this.pack();
            this.setLocation(100,100);
            this.setVisible(true);
            l_dialog.setVisible(true);
    }(Too bad blank lines are stripped, eh?)
    Thanks in advance for any insights you may be able to provide.
    ---Mark

    I guess we can think of this as one problem. When mouse dragged, JFrame also (Parent) receives events. If i understood correctly, what happens here is, Modal dialog creates its own event pump and Frame will be having its own. See the source code of Dialog's show() method. It uses an interface called Conditional to determine whether to block the events or yield it to parent pump.
    Here is the Conditional code and show method code from java.awt.dialog for reference
    package java.awt;
    * Conditional is used by the EventDispatchThread's message pumps to
    * determine if a given pump should continue to run, or should instead exit
    * and yield control to the parent pump.
    * @version 1.3 02/02/00
    * @author David Mendenhall
    interface Conditional {
        boolean evaluate();
    /////show method
        public void show() {
            if (!isModal()) {
                conditionalShow();
            } else {
                // Set this variable before calling conditionalShow(). That
                // way, if the Dialog is hidden right after being shown, we
                // won't mistakenly block this thread.
                keepBlocking = true;
                if (conditionalShow()) {
                    // We have two mechanisms for blocking: 1. If we're on the
                    // EventDispatchThread, start a new event pump. 2. If we're
                    // on any other thread, call wait() on the treelock.
                    if (Toolkit.getEventQueue().isDispatchThread()) {
                        EventDispatchThread dispatchThread =
                            (EventDispatchThread)Thread.currentThread();
                           * pump events, filter out input events for
                           * component not belong to our modal dialog.
                           * we already disabled other components in native code
                           * but because the event is posted from a different
                           * thread so it's possible that there are some events
                           * for other component already posted in the queue
                           * before we decide do modal show. 
                        dispatchThread.pumpEventsForHierarchy(new Conditional() {
                            public boolean evaluate() {
                                return keepBlocking && windowClosingException == null;
                        }, this);
                    } else {
                        synchronized (getTreeLock()) {
                            while (keepBlocking && windowClosingException == null) {
                                try {
                                    getTreeLock().wait();
                                } catch (InterruptedException e) {
                                    break;
                    if (windowClosingException != null) {
                        windowClosingException.fillInStackTrace();
                        throw windowClosingException;
        }I didn't get exactly what is happening but this may help to think further

  • How to make the Enter key close a JDialog?

    I have a dialog box which extends JDialog. I have several buttons and other components, but I would like to make the OK button the one which reacts when the user presses Enter. Are there any specific methods to get this behaviour?

    dialog.getRootPane().setDefaultButton(okButton);

  • How to add the action enter  to the textfield in a jdialog?

    I did a login class using a applet it is working very well...but now..i would like to add the action to the textfield when the user press a enter.
    I would like that after that he or she has pressed a enter in the textfield were done the corresponding action, could some body help me please?
    This is my code:
         public void init() {
    AppletContext context;
              URL exitoUrl, fallaUrl;
         try {
         context = getAppletContext();
         exitoUrl = new URL("http://111.23.56.12/page1.html");
         fallaUrl = new URL("http://111.23.56.12/passwordIncorrecto.html");
                   JPasswordField pf = new JPasswordField();
                   Object[] message = new Object[] {"Intr. the password", pf};
                   Object[] options = new String[] {"Intro", "Cancel"};
                   JOptionPane op = new JOptionPane(message, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null, options);
                   JDialog dialog = op.createDialog(null, "Login");
                   dialog.show();
                   String password = new String("success");
                   String tmp = new String(pf.getPassword());
                   if ( password.equals(tmp) ) {
                        System.out.println("correct password");
         context.showDocument(exitoUrl);
         else {
                        System.out.println("incorrecto password ");
         context.showDocument(fallaUrl);
              } catch(Exception e) {
                   System.out.println("Error exception");
    Thanks in advance;
    Mary

    Hi,
    it is easy: create an entity object for every table and one view object where you select your both entity objects and join them in your select statement.
    Your desired 'confirm' functionality could be achieved with helpp of view object transient attributes - for more information see: http://docs.oracle.com/cd/E21764_01/web.1111/b31974/bcquerying.htm#CHDHJHBI
    Regards
    Pavol

  • Configuring what element gets enter key press in JDialog?

    Hi all,
    In windows applications, some dialogs or windows, have a specific button that gets activated when enter is pressed. E.g. in a JDialog, the OK button would normally be activated when no button had focus. How do you set this to be? Is there some API call to do this? And is there some way to do the same with the escape key, so that cancel will always get triggered when its pressed?
    I just don't want to have to manually add a key listener to each component in the dialog that listens for the escape and enter buttons to be pressed.
    thanks,
    J

    As for the Esc key, there is nothing "out of the box" to do this. I created a JDialog sub-class to handle it, which I use in place of JDialog throughout my app. In the JDialog sub-class, over-ride the createRootPane() method as follows:
        * Overriding this method to register an action so the 'Esc' key will dismiss
        * the dialog.
        * @return a <code>JRootPane</code> with the appropiate action registered
       protected JRootPane createRootPane()
          JRootPane pane = super.createRootPane();
          pane.getInputMap( JComponent.WHEN_IN_FOCUSED_WINDOW ).
             put( KeyStroke.getKeyStroke( KeyEvent.VK_ESCAPE, 0 ), "escPressed" );
          pane.getActionMap().put( "escPressed",
             new AbstractAction( "escPressed" )
                public void actionPerformed( ActionEvent actionEvent )
                   onDialogClose();
          return pane;
       }then, create an abstract onDialogClose() method like the following:
        * This method gets called when the user attemps to close the JDialog via the
        * 'Esc' key.  It is up to the sub-class to implement this method and handle
        * the situation appropriately.
       protected abstract void onDialogClose();Alternatively, you could create a default implemenation of onDialogClose() instead of making it abstract; sub-classes could still over-ride it if they needed custom behavior.
    HTH,
    Jamie

  • Saving parameters entered in a gui dialog to be used in the main panel

    Hi,
    I'm having a nightmare at the moment.
    I've finished creating a program for my final year project, that is all comand line at the moment.
    i'm required to design a GUI for this. i've started already and have a main panel that has a few buttons one of which is a setParameters button. which opens up a file dialog that allows the user to enter parameters that will be used by the main panel later on.
    I'm having trouble imagining how these parameters will be accessed by the main Panel once they are saved.
    At the moment, without the GUI i have get and set methods in my main program which works fine. Is this the kind of thing i'll be using for this?
    my code for the parameters dialog
    public class Parameters  extends JDialog
         private GridLayout grid1, grid2, grid3;
         JButton ok, cancel;
            public Parameters()
                    setTitle( "Parameters" );
                    setSize( 400,500 );
                    setDefaultCloseOperation( DISPOSE_ON_CLOSE );
              grid1 = new GridLayout(7,2);
              grid2 = new GridLayout(1,2);
                    JPanel topPanel = new JPanel();
                    topPanel.setLayout(grid1);
              JPanel buttonPanel = new JPanel();
                    buttonPanel.setLayout(grid2);
              ok = new JButton("OK");
                  ok.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent e) {
                  //when pressed i want to save the parameters that the user has entered
              //and be able to access these in the RunPanel class
              cancel = new JButton("Cancel");
                 cancel.addActionListener(new ActionListener() {
                          public void actionPerformed(ActionEvent e) {
                        //when pressed just want the Jdialog  to close
              buttonPanel.add(ok);
              buttonPanel.add(cancel);
              JTextArea affinityThresholdScalar = new JTextArea();
              JTextArea clonalRate = new JTextArea();
              JTextArea stimulationValue = new JTextArea();
              JTextArea totalResources = new JTextArea();
              JLabel aTSLabel = new JLabel("affinityThresholdScalar");
              JLabel cRLabel = new JLabel("clonalRate");
              topPanel.add(aTSLabel);
              topPanel.add(affinityThresholdScalar);
              topPanel.add(cRLabel);
              topPanel.add(clonalRate);
                    Container container = getContentPane();//.add( topPanel );
              container.add( topPanel, BorderLayout.CENTER );
              container.add( buttonPanel, BorderLayout.SOUTH );
         }the main panel class is:
    public class RunPanel extends JPanel implements ActionListener
         JButton openButton, setParametersButton, saveButton;
         static private final String newline = "\n";
         JTextArea log;
             JFileChooser fc;
         Data d = new Data();
         Normalise rf = new Normalise();
         Parameters param = new Parameters();
        public RunPanel()
            super(new BorderLayout());
            log = new JTextArea(5,20);
            log.setMargin(new Insets(5,5,5,5));
            log.setEditable(false);
            JScrollPane logScrollPane = new JScrollPane(log);
            fc = new JFileChooser();
            openButton = new JButton("Open a File...")
            openButton.addActionListener(this);
         setParametersButton = new JButton("Set User Parameters");
            setParametersButton.addActionListener(this);
         saveButton = new JButton("save");
            saveButton.addActionListener(this);
            JPanel buttonPanel = new JPanel(); //use FlowLayout
            buttonPanel.add(openButton);
         buttonPanel.add(setParametersButton);
         JPanel savePanel = new JPanel();
         savePanel.add(saveButton);
            add(buttonPanel, BorderLayout.PAGE_START);
            add(logScrollPane, BorderLayout.CENTER);
         add(savePanel, BorderLayout.SOUTH);
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == openButton) {
                int returnVal = fc.showOpenDialog(RunPanel.this);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = fc.getSelectedFile();
                    log.append("Opening: " + file.getName() + "." + newline);
              Vector data = d.readFile(file);
              log.append("Reading file into Vector " +data+ "." + newline);
              Vector dataNormalised = rf.normalise(data);
             else {
                    log.append("Open command cancelled by user." + newline);
                log.setCaretPosition(log.getDocument().getLength());
         else if (e.getSource() == saveButton) {
                int returnVal = fc.showSaveDialog(RunPanel.this);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = fc.getSelectedFile();
                    log.append("Saving: " + file.getName() + "." + newline);
                } else {
                    log.append("Save command cancelled by user." + newline);
                log.setCaretPosition(log.getDocument().getLength());
         else
              if (e.getSource() == setParametersButton)
                    log.append("loser." + newline);
                          param.show();
        private static void createAndShowGUI() {
            JFrame.setDefaultLookAndFeelDecorated(true);
            JDialog.setDefaultLookAndFeelDecorated(true);
            JFrame frame = new JFrame("AIRS");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JComponent newContentPane = new RunPanel();
            newContentPane.setOpaque(true);
            frame.setContentPane(newContentPane);
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }Can anybody offer any suggestions?
    Cheers

    What you need is my ParamDialog. I think it could be perfect for this sort of thing. There are a few references in it to some of my other classes namely
    StandardDialog. Which you can find by searching for other posts on this forum. But if you'd rather not find that you could just use JDialog instead
    WindowUtils.visualize() this is just a helper method for getting things visualized on the screen. You can just use setBounds and setVisible and you'll be fine.
    You are welcome to use and modify this code but please don't change the package or take credit for it as your own work.
    If you need to bring up a filedialog or a color chooser you will need to make some modifications. If you do this, would you mind posting that when you are done so that myself and others can use it? :)
    StandardDialog.java
    ================
    package tjacobs.ui;
    import java.awt.Dialog;
    import java.awt.Frame;
    import java.awt.GraphicsConfiguration;
    import java.awt.HeadlessException;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JPasswordField;
    import javax.swing.JTextField;
    import java.awt.*;
    import java.util.HashMap;
    import java.util.Properties;
    /** Usage:
    * *      ParamDialog pd = new ParamDialog(new String[] {"A", "B", "C"});
    * pd.pack();
    * pd.setVisible(true);
    * Properties p = pd.getProperties();
    public class ParamDialog extends StandardDialog {
         public static final String SECRET = "(SECRET)";
         String[] fields;
         HashMap<String, JTextField> mValues = new HashMap<String, JTextField>();
         public ParamDialog(String[] fields) throws HeadlessException {
              this(null, fields);
         public ParamDialog(JFrame owner, String[] fields) {
              super(owner);
              setModal(true);
              this.fields = fields;
              JPanel main = new JPanel();
              main.setLayout(new GridLayout(fields.length, 1));
              for (int i = 0; i < fields.length; i++) {
                   JPanel con = new JPanel(new FlowLayout());
                   main.add(con);
                   JTextField tf;
                   if (fields.endsWith(SECRET)) {
                        con.add(new JLabel(fields[i].substring(0, fields[i].length() - SECRET.length())));
                        tf = new JPasswordField();
                   else {
                        con.add(new JLabel(fields[i]));
                        tf = new JTextField();
                   tf.setColumns(12);
                   con.add(tf);
                   mValues.put(fields[i], tf);
              this.setMainContent(main);
         public boolean showApplyButton() {
              return false;
         public void apply() {
         private boolean mCancel = false;
         public void cancel() {
              mCancel = true;
              super.cancel();
         public Properties getProperties() {
              if (mCancel) return null;
              Properties p = new Properties();
              for (int i = 0; i < fields.length; i++) {
                   p.put(fields[i], mValues.get(fields[i]).getText());
              return p;
         public static void main (String[] args) {
              ParamDialog pd = new ParamDialog(new String[] {"A", "B", "C"});
              WindowUtilities.visualize(pd);     
         public static Properties getProperties(String[] fields) {
              ParamDialog pd = new ParamDialog(fields);
              WindowUtilities.visualize(pd);
              return pd.getProperties();          

  • Hiding a JDialog invoked in a Thread.

    Hi,
    I have a Swing application that starts a Thread that in turn creates a modal JDialog. I need to use the Thread so that I can wait around for information entered in the Dialog while leaving the rest of the application interactive. However, when I do this, any attempt I try (hide and setVisible(false)) to remove the dialog visibly from the screen fails. I initialize the Dialog with null as the Parent frame. Is that my problem, or am I doing something else wrong?
    Thanks,
    Jason Mazzotta

    Generally you can close the dialog only from the event-dispatching thread. If you want to do it from another thread, you have to do the following:
    instead of calling
    setVisible( false );call
            SwingUtilities.invokeLater(
            new Runnable()
                public void run()
                     waitDlg.setVisible( false );

  • Tranfer data from a jdialog to a frame!

    Hello, everybody?!That is my doubt!!There's a jtable inside a jdialog, when a row was selected, and the "enter" key was pressed, i'd like to send the data to a frame (main).How could i create that?Thanks!!

    here's something rough - just sets the selection as the label's text. modify for the row data
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    class Testing
      JLabel selection = new JLabel("Selected Value = ");
      public void buildGUI()
        JButton btn = new JButton("Get Selection");
        final JFrame f = new JFrame();
        f.getContentPane().add(selection,BorderLayout.NORTH);
        f.getContentPane().add(btn,BorderLayout.SOUTH);
        f.setSize(200,80);
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
        btn.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            final JDialog d = new JDialog();
            Object[] cols = {"A","B","C"};
            Object[][] data = {{1,2,3},{4,5,6},{7,8,9},{10,11,12},{13,14,15}};
            final JTable table = new JTable(data,cols){
              public boolean isCellEditable(int row, int col){
                return false;
            JScrollPane sp = new JScrollPane(table);
            sp.setPreferredSize(new Dimension(100,100));
            d.setModal(true);
            d.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
            d.getContentPane().add(sp);
            d.pack();
            d.setLocationRelativeTo(f);
            Action enterAction = new AbstractAction(){
              public void actionPerformed(ActionEvent ae){
                selection.setText("Selected Value = " +
                table.getValueAt(table.getSelectedRow(),table.getSelectedColumn()));
                d.dispose();
            InputMap im = table.getInputMap(JTable.WHEN_FOCUSED);
            KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
            im.put(enter, "enter");
            table.getActionMap().put(im.get(enter), enterAction);
            d.setVisible(true);
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    }

  • Problem with a template method in JDialog

    Hi friends,
    I'm experiencing a problem with JDialog. I have a base abstract class ChooseLocationDialog<E> to let a client choose a location for database. This is an abstract class with two abstract methods:
    protected abstract E prepareLocation();
    protected abstract JPanel prepareForm();Method prepareForm is used in the constructor of ChooseLocationDialog to get a JPanel and add it to content pane.
    Method prepareLocation is used to prepare location of a database. I have to options - local file and networking.
    There are two subclasses ChooseRemoteLocationDialog and ChooseLocalFileDialog.
    When I start a local version, ChooseLocalFileDialog with one input field for local file, everything works fine and my local client version starts execution.
    The problem arises when I start a network version of my client. Dialog appears and I can enter host and port into the input fields. But when I click Select, I get NullPointerException. During debugging I noticed that the values I entered into these fields ("localhost" for host and "10999" for port) were not set for corresponding JTextFields and when my code executes getText() method for these input fields it returns empty strings. This happens only for one of these dialogs - for the ChooseRemoteLocationDialog.
    The code for ChooseLocationDialog class:
    public abstract class ChooseLocationDialog<E> extends JDialog {
         private E databaseLocation;
         private static final long serialVersionUID = -1630416811077468527L;
         public ChooseLocationDialog() {
              setTitle("Choose database location");
              setAlwaysOnTop(true);
              setModal(true);
              Container container = getContentPane();
              JPanel mainPanel = new JPanel();
              //retrieving a form of a concrete implementation
              JPanel formPanel = prepareForm();
              mainPanel.add(formPanel, BorderLayout.CENTER);
              JPanel buttonPanel = new JPanel(new GridLayout(1, 2));
              JButton okButton = new JButton(new SelectLocationAction());
              JButton cancelButton = new JButton(new CancelSelectAction());
              buttonPanel.add(okButton);
              buttonPanel.add(cancelButton);
              mainPanel.add(buttonPanel, BorderLayout.SOUTH);
              container.add(mainPanel);
              pack();
              Toolkit toolkit = Toolkit.getDefaultToolkit();
              Dimension screenSize = toolkit.getScreenSize();
              int x = (screenSize.width - getWidth()) / 2;
              int y = (screenSize.height - getHeight()) / 2;
              setLocation(x, y);
              addWindowListener(new WindowAdapter() {
                   @Override
                   public void windowClosing(WindowEvent e) {
                        super.windowClosing(e);
                        System.exit(0);
         public E getDatabaseLocation() {
                return databaseLocation;
         protected abstract E prepareLocation();
         protected abstract JPanel prepareForm();
          * Action for selecting location.
          * @author spyboost
         private class SelectLocationAction extends AbstractAction {
              private static final long serialVersionUID = 6242940810223013690L;
              public SelectLocationAction() {
                   putValue(Action.NAME, "Select");
              @Override
              public void actionPerformed(ActionEvent e) {
                   databaseLocation = prepareLocation();
                   setVisible(false);
         private class CancelSelectAction extends AbstractAction {
              private static final long serialVersionUID = -1025433106273231228L;
              public CancelSelectAction() {
                   putValue(Action.NAME, "Cancel");
              @Override
              public void actionPerformed(ActionEvent e) {
                   System.exit(0);
    }Code for ChooseLocalFileDialog
    public class ChooseLocalFileDialog extends ChooseLocationDialog<String> {
         private JTextField fileTextField;
         private static final long serialVersionUID = 2232230394481975840L;
         @Override
         protected JPanel prepareForm() {
              JPanel panel = new JPanel();
              panel.add(new JLabel("File"));
              fileTextField = new JTextField(15);
              panel.add(fileTextField);
              return panel;
         @Override
         protected String prepareLocation() {
              String location = fileTextField.getText();
              return location;
    }Code for ChooseRemoteLocationDialog
    public class ChooseRemoteLocationDialog extends
              ChooseLocationDialog<RemoteLocation> {
         private JTextField hostField;
         private JTextField portField;
         private static final long serialVersionUID = -2282249521568378092L;
         @Override
         protected JPanel prepareForm() {
              JPanel panel = new JPanel(new GridLayout(2, 2));
              panel.add(new JLabel("Host"));
              hostField = new JTextField(15);
              panel.add(hostField);
              panel.add(new JLabel("Port"));
              portField = new JTextField(15);
              panel.add(portField);
              return panel;
         @Override
         protected RemoteLocation prepareLocation() {
              String host = hostField.getText();
              int port = 0;
              try {
                   String portText = portField.getText();
                   port = Integer.getInteger(portText);
              } catch (NumberFormatException e) {
                   e.printStackTrace();
              RemoteLocation location = new RemoteLocation(host, port);
              return location;
    }Code for RemoteLocation:
    public class RemoteLocation {
         private String host;
         private int port;
         public RemoteLocation() {
              super();
         public RemoteLocation(String host, int port) {
              super();
              this.host = host;
              this.port = port;
         public String getHost() {
              return host;
         public void setHost(String host) {
              this.host = host;
         public int getPort() {
              return port;
         public void setPort(int port) {
              this.port = port;
    }Code snippet for dialog usage in local client implementation:
    final ChooseLocationDialog<String> dialog = new ChooseLocalFileDialog();
    dialog.setVisible(true);
    location = dialog.getDatabaseLocation();
    String filePath = location;Code snippet for dialog usage in network client implementation:
    final ChooseLocationDialog<RemoteLocation> dialog = new ChooseRemoteLocationDialog();
    dialog.setVisible(true);
    RemoteLocation location = dialog.getDatabaseLocation();Exception that I'm getting:
    Exception occurred during event dispatching:
    java.lang.NullPointerException
         at suncertify.client.gui.dialog.ChooseRemoteLocationDialog.prepareLocation(ChooseRemoteLocationDialog.java:42)
         at suncertify.client.gui.dialog.ChooseRemoteLocationDialog.prepareLocation(ChooseRemoteLocationDialog.java:1)
         at suncertify.client.gui.dialog.ChooseLocationDialog$SelectLocationAction.actionPerformed(ChooseLocationDialog.java:87)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
         at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
         at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
         at java.awt.Component.processMouseEvent(Component.java:6134)
         at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
         at java.awt.Component.processEvent(Component.java:5899)
         at java.awt.Container.processEvent(Container.java:2023)
         at java.awt.Component.dispatchEventImpl(Component.java:4501)
         at java.awt.Container.dispatchEventImpl(Container.java:2081)
         at java.awt.Component.dispatchEvent(Component.java:4331)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4301)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3965)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3895)
         at java.awt.Container.dispatchEventImpl(Container.java:2067)
         at java.awt.Window.dispatchEventImpl(Window.java:2458)
         at java.awt.Component.dispatchEvent(Component.java:4331)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
         at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
         at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:178)
         at java.awt.Dialog$1.run(Dialog.java:1046)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
         at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)java version "1.6.0"
    OpenJDK Runtime Environment (build 1.6.0-b09)
    OpenJDK Client VM (build 1.6.0-b09, mixed mode, sharing)
    OS: Ubuntu 8.04
    Appreciate any help.
    Thanks.
    Edited by: spyboost on Jul 24, 2008 5:38 PM

    What a silly error! I have to call Integer.parseInt instead of getInt. Integer.getInt tries to find a system property. A small misprint, but a huge amount of time to debug. I always use parseInt method and couldn't even notice that silly misprint. Sometimes it's useful to see the trees instead of whole forest :)
    It works perfectly. Sorry for disturbing.

  • JButton on XP non-modal Jdialog doen't work.

    I recently upgraded from 1.3 to 1.4 while upgrading my OS from NT 4.0 to XP.
    In a stand-alone application I have non-modal JDialog's that are launched as threads so that I can have multiple instances of them running simultaneously. There are JButton's on the JDialog's which no longer respond to any mouse events even though I can execute them via the keyboard using the tab and enter keys. They work just fine under 1.3 or if I make them modal.
    Any thoughts?

    Hello,
    Issue is-
    There are JButton's on the JDialog's which no longer respond to any mouse events even though I can execute them via the keyboard using the tab and enter keys. They work just fine if I make them modal.
    Plz suggest

  • JOptionPane and JDialog

    Hi guys,
    I've been scooting around the net trying to find an answer to this problem. Basically I have a JDialog that users enter registration details. If they haven't completed all fields or if the password confirmation is wrong then a JOptionPane.showMessageDialog appears telling users what has happened. However if they were to then click ok in the OptionPane it closes both the option pane and the original Dialog window. Have you guys any idea?
    A code snippet below:
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    public class Register extends JDialog implements ActionListener {
         //declare components
         JLabel lblHeading;
         JLabel lblUserName;
         JLabel lblUserPwd;
         JLabel lblCnfUserPwd;
         JLabel lblFrstName;
         JLabel lblLstName;
         JLabel lblAge;
         JLabel lblEmpId;
         JLabel lblSex;
         JLabel lblEmail;
         String usrName;
         String strUsrPwd;
         String strCnfPwd;
         String frstName;
         String lstName;
         String age;
         String empid;
         String email;
         String sex;
         Socket toServer;
         ObjectInputStream streamFromServer;
         PrintStream streamToServer;
         JComboBox listSex;
         JTextField txtUserName;
         JPasswordField txtUsrPwd;
         JPasswordField txtCnfUsrPwd;
         JTextField txtFrstName;
         JTextField txtLstName;
         JTextField txtAge;
         JTextField txtEmpId;
         JTextField txtEmail;
         Font f;
         Color r;
         JButton btnSubmit;
         JButton btnCancel;
         public Register() {
              this.setTitle("Registration Form");
            JPanel panel=new JPanel();
              //apply the layout
               panel.setLayout(new GridBagLayout());
               GridBagConstraints gbCons=new GridBagConstraints();
              //place the components
              gbCons.gridx=0;
              gbCons.gridy=0;
              lblHeading=new JLabel("Please register below");
               Font f = new Font("Monospaced" , Font.BOLD , 12);
              lblHeading.setFont(f);
              Color c=new Color(0,200,0);
              lblHeading.setForeground(new Color(131,25,38));
              lblHeading.setVerticalAlignment(SwingConstants.TOP);
              gbCons.anchor=GridBagConstraints.EAST;
              panel.add(lblHeading, gbCons);
              gbCons.gridx = 0;
              gbCons.gridy = 1;
              lblUserName = new JLabel("Enter Username");
              gbCons.anchor=GridBagConstraints.WEST;
              panel.add(lblUserName, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=1;
              txtUserName=new JTextField(15);
              panel.add(txtUserName, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=2;
              lblUserPwd=new JLabel("Enter Password ");
              panel.add(lblUserPwd, gbCons);
              gbCons.gridx = 1;
              gbCons.gridy = 2;
              txtUsrPwd = new JPasswordField(15);
              panel.add(txtUsrPwd, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=3;
              lblCnfUserPwd=new JLabel("Confirm Password ");
              panel.add(lblCnfUserPwd, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=3;
              txtCnfUsrPwd=new JPasswordField(15);
              panel.add(txtCnfUsrPwd, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=4;
              lblEmpId=new JLabel("Employee ID");
              panel.add(lblEmpId, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=4;
              txtEmpId=new JTextField(15);
              panel.add(txtEmpId, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=5;
              lblFrstName=new JLabel("First Name");
              panel.add(lblFrstName, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=5;
              txtFrstName=new JTextField(15);
              panel.add(txtFrstName, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=6;
              lblLstName=new JLabel("Last Name");
              panel.add(lblLstName, gbCons);
              gbCons.gridx = 1;
              gbCons.gridy = 6;
              txtLstName=new JTextField(15);
              panel.add(txtLstName, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=7;
              lblAge=new JLabel("Age");
              panel.add(lblAge, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=7;
              txtAge=new JTextField(3);
              panel.add(txtAge, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=8;
              lblEmail=new JLabel("Email address");
              panel.add(lblEmail, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=8;
              txtEmail=new JTextField(20);
              panel.add(txtEmail, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=9;
              lblSex=new JLabel("Sex");
              panel.add(lblSex, gbCons);
              gbCons.gridx = 1;
              gbCons.gridy=9;
              String [] sex= {"Male", "Female"};
              listSex = new JComboBox(sex);
              listSex.setSelectedIndex(0);
              panel.add(listSex, gbCons);
              JPanel btnPanel=new JPanel();
              btnSubmit=new JButton("Submit");
              btnPanel.add(btnSubmit);
              btnSubmit.addActionListener(this); //add listener to the Submit button
              btnCancel=new JButton("Cancel");
              btnPanel.add(btnCancel);
              btnCancel.addActionListener(this); //add listener to the Cancel button
              gbCons.gridx=0;
              gbCons.gridy=10;
              gbCons.anchor=GridBagConstraints.EAST;
              panel.add(btnPanel, gbCons);
              getContentPane().add(panel);
             setDefaultCloseOperation(DISPOSE_ON_CLOSE); //get rid of this window only on closing
              setVisible(true);
              setSize(450,400);
             }//end Register()
              public void actionPerformed(ActionEvent ae) {
                   Object o = ae.getSource(); //get the source of the event
                   if(o == btnCancel)
                        this.dispose();
                   if(o == btnSubmit){
                        usrName = txtUserName.getText();
                        strUsrPwd = txtUsrPwd.getText();
                        strCnfPwd = txtCnfUsrPwd.getText();
                        frstName = txtFrstName.getText();
                        lstName = txtLstName.getText();
                        age = txtAge.getText();
                        empid = txtEmpId.getText();
                        email = txtEmail.getText();
                        sex = (String)listSex.getItemAt(0);
                        if ((usrName.length() == 0) || (strUsrPwd.length() == 0) ||
                        (strCnfPwd.length() == 0) || (frstName.length() == 0) ||
                        (lstName.length() == 0) || (age.length() == 0) ||
                        (empid.length() == 0) || (email.length() == 0))
                        JOptionPane.showMessageDialog(null,
                        "One or more entry is empty. Please fill out all entries.", "Message", JOptionPane.ERROR_MESSAGE);
                        if ((!strUsrPwd.equals(strCnfPwd))){
                             JOptionPane.showMessageDialog(null,
                             "Passwords do not match. Please try again", "Message", JOptionPane.ERROR_MESSAGE);
                        Thanks,
    Chris

    try something like this:
    import java.awt.Dimension;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.event.ActionListener;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    public class About extends JDialog {
    /** Creates new form About */
    public About(JFrame parent) {
    super(parent,true);
    initComponents();
    pack();
    Rectangle parentBounds = parent.getBounds();
    Dimension size = getSize();
    // Center in the parent
    int x = Math.max(0, parentBounds.x + (parentBounds.width - size.width) / 2);
    int y = Math.max(0, parentBounds.y + (parentBounds.height - size.height) / 2);
    setLocation(new Point(x, y));
    and from the main dialog:
    new About(this).setVisible(true);

  • Mapping enter and esc to ok and cancel buttons

    Hi,
    Does java's fine API offer any method of mapping Enter and ESC to OK and Cancel buttons in a customized JDialog?
    The current way I'm doing it is through a brute force of adding a KeyListener to every component in the dialog box (in an automated way), is there another way?
    Any suggestions would be appreciated.

    Uh oh, should I be scared because he knows more about
    Swing than just about anyone?
    Yes. Because if you really get stuck then he won't help you and then you are doomed.
    If anybody was rude it was him, and if anybody is an
    idiot it's you. See how easy it is to make claims
    without providing any reasons or rationale?Reasons and rationale have been provided but I guess you didn't grasp them the first go around so here goes.
    1) You were impatient
    You waited 30 minutes before whining and bumping. That is impatient. Nobody is being paid to deliver answers to you.
    2) You posted in the wrong forum.
    This is not the Swing forum is it? No it is not.
    3) You should learn to search
    If you had searched for even up to 15 minutes (and you wouldn't have needed this long) then you would have had your answer in half the time. Searching saves YOU time.
    4) You were rude
    When the facts (and please note the use of the word "fact" not personal opinion) above were pointed out to you then you were rude.
    Finally the "you are an idiot" problem. I will give you this is the most subjective of the lot although given that you cannot dispute ANY of the above facts (although you seem to be trying and that's helping to make the case that you're quite the idiot) that's really not saying much.
    However, it seems to me that if Person A wants the assistance of Person B (who is a valuable resource of information for person A and others) it does not seem wise for Person A to be rude to person B. So in the case of Person A who is rude to Person B who they are relying on as a free resource we can make the assertion that Person A is an idiot.
    In case you couldn't follow that you are Person A.

  • Deciding what to do if user closes window(JDialog)

    I am drawing shapes- Rectangle, Ellipse, Trianlge...I have big class that implements JFrame and it is used to draw the draw the shapes on the its content pane. Inside this class, I have an inner class that draws a custom JDialog frame. A user selects a shape from a MenuItem and the cuztom dialog frame pops up. This inner cuztom frame basically has textfields for user to enter specifications and it has a button for user to press if he/she finishes enterring the data. So user enters data in the inner frame and clicks on enter, then the Bigger(Outer) class draws the shape.
    The problem is Even if the user clicks on close to close to the custom dialog, the shape is drawn. This is what I want to control. The Shape should only be drawn if the user clicks on enter.
    Couls some guys offer help???
    This is the code in the Outer Class. It calls the inner class so that the custom frame is popped up
    if(e.getActionCommand().equalsIgnoreCase("Rectangle")) {
                  showDialog() ;
                  list.myList.add(new Rectangle( x, y, w, h, x3, y3, Fill, Outline)) ;
                  model.addElement((list.myList.size()-1) + ": Rectangle ");
                  repaint() ;
    This is the inner class, but inside a method, so that I can call it in the outer class
    public void showDialog() {
             class GetName extends JDialog 
               JPanel textF = new JPanel(new GridLayout(0,1)) ;
               JPanel labelF = new JPanel(new GridLayout(0,1)) ;
               JLabel XL1 = new JLabel("Add Xpos/X1") ; // the rest deleted because of space
               // the rest deleted because of space
               JFormattedTextField XT1 = new JFormattedTextField(new Integer("100"));
               public GetName() 
                 setModal(true); 
                 Container cont = getContentPane() ;
                //I have labels here but deleted them
                 //because of the size limit to send here
              lebalF.addXL1) ; // the rest deleted because of space
                 textF.add(XT1) ;
                 cont.add(labelF, BorderLayout.CENTER) ;
                 cont.add(textF, BorderLayout.LINE_END) ;
                 JButton mybutt = new JButton("DrawShape"); 
                 mybutt.addActionListener(new ActionListener(){ 
                 public void actionPerformed(ActionEvent e){
                     x = Integer.parseInt(XT1.getText()) ;
                     y = Integer.parseInt(XT2.getText() ) ;
                     w = Integer.parseInt(XT3.getText() ) ;
                     ih = Integer.parseInt(YT1.getText() ) ;
                     x3 = Integer.parseInt(YT2.getText() ) ;
                     y3 = Integer.parseInt(YT3.getText() ) ;
                     // some deleted because of space
                     if(FilText.getText().equals("white"))       {Fill = Color.white;  }
                     else if(FilText.getText().equals("black"))  {Fill = Color.black;  }
                     else if(FilText.getText().equals("magenta")){Fill = Color.magenta;}
              // some deleted because of space
                     if(OutText.getText().equals("white"))       {Outline = Color.white;  }
                     else if(OutText.getText().equals("black"))  {Outline = Color.black;  }
                     else if(OutText.getText().equals("cyan"))   {Outline = Color.cyan;   }
                     dispose();}}); 
                 cont.add(mybutt, BorderLayout.SOUTH) ;
                 pack(); 
                 setVisible(true); 
             } //End of internal class GetName
             new GetName();
         } //End of Public Method showTriDialog

    My problem is solved.
    I used a boolean variable and test : if(e.getSource() instanceof JButton && (JButton)e.getSource() == mybutt), then my boolean is set to true. So before I draw, i test of the boolean variable to see if it is true(meaning the button was clicked), if the boolean returns false, i skip the code that draws.
    Thanks for response anyway.
    //This code is in the inner class
    if(e.getSource() instanceof JButton && (JButton)e.getSource() == mybutt) {
                      eventCheck = true ; //Check if user clicked on the button or closed the window
    //This one in the outer class
    public void actionPerformed(ActionEvent e)  {
               if(e.getActionCommand().equalsIgnoreCase("Ellipse")) {
                  showDialog() ;
                  if(eventCheck == true) {
                  list.myList.add(new Ellipse( x, y, w, h, x3, y3, Fill, Outline)) ;
                  model.addElement((list.myList.size()-1) + ": Ellipse ");
                  repaint() ;
                  eventCheck = false ;
                else return ;
              }

  • Calling a function through JDialog

    Hi all,
    The title might be a bit confusing, but the topic is about the following:
    I've got a JFrame as the main application. From the main application a JDialog gets called when you want to see more about an item in the JFrame.
    Because I want to collect all clicked information in the JDialog(so you can see what you've click before) I want to have the old JDialog with his current information + the new information at the moment you click on a other item.
    Example:
    JFrame mainFrame = The_CollectorApp.getApplication().getMainFrame();
    gameInfoBox = new The_CollectorCollectionDialog(mainFrame, tempGame, "game");
    gameInfoBox.setLocationRelativeTo(mainFrame);
    The_CollectorApp.getApplication().show(gameInfoBox);
    For opening a new JDialog with the game content. Now when you click on an other game, I want this gameInfoBox been showed (easy, just enter the last line only ), but I also want to pass the new Information to this JDialog.
    In the CollectionDialog.java is a function called AddItem(), so I want to call this function from the main when the JDialog has already been made.
    With a normal object gameInfoBox.addItem() would be enough, how to do this trick with this setup?

    Sounds like a bit of re-architecting might be in order. I haven't bothered deciphering your description of the flows, but the very fact that UI widgets are apparently trying to affect what other UI widgets are showing tells me you need something like MVC to keep things under control. Have a look into that pattern, MVC

  • Subclass of abstract JDialog - NullPointerException

    Hello!
    I wanted to make an abstract subclass of JDialog that will handle a few things that are common to several of the dialogs in my program. Things like creating and setting up the Ok/Cancel buttons, handling the case where the user closes the dialog with the red X as though they clicked Cancel, etc. The method that is called when the Ok button is clicked is abstract and is supposed to be implemented by the subclasses.
    The problem is, when the subclass implements that ok() method and tries to access one of its own instance variables (a JTextField), it throws a NullPointerException. I'm certain this JTextField instance was created, because it was added to the dialog's content pane; I can see it and type text into it. The reference is also visible across method calls after it's created. But when the Ok button is clicked and the method tries to access it, it's always null for some reason that I can't figure out. I tried refactoring the inner classes to their own class files, but it gave me the same results.
    Here's a SSCCE. I tried to keep it as short as possible. The comments should highlight the relevant parts of the code. I can do this a few other ways, so I'm not really looking for a JDialog tutorial or anything. I'm mainly just curious why this doesn't work. Can anyone tell me what I'm doing wrong here?
    import java.awt.BorderLayout;
    import java.awt.EventQueue;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    public class Main {
         // This creates and shows JFrame with a button.  Clicking the
         // button displays a SomeDialog instance that prompts the user
         // to enter a String value.
         public static void main(String[] args) {
              final JFrame frame = new JFrame();
              final JButton btnShowDialog = new JButton("Show Dialog");
              frame.setSize(340,280);
              frame.setLocationRelativeTo(null);
              frame.getContentPane().add(btnShowDialog, BorderLayout.SOUTH);
              frame.addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        frame.dispose();
              btnShowDialog.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        SomeDialog dlg = new SomeDialog(frame);
                        dlg.setVisible(true);
                        if (dlg.isCancelled() == true) {
                             System.out.println("Cancelled");
                        } else {
                             String value = dlg.getValue();
                             System.out.println("Value: "+value);
              EventQueue.invokeLater(new Runnable() {
                   public void run() {
                        frame.setVisible(true);
         // This is intended to provide some basic dialog behavior.
         private static abstract class AbstractDialog extends JDialog {
              private boolean cancelled = false;
              private JButton btnOk = new JButton("Ok");
              private JButton btnCancel = new JButton("Cancel");
              protected abstract void initComponents();
              protected abstract void ok();
              public AbstractDialog(JFrame parent) {
                   super(parent, true);
                   addWindowListener(new WindowAdapter() {
                        public void windowClosing(WindowEvent e) {
                             cancelled = true;
                   // This call to initComponents() should cause the subclass to
                   // create its txtValue instance long before the Ok button is
                   // clicked.
                   initComponents();
                   pack();
                   setLocationRelativeTo(parent);
              protected JPanel buildButtons() {
                   btnOk.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             cancelled = false;
                             ok();
                   btnCancel.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             cancelled = true;
                             dispose();
                   JPanel pnlGrid = new JPanel(new GridLayout(1,2,5,5));
                   pnlGrid.add(btnOk);
                   pnlGrid.add(btnCancel);
                   return pnlGrid;
              public boolean isCancelled() {
                   return cancelled;
         // This implements AbstractDialog to prompt the user for a
         // String value.
         private static class SomeDialog extends AbstractDialog {
              // txtValue is a class-level instance in the subclass.
              private JTextField txtValue = null;
              private String value = null;
              public SomeDialog(JFrame parent) {
                   super(parent);
              @Override
              protected void initComponents() {
                   // The class-level JTextField instance is created here.
                   // I would expect this instance to persist throughout the
                   // life of this dialog.
                   txtValue = new JTextField();
                   getContentPane().add(txtValue, BorderLayout.NORTH);
                   getContentPane().add(buildButtons(), BorderLayout.SOUTH);
                   // This check is to make sure that the txtValue reference
                   // is non-null across method calls.  It always prints
                   // "Not null"
                   checkNull();
              private void checkNull() {
                   if (txtValue == null) {
                        System.out.println("Null");
                   } else {
                        System.out.println("Not null");
              @Override
              protected void ok() {
                   // *** The NullPointerException is thrown at this line: ***
                   value = txtValue.getText();
                   dispose();
              public String getValue() {
                   return value;
    }

    The problem is that the text field is created, but then you set it to null in the derived class. This may seem counter-intuitive at first, but remember that the super-class constructor always runs first, and then additional initialization takes place in the derived class. You have the following:
              // txtValue is a class-level instance in the subclass.
              private JTextField txtValue = null;
              private String value = null;
              public SomeDialog(JFrame parent) {
                   super(parent);
              }First super(parent) is called, and your text field is created through the call to initComponents(). Then the initialization in the SomeDialog class takes place, and there you set txtValue to null.
    There are two bad practices contributing to this confusing situation:
    1. You are calling an overridden method from a constructor. If used carefully this is not a problem, if used carelessly you end up wasting hours tracking down mysterious bugs (like this one).
    2. You are explicitly initializing instance variables to null. This is always completely unnecessary, and in this case it actually causes your program to fail.
    In short, to get rid of this problem, do not set txtValue explicitly to null:
              // txtValue is a class-level instance in the subclass.
              private JTextField txtValue;
              private String value;
              public SomeDialog(JFrame parent) {
                   super(parent);
              }

Maybe you are looking for

  • OIM - Email notification to a specific user based on a dynamic rule

    Hello, After creation of account in a particular target resource I need to send an email to a specific user based on the location of the user (e.g area admin). In the notification tab of process tasks, I see only "Assignee", "Requestor", "User", "Use

  • My MacBook Pro is running very slow with the wheel constantly spinning.  Can anyone please help?!?!

    My MacBook is running very slow and the wheel is constantly spinning.  It's not just using the internet as it takes forever to start, open programs, etc.  It is even taking me a long time to type in this question as the spinning wheel keeps coming up

  • LV 8.0 PDA "unknown error"

    Whenever i try to build this VI, I get an unknown error prompt. I have attached the VI's for reference. Attachments: Filedialog.vi ‏20 KB y2kserflnme.vi ‏29 KB

  • MIRO- How to check the Status of Invoice Image in Document

    Hi, Can anyone help me extract a report from SAP to identify the list of documents (posted in MIRO) on which Invoice Images are attached? Is there any T-codes or programs? This is required to identify which all documents have invoice images & which a

  • Uccx demo license disappears after reboot

    hi. im trying to install uccx 8.5 in vmware for lab purposes. when i install the demo license included in the DVD, it works out fine. however when i reload the VM and try to log back to uccx, it says that there is no license installed. when i try to