java jframe位置_设置JFrame位置的最佳做法

这是一个包含以下建议的示例:气垫船满鳗鱼 - 按平台设置位置。

Aardvocate Akintayo Olu - 序列化位置。

但继续增加2个调整:序列化宽度/高度。

如果帧在关闭时最大化,则在获得边界之前恢复。(我讨厌应用程序。序列化选项,但不考虑这一点。用户坐在那里点击'最大化/恢复'按钮,并想知道为什么没有发生!)

4点组合提供最佳用户体验!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);

}}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值