【发布时间】:2014-09-15 03:20:19
【问题描述】:
我的程序中有两个课程给我带来了麻烦。第一个打开一个 JFrame。第二个更新 .properties 文件上的数据。在 JFrame 中有一个带有 JTextAreas 的面板和一个“保存更改”按钮。当按下该按钮时,我从第二类调用一个方法,但要做到这一点,我必须firstClass x = new firstClass(); 所以当按下按钮时,文件会更新,但会打开一个新的 JFrame。我很确定创建实例 x 是造成这种情况的原因,但如果不这样做,我不知道有任何其他方法可以做到这一点。
第 1 类:
public class firstClass{
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
new firstClass();
}
});
}
JFrame go = new JFrame("firstClass");
JPanel panel = new JPanel();
JTextArea textArea = new JTextArea();
JButton savechanges = new JButton("Save");
public firstClass() {
panel.add(textArea);
panel.add(savechanges);
savechanges.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0){
secondClass f = new secondClass();
try {
f.UpdateData();
} catch (IOException e) {
e.printStackTrace();
}
}
});
go.add(panel);
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(750, 750);
go.setVisible(true);
}
第 2 类:
public class secondClass {
public static void main(String[] args) {
//creates properties file
}
public void UpdateData() throws IOException{
firstClass x = new firstClass(); // <-------------------------------
FileInputStream in = new FileInputStream("config.properties");
Properties props = new Properties();
props.load(in);
in.close();
FileOutputStream out = new FileOutputStream("config.properties");
props.setProperty("prop1", x.textArea.getText().toString());
props.store(out, null);
out.close();
}
【问题讨论】:
标签: java swing properties jframe instance