2012-06-09 32 views
5

Điều này có thể là một điều rất đơn giản mà tôi đang nhìn, nhưng tôi dường như không thể tìm ra nó.JOptionPane.showMessageDialog đợi cho đến khi OK được nhấp?

tôi có phương pháp sau đó cập nhật một 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; 
      } 
     } 
    } 

Tuy nhiên, tôi không muốn isOpenDialog boolean được thiết lập là false cho đến khi nút OK trên hộp thoại thông báo được nhấn, bởi vì nếu người dùng nhấn enter nó sẽ kích hoạt một sự kiện KeyListener trên một trường văn bản và nó kích hoạt lại toàn bộ khối mã nếu nó được đặt thành false.

Một phần của mã KeyListener được hiển thị dưới đây:

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(); 
      } 
     } 
    } 
} 

Liệu JOptionPane.showMessageDialog() có một số loại cơ chế có thể ngăn chặn thực hiện các dòng tiếp theo cho đến khi nút OK được nhấn? Cảm ơn bạn.

Trả lời

10

Các JOptionPane tạo ra một hộp thoại modal và do đó, dòng vượt ra ngoài nó sẽ do thiết kế không được gọi cho đến khi hộp thoại đã được xử lý (hoặc một trong các nút đã được đẩy hoặc nút menu đóng đã được nhấn).

Quan trọng hơn, bạn không nên sử dụng KeyListener cho loại điều này. Nếu bạn muốn có một JTextField nghe cho báo chí của phím enter, thêm một ActionListener cho nó.

-3

Hãy thử điều này,

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

hoạt động Swing (chẳng hạn như mở một hộp thoại) nên xảy ra trong EventDispatchThread –

+3

Đồng ý với tiếng ồn: loại mã này không thuộc về trong một ứng dụng Swing vì nó hoàn toàn bỏ qua các quy tắc luồng Swing. –

+0

Ngay cả khi tôi đồng ý rằng thao tác Swing phải xảy ra trong Event Dispatcher Thread, vì phương thức main() trong lịch trình ứng dụng swing xây dựng GUI trong Thread Dispatcher Thread và thoát. nhưng Quy tắc được mô tả trong sách là vì thế giới lý tưởng, và đôi khi người ta cần phải là một người nổi dậy để hoàn thành công việc. –

7

Một công việc dễ dàng xung quanh để đáp ứng nhu cầu của bạn là sử dụng showConfirmDialog(...), trên showMessageDialog(), điều này cho phép bạn lấy dữ liệu đầu vào từ người dùng và sau đó tiến hành tương tự. Đừng có nhìn vào chương trình ví dụ này, để làm rõ :-)

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); 
    } 
} 
Các vấn đề liên quan