swing从不同的类获取数据,而不重新打开java中的JFrame?
我课程中的两门课给我带来了麻烦。第一个打开了一个JFrame。第二个更新一个数据库上的数据。属性文件。JFrame中有一个带有JTextAreas的面板和一个“保存更改”按钮当按下该按钮时,我从第二个类调用一个方法,但要做到这一点,我必须
firstClass x = new firstClass();
因此,当按下按钮时,文件会更新,但会打开一个新的JFrame。我很确定创建实例x
是造成这种情况的原因,但我不知道不这样做还有什么其他方法可以实现这一点
第一类:
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);
}
第二类:
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();
}
# 1 楼答案
你在越界,谁在控制这里,谁对什么负责
将责任区分开,例如,你的
SecondClass
只(真正)负责从用户那里收集数据,因为你的FirstClass
实际上是知道应该使用哪些数据的人,所以SecondClass
不应该关心这样想吧,
<>而不是使用单独的帧(参见The Use of Multiple JFrames, Good/Bad Practice?由于一些不应该的原因),考虑使用某个因子的模态^ {< CD6>}。SecondClass
是服务员,它接受订单并将信息提供给FirstClass
是厨师,他知道如何完成订单和准备饭菜对话框应该从用户那里收集信息,当它关闭时,根据关闭的方式,使用调用者来处理和处理结果
有关更多详细信息,请参见How to Make Dialogs
更新
好的,那么您似乎想要的是某种“配置”管理器,它能够存储/检索值
配置管理器将知道如何读取和写入属性,而不关心其他任何事情,它有一个明确定义的边界。然后,您需要要求配置管理器根据需要读取或写入值
这个例子非常严厉。。。每次读取值时,它都会从磁盘加载内容,每次设置值时,它都会存储到磁盘
你可以将这些值缓存在内存中,在第一次加载时读取一次,然后在将来某个时候写入,但我希望你还是能理解这个想法