在我的程序的一部分中,我使用JOptionPane来询问用户他们是否确定他将做什么.但是我不想让用户每次尝试都要求这样我喜欢使用
android中的一些对话框的功能,这些对话框带有“不要再问”,但不知道如何在我的程序中实现它,有人在这里你可以帮助我吗?
(应该有一个西班牙语StackOverflow)
这是我的代码
(应该有一个西班牙语StackOverflow)
这是我的代码
if (jCheckBox2.isSelected() && jCheckBox1.isSelected()){ JOptionPane.showConfirmDialog(null,"This action can cause problems,want to do it?"); //here must be something to never ask again this }
解决方法
基本思想是利用message参数实际上可以是Component的事实.然后问题归结为检查用户是否选择了“不要再问我”选项,存储并重新使用它
就像是…
import java.awt.BorderLayout; import java.awt.Component; import java.awt.FlowLayout; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.Properties; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; public class DontAskMeAgainPanel extends JPanel { private JCheckBox dontAskMeAgain; public DontAskMeAgainPanel(Object message) { setLayout(new BorderLayout()); if (message instanceof Component) { add((Component) message); } else if (message != null) { add(new JLabel(message.toString())); } dontAskMeAgain = new JCheckBox("Don't ask me again"); JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); panel.add(dontAskMeAgain); add(panel,BorderLayout.SOUTH); } public boolean dontAskMeAgain() { return dontAskMeAgain.isSelected(); } private static Properties settings; protected static void loadProperties() { if (settings != null) { settings = new Properties(); File source = new File("..."); if (source.exists()) { try (Reader r = new FileReader(source)) { settings.load(r); } catch (IOException exp) { exp.printStackTrace(); } } } } protected static void saveProperties() { if (settings != null) { settings = new Properties(); File source = new File("..."); try (Writer w = new FileWriter(source)) { settings.store(w,"Don't prompt for settings"); } catch (IOException exp) { exp.printStackTrace(); } } } public static int showConfirmDialog(Component parent,Object message,String key) { loadProperties(); int result = JOptionPane.NO_OPTION; if (settings.containsKey(key + ".prompt") && !Boolean.parseBoolean(settings.getProperty(key + ".value"))) { result = Integer.parseInt(settings.getProperty(key + ".value")); } else { DontAskMeAgainPanel panel = new DontAskMeAgainPanel(message); result = JOptionPane.showConfirmDialog(parent,panel); if (panel.dontAskMeAgain()) { settings.put(key + ".prompt","false"); settings.put(key + ".value",Integer.toString(result)); saveProperties(); } } return result; } }
作为一个基本出发点.为简单起见,我使用了Properties作为后备存储,你可以使用数据库或其他持久化方法(Preferences,XML等)
然后你就可以使用它……
int result = DontAskMeAgainPanel.showConfirmDialog(null,"This is annoying","Annoying"); System.out.println("You selected " + result); result = DontAskMeAgainPanel.showConfirmDialog(null,"Annoying"); System.out.println("Then you selected " + result);
如果在第一个提示中选择“不要再问我”,则第二个调用将返回先前选择的值
现在,在某个地方,你可能希望有能力扭转这些决定;)