【发布时间】:2016-02-23 18:21:22
【问题描述】:
我正在使用 IntelliJ IDEA 创建一个表单应用程序。到目前为止,我已经有了 UI,一切都按我的意愿工作。除了:我想在退出时保存文本字段的内容并在启动时加载它们。
我是表单方面的新手,对 Java 不是很熟悉,但我认为我已经非常接近解决方案了。我不知道我的想法错在哪里,但首先是一些代码:
...
/**
* Created by on 22.02.2016.
*/
public class MainWindow {
public MainWindow() {
...
some listeners
...
}
private void logToInfoArea(String text){
...
}
private void logToResultArea(String text){
...
}
private void saveConfig(){
FileOutputStream out;
try {
out = new FileOutputStream("appConf");
appConf = new Properties();
appConf.setProperty("pathQuery", pathQuery.getText());
appConf.setProperty("pathMapping", pathMapping.getText());
appConf.setProperty("pathOntology", pathOntology.getText());
appConf.setProperty("queryText", queryText.getText());
appConf.store(out, "[update]");
out.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
public void run() throws Exception {
...
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Prototyp");
frame.setContentPane(new MainWindow().mainfield);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent e) {
//loading of the config should be here
/* FileInputStream in;
System.out.println("UI loaded.");
defaultConf = new Properties();
try {
in = new FileInputStream("defaultConf");
defaultConf.load(in);
in.close();
} catch (Exception e1) {
e1.printStackTrace();
}
Properties appConf = new Properties(defaultConf);
try {
in = new FileInputStream("appConf");
appConf.load(in);
in.close();
} catch (Exception e1) {
e1.printStackTrace();
}*/
}
@Override
public void windowClosing(WindowEvent e) {
System.out.println("UI closing.");
saveConfig();
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private static Properties defaultConf;
private static Properties appConf;
private JButton execute;
private JPanel mainfield;
private JTextField pathQuery;
private JTextField pathMapping;
private JTextField pathOntology;
private JRadioButton radQueryText;
private JRadioButton radQueryFile;
private JTextArea consoleLog;
private JTextArea result;
private JTextArea queryText;
}
如您所见,我知道该怎么做,但我的问题是,如何从 WindowListener 引发的方法“windowOpened”和“windowClosing”访问创建的框架?我知道我处于静态上下文中,并且我的所有组件都是非静态的,但我不知道如何到达触发侦听器的实例。因为如果我获得对实例的访问权限,我想我可以提出一些问题。喜欢:
saveConfig(instance);
然后在saveConfig方法里面:
appConf.setProperty("pathMapping", instance.pathMapping.getText());
对吗?
非常感谢您的帮助!
【问题讨论】:
标签: java swing intellij-idea properties windowlistener