首页 > 解决方案 > 如何让 JFrame 存储数据而不刷新?

问题描述

即使在关闭 jframe 以打开单独的 jframe 之后,如何将信息存储在 jframe 中,以便在重新打开第一个 jframe 时仍然列出相同的信息?

所以基本上我有一个带有搜索按钮和配置文件按钮的 jFrame。查看配置文件按钮将您带到一个不同的 Jframe,其中存储了您的所有“搜索历史”。但是,每次您返回主页并再次打开配置文件时,配置文件都会刷新并再次开始。我希望按钮再次打开完全相同的窗口,而不是 GUI 的新窗口。我怎么做?

标签: javajframe

解决方案


如果我的问题是正确的,那么您需要的是secondFrame.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);

但是,不建议使用 2 个 JFrame。您可以使用 JDialog 代替您的“第二帧”。

此外,如果您在按钮的动作侦听器中对其进行初始化,则每次单击按钮时都将无法正常工作,它将创建一个新对话框。所以你必须先初始化它。看看这个例子:

package test;

import java.awt.BorderLayout;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class TestFrame extends JFrame {
    private JDialog secondFrame;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new TestFrame().setVisible(true);
        });
    }

    public TestFrame() {
        super("Frame");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        getContentPane().setLayout(new FlowLayout());
        initializeSecondFrame();

        JButton button = new JButton("Show \"Second Frame\".");
        button.addActionListener(e -> {
            secondFrame.setVisible(true);
        });
        getContentPane().add(button);
        setSize(300, 300);
    }

    private void initializeSecondFrame() {
        secondFrame = new JDialog(this);
        // When "X" button is presed, dialog does nothing.
        secondFrame.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
        secondFrame.getContentPane().setLayout(new FlowLayout());
        JTextField textField = new JTextField(10);
        secondFrame.getContentPane().add(textField);
        secondFrame.setSize(300, 300);
    }
}

该按钮所做的唯一事情是使对话框(已经启动)可见。现在,如果您在对话框(即 secondFrame)中编辑 TextField,然后将其关闭,然后再次按下按钮,文本字段将具有其文本。


推荐阅读