图形界面 Hello Swing练习
在上次关闭位置启动窗口
比如这次使用这个窗口,导致窗口被移动到了右下角。 关闭这个窗口,下一次再启动的时候,就会自动出现在右下角。
思路提示:
启动一个线程,每个100毫秒读取当前的位置信息,保存在文件中,比如location.txt文件。
启动的时候,从这个文件中读取位置信息,如果是空的,就使用默认位置,如果不是空的,就把位置信息设置在窗口上。
读取位置信息的办法: f.getX() 读取横坐标信息,f.getY()读取纵坐标信息。
注:这个练习要求使用多线程来完成。 还有另一个思路来完成,就是使用监听器,因为刚开始学习GUI,还没有掌握监听器的使用,所以暂时使用多线程来完成这个功能。
SavingPostionThread 用于每隔100毫秒记录当前的位置信息到location.txt中,记录数据的时候用到了数据输出流可以方便的保存多个整数
接着在TestGUI设计一个静态内部类 Point用于保存x和y。
然后在TestGUI中设计一个方法getPointFromLocationFile,通过数据输入流读取坐标x和y,放在一个Point对象中,并返回。
注意: 第一次读取的时候,是没有文件的,所以会返回null,需要进行专门处理。
SavingPostionThread代码:
package gui;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import javax.swing.JFrame;
public class SavingPostionThread extends Thread{
private JFrame f;
File file=new File("D:\\Location.txt");
SavingPostionThread(JFrame f)
{
this.f=f;
}
public void run(){
while(true){
int x=f.getX();
int y=f.getY();
try(FileOutputStream fos=new FileOutputStream(file);
DataOutputStream dos=new DataOutputStream(fos);){
dos.writeInt(x);
dos.writeInt(y);
}catch (Exception e){
e.printStackTrace();
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}
GUIText代码:
package gui;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
public class GUIText {
static class Point{
int x;
int y;
}
public static Point getPointFromLocationFile(){
File file=new File("D:\\Location.txt");
Point p=null;
try(FileInputStream fis=new FileInputStream(file);
DataInputStream dis=new DataInputStream(fis);){
int x=dis.readInt();
int y=dis.readInt();
p=new Point();
p.x=x;
p.y=y;
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
return p;
}
public static void main(String[] args) {
JFrame f=new JFrame("LOL");
f.setSize(400, 300);
Point p=getPointFromLocationFile();
if(p!=null)
f.setLocation(p.x,p.y);
else
f.setLocation(200,200);
f.setLayout(null);
JButton b=new JButton("秒杀");
b.setBounds(50,50,280,30);
f.add(b);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
new SavingPostionThread(f).start();
}
}