我正在编写一个 java 程序,我在这里使用了 Andrew Thompson 的代码:设置 JFrame 位置的最佳实践:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Properties;
import java.io.*;
class RestoreMe {
/** This will end up in the current directory
A more sensible location is a sub-directory of user.home.
(left as an exercise for the reader) */
public static final String fileName = "options.prop";
/** Store location & size of UI */
public static void storeOptions(Frame f) throws Exception {
File file = new File(fileName);
Properties p = new Properties();
// restore the frame from 'full screen' first!
f.setExtendedState(Frame.NORMAL);
Rectangle r = f.getBounds();
int x = (int)r.getX();
int y = (int)r.getY();
int w = (int)r.getWidth();
int h = (int)r.getHeight();
p.setProperty("x", "" + x);
p.setProperty("y", "" + y);
p.setProperty("w", "" + w);
p.setProperty("h", "" + h);
BufferedWriter br = new BufferedWriter(new FileWriter(file));
p.store(br, "Properties of the user frame");
}
/** Restore location & size of UI */
public static void restoreOptions(Frame f) throws IOException {
File file = new File(fileName);
Properties p = new Properties();
BufferedReader br = new BufferedReader(new FileReader(file));
p.load(br);
int x = Integer.parseInt(p.getProperty("x"));
int y = Integer.parseInt(p.getProperty("y"));
int w = Integer.parseInt(p.getProperty("w"));
int h = Integer.parseInt(p.getProperty("h"));
Rectangle r = new Rectangle(x,y,w,h);
f.setBounds(r);
}
public static void main(String[] args) {
final JFrame f = new JFrame("Good Location & Size");
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent we) {
try {
storeOptions(f);
} catch(Exception e) {
e.printStackTrace();
}
System.exit(0);
}
});
JTextArea ta = new JTextArea(20,50);
f.add(ta);
f.pack();
File optionsFile = new File(fileName);
if (optionsFile.exists()) {
try {
restoreOptions(f);
} catch(IOException ioe) {
ioe.printStackTrace();
}
} else {
f.setLocationByPlatform(true);
}
f.setVisible(true);
}
}
我有三个问题:
- 我设置全屏窗口 (
JFrame
) 然后关闭它,当我重新打开窗口时,它具有全屏的尺寸但不是全屏。 - 这个 2° 问题与 Thompson 的代码无关,当我将窗口移动到屏幕边框时,它不会超出屏幕边框并与屏幕边距并排。
- 关于“option.prop”文件,目前该文件存储在我的 .jar 父文件夹中,我想将它存储在我的 .jar 程序的同一个文件夹中,我该怎么做?
谢谢