帮我写段代码,实现关闭程序再次打开时记忆上次的位置和链接
时间: 2024-03-13 22:48:15 浏览: 172
好的,下面是一个简单的示例代码,可以实现记录上次窗口位置和链接的功能:
```java
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class MainFrame extends JFrame {
private static final String CONFIG_FILE = "config.txt";
private static final int DEFAULT_X = 100;
private static final int DEFAULT_Y = 100;
private static final int DEFAULT_WIDTH = 800;
private static final int DEFAULT_HEIGHT = 600;
private JTextField urlField;
public MainFrame() {
// 初始化窗口大小和位置
int x = DEFAULT_X;
int y = DEFAULT_Y;
int width = DEFAULT_WIDTH;
int height = DEFAULT_HEIGHT;
try {
// 读取配置文件中的位置和大小信息
BufferedReader reader = new BufferedReader(new FileReader(CONFIG_FILE));
String line = reader.readLine();
if (line != null) {
String[] parts = line.split(",");
x = Integer.parseInt(parts[0]);
y = Integer.parseInt(parts[1]);
width = Integer.parseInt(parts[2]);
height = Integer.parseInt(parts[3]);
}
reader.close();
} catch (IOException e) {
// 配置文件不存在或读取失败,使用默认值
}
// 设置窗口位置和大小
setBounds(x, y, width, height);
// 添加组件
JPanel panel = new JPanel(new BorderLayout());
JLabel label = new JLabel("URL:");
urlField = new JTextField();
JButton button = new JButton("打开链接");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String url = urlField.getText();
openUrl(url);
}
});
panel.add(label, BorderLayout.WEST);
panel.add(urlField, BorderLayout.CENTER);
panel.add(button, BorderLayout.EAST);
getContentPane().add(panel);
// 添加窗口关闭事件监听器
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
saveConfig();
System.exit(0);
}
});
}
private void openUrl(String url) {
try {
Desktop.getDesktop().browse(new java.net.URI(url));
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "打开链接失败:" + e.getMessage());
}
}
private void saveConfig() {
try {
// 保存窗口位置和大小信息到配置文件
BufferedWriter writer = new BufferedWriter(new FileWriter(CONFIG_FILE));
writer.write(getX() + "," + getY() + "," + getWidth() + "," + getHeight());
writer.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(this, "保存配置文件失败:" + e.getMessage());
}
}
public static void main(String[] args) {
MainFrame frame = new MainFrame();
frame.setVisible(true);
}
}
```
这段代码实现了一个简单的窗口,包含一个文本框和一个按钮,可以输入要打开的链接。当关闭程序时,会自动保存窗口的位置和大小信息到配置文件中。下次再打开程序时,会自动读取配置文件中的位置和大小信息,并将窗口恢复到上次关闭时的状态。
阅读全文