2012-06-09 22 views
5

Esto podría ser algo muy simple que estoy pasando por alto, pero parece que no puedo resolverlo.JOptionPane.showMessageDialog ¿esperar hasta que se haga clic en Aceptar?

Tengo el siguiente método que actualiza un JTable:

class TableModel extends AbstractTableModel {  
     public void updateTable() { 
      try { 
       // update table here 
      ... 
    } catch (NullPointerException npe) { 
       isOpenDialog = true; 
       JOptionPane.showMessageDialog(null, "No active shares found on this IP!"); 
       isOpenDialog = false; 
      } 
     } 
    } 

Sin embargo, no quiero isOpenDialog booleano que se establece en false hasta que el botón OK en el diálogo de mensaje se presiona, porque si un usuario al presionar Enter se activará un evento KeyListener en un campo de texto y se activará ese bloque completo de código si está configurado en false.

parte del código KeyListener se muestra a continuación:

public class KeyReleased implements KeyListener { 
     ... 

    @Override 
    public void keyReleased(KeyEvent ke) { 
     if(txtIPField.getText().matches(IPADDRESS_PATTERN)) { 
      validIP = true; 
     } else { 
      validIP = false; 
     } 

     if (ke.getKeyCode() == KeyEvent.VK_ENTER) { 
      if (validIP && !isOpenDialog) { 
       updateTable(); 
      } 
     } 
    } 
} 

¿Se JOptionPane.showMessageDialog() tienen algún tipo de mecanismo que impide la ejecución de la línea siguiente hasta que se pulse el botón OK? Gracias.

Respuesta

10

El JOptionPane crea un cuadro de diálogo modal y por lo que la línea más allá Será por diseño no puede ser llamado hasta que el diálogo ha sido tratado (ya sea uno de los botones han sido empujados o la botón de menú cercano ha sido presionado).

Más importante aún, no debe utilizar KeyListener para este tipo de cosas. Si desea que JTextField escuche para presionar la tecla Enter, agregue un ActionListener a ella.

-3

Prueba de esto,

catch(NullPointerException ex){ 
    Thread t = new Thread(new Runnable(){ 

          public void run(){ 

            isOpenDialog = true; 

            JOptionPane.setMessageDialog(Title,Content); 
           } 
           }); 

    t.start(); 

    t.join(); // Join will make the thread wait for t to finish its run method, before 
        executing the below lines 

    isOpenDialog = false; 

    } 
+3

operaciones Swing (como la apertura de un cuadro de diálogo) debe suceder en el EventDispatchThread –

+3

acuerdo con el ruido: Este tipo de código no pertenecen en una aplicación Swing ya que ignora por completo las reglas de enhebrado Swing. –

+0

Incluso estoy de acuerdo en que la operación de Swing debe ocurrir en Event Dispatcher Thread, como método main() en la aplicación swing programa la construcción de la GUI en el Event Dispatcher Thread y se cierra. pero las reglas descritas en los libros son para el mundo ideal, y algunas veces uno debe ser un rebelde para realizar el trabajo. –

7

un trabajo fácil en torno a la habitación sus necesidades es el uso de showConfirmDialog(...), sobre showMessageDialog(), esto le permite tomar la entrada del usuario y luego proceder del mismo modo. No echar un vistazo a este programa de ejemplo, para la clarificación :-)

import javax.swing.*; 

public class JOptionExample 
{ 
    public static void main(String... args) 
    { 
     SwingUtilities.invokeLater(new Runnable() 
     { 
      public void run() 
      { 
       int selection = JOptionPane.showConfirmDialog(
           null 
         , "No active shares found on this IP!" 
         , "Selection : " 
         , JOptionPane.OK_CANCEL_OPTION 
         , JOptionPane.INFORMATION_MESSAGE); 
       System.out.println("I be written" + 
        " after you close, the JOptionPane");  
       if (selection == JOptionPane.OK_OPTION) 
       { 
        // Code to use when OK is PRESSED. 
        System.out.println("Selected Option is OK : " + selection); 
       } 
       else if (selection == JOptionPane.CANCEL_OPTION) 
       { 
        // Code to use when CANCEL is PRESSED. 
        System.out.println("Selected Option Is CANCEL : " + selection); 
       } 
      }   
     }); 
    } 
} 
1
You can get acces to the OK button if you create optionpanel and custom dialog. Here's an example of this kind of implementation: 

/* 
* To change this template, choose Tools | Templates 
* and open the template in the editor. 
*/ 

/** 
* 
* @author OZBORN 
*/ 
public class TestyDialog { 
    static JFrame okno; 
    static JPanel panel; 
    /** 
    * @param args the command line arguments 
    */ 

    public static void main(String[] args) { 
     zrobOkno(); 
     JButton przycisk =new JButton("Dialog"); 
     przycisk.setSize(200,200); 
     panel.add(przycisk,BorderLayout.CENTER); 
     panel.setCursor(null); 
     BufferedImage cursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB); 
     przycisk.setCursor(Toolkit.getDefaultToolkit().createCustomCursor(
          cursorImg, new Point(0, 0), "blank cursor")); 
     final JOptionPane optionPane = new JOptionPane(
       "U can close this dialog\n" 
       + "by pressing ok button, close frame button or by clicking outside of the dialog box.\n" 
       +"Every time there will be action defined in the windowLostFocus function" 
       + "Do you understand?", 
       JOptionPane.INFORMATION_MESSAGE, 
       JOptionPane.DEFAULT_OPTION); 

     System.out.println(optionPane.getComponentCount()); 
     przycisk.addActionListener(new ActionListener(){ 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       final JFrame aa=new JFrame(); 
       final JDialog dialog = new JDialog(aa,"Click a button",false); 
       ((JButton)((JPanel)optionPane.getComponents()[1]).getComponent(0)).addActionListener(new ActionListener() { 
        @Override 
        public void actionPerformed(ActionEvent e) { 
         aa.dispose(); 
        } 
       }); 
       dialog.setContentPane(optionPane); 
       dialog.pack(); 

       dialog.addWindowFocusListener(new WindowFocusListener() { 
        @Override 
        public void windowLostFocus(WindowEvent e) { 
         System.out.println("Zamykam");   
         aa.dispose(); 
        } 
        @Override public void windowGainedFocus(WindowEvent e) {} 
       }); 

       dialog.setVisible(true);  
      } 
     }); 
    } 
    public static void zrobOkno(){ 
     okno=new JFrame("Testy okno"); 
     okno.setLocationRelativeTo(null); 
     okno.setSize(200,200); 
     okno.setPreferredSize(new Dimension(200,200)); 
     okno.setVisible(true); 
     okno.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     panel=new JPanel(); 
     panel.setPreferredSize(new Dimension(200,200)); 
     panel.setLayout(new BorderLayout()); 
     okno.add(panel); 
    } 
} 
Cuestiones relacionadas