java - 从不同的类获取数据而不用在java中重新打开JFrame?

标签 java swing properties jframe instance

我的程序中的两个类给我带来了麻烦。第一个打开一个 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();

    }

最佳答案

你的目的是交叉的,谁是真正的控制者,谁对什么负责?

分隔职责范围,例如,您的 SecondClass 仅(真正)负责从用户收集数据,而您的 FirstClass 实际上是负责收集用户数据的人知道应该使用该数据,SecondClass 不应该关心...

这样想,SecondClass 是服务员,它接受订单并将该信息提供给 FirstClass,后者是厨师,知道如何做完成订单并准备饭菜...

不要使用单独的框架(请参阅The Use of Multiple JFrames, Good/Bad Practice?,因为某些原因您不应该这样做),请考虑使用某种kine的模态JDialog

对话框应该收集用户的信息,当它关闭时,根据它的关闭方式,使用调用者来处理和处理结果...

SecondClass secondClass = new SecondClass();
int reason = secondClass.showDialog();
if (reason == SAVE_RESULTS) {
    //... Get the data from the secondClass and save it...
}

参见How to Make Dialogs了解更多详情

已更新

好吧,所以您似乎想要的是某种能够存储/检索值的“配置”管理器。

配置管理器将知道如何读取和写入属性,并且不会关心其他任何事情,它有一个明确定义的边界。然后,您需要要求配置管理器根据需要读取或写入值...

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class TestConfig {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TestConfig();
            }
        });
    }

    JFrame go = new JFrame("firstClass");
    JPanel panel = new JPanel();
    JTextArea textArea = new JTextArea();
    JButton savechanges = new JButton("Save");

    public TestConfig() {
        panel.add(textArea);
        panel.add(savechanges);

        savechanges.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                try {
                    ConfigurationManager.INSTANCE.put("prop1", textArea.getText());
                } catch (IOException ex) {
                    JOptionPane.showMessageDialog(panel, "Failed to write properties", "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        go.add(panel);
        go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        go.setSize(750, 750);
        go.setVisible(true);

    }

    public enum ConfigurationManager {

        INSTANCE;

        protected Properties readProperties() throws IOException {
            Properties p = new Properties();
            try (FileInputStream fis = new FileInputStream("config.properties")) {
                p.load(fis);
            }
            return p;
        }

        public String get(String name) throws IOException {
            return readProperties().getProperty(name);
        }

        public void put(String key, String vaue) throws IOException {            
            Properties p =  readProperties();
            p.put(key, vaue);
            writeProperties(p);            
        }

        protected void writeProperties(Properties p) throws IOException {
            try (FileOutputStream fos = new FileOutputStream("config.properties")) {
                p.store(fos, "Config");
            }
        }            
    }
}

这个例子非常繁琐......每次读取一个值时,它都会从磁盘加载内容,每次设置值时,它都会存储到磁盘。

您可以将值缓存在内存中,在首次加载时读取一次并在将来的某个时间写入,但我希望您仍然明白这个想法

关于java - 从不同的类获取数据而不用在java中重新打开JFrame?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25840381/

相关文章:

java - java swing应用程序中的快速搜索?

java.lang.StringIndexOutOfBoundsException : String index out of range: -1

java - 清除JFrame的组件并添加新组件

java - Swing 中的属性列表 GUI 组件

java - xstream json : convert java. util.Properties 对象文字

javascript - 是否有一个 ES6 函数会返回一个包含属性更改的对象?

java - java中未找到文件text.properties

java - 尝试在跨度中查找文本元素

java - 没有硬编码值的外观和感觉

java - 在 Windows 中查看 tomcat 日志文件