有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JOptionPane如何禁用X?

如果用户单击右上角的X,我不希望发生任何事情。实现这一点的代码行是什么

Object [] options1 = {"Go Back", "Accept"};
 int a3 =JOptionPane.showOptionDialog(null,"Mean arterial pressure restored.\nReassess all vitals STAT.", "Title", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options1, options1[0]);

 if(a3 == JOptionPane.CLOSED_OPTION)
{
 //what should i put here? if user X out, I want no response (DO_NOTHING_ON_CLOSE)
 }

 if(a3 == JOptionPane.YES_OPTION)
{ 
// doing something else
 }

if (a3 == JOptionPane.NO_OPTION)
{
//doing something else
}

我试过a3之类的。setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); 但我得到一个错误int不能被解引用


共 (2) 个答案

  1. # 1 楼答案

    这段代码可能会起作用(您可以运行代码来测试它):

    import javax.swing.*;  
    import java.awt.*;  
    import java.awt.event.*;  
    class Testing  
    {  
      public void buildGUI()  
      {  
        JFrame.setDefaultLookAndFeelDecorated(true);  
        JFrame f = new JFrame();  
        f.setResizable(false);  
        removeMinMaxClose(f);  
        JPanel p = new JPanel(new GridBagLayout());  
        JButton btn = new JButton("Exit");  
        p.add(btn,new GridBagConstraints());  
        f.getContentPane().add(p);  
        f.setSize(400,300);  
        f.setLocationRelativeTo(null);  
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
        f.setVisible(true);  
        btn.addActionListener(new ActionListener(){  
          public void actionPerformed(ActionEvent ae){  
            System.exit(0);  
          }  
        });  
      }  
      public void removeMinMaxClose(Component comp)  
      {  
        if(comp instanceof AbstractButton)  
        {  
          comp.getParent().remove(comp);  
        }  
        if (comp instanceof Container)  
        {  
          Component[] comps = ((Container)comp).getComponents();  
          for(int x = 0, y = comps.length; x < y; x++)  
          {  
            removeMinMaxClose(comps[x]);  
          }  
        }  
      }  
      public static void main(String[] args)  
      {  
        SwingUtilities.invokeLater(new Runnable(){  
          public void run(){  
            new Testing().buildGUI();  
          }  
        });  
      }  
    }  
    
  2. # 2 楼答案

    那么这种极简主义的方法呢:

    Object [] options1 = {"Go Back", "Accept"};
    
    do {
        a3 = JOptionPane.showOptionDialog(null,"Mean arterial pressure restored.\nReassess all vitals STAT.", "Title", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options1, options1[0]);
    } while(a3 == JOptionPane.CLOSED_OPTION);
    
    if (a3 == JOptionPane.YES_OPTION) { 
        // doing something else
    }
    
    if (a3 == JOptionPane.NO_OPTION) {
        //doing something else
    }