java——GUI图形界面

一、一个简单的 SWING 例子

练习——在上次关闭位置启动窗口
比如这次使用这个窗口,导致窗口被移动到了右下角。 关闭这个窗口,下一次再启动的时候,就会自动出现在右下角。

思路提示
启动一个线程,每个100毫秒读取当前的位置信息,保存在文件中,比如location.txt文件。
启动的时候,从这个文件中读取位置信息,如果是空的,就使用默认位置,如果不是空的,就把位置信息设置在窗口上。
读取位置信息的办法: f.getX() 读取横坐标信息,f.getY()读取纵坐标信息。

注:这个练习要求使用多线程来完成。 还有另一个思路来完成,就是使用监听器,因为刚开始学习GUI,还没有掌握监听器的使用,所以暂时使用多线程来完成这个功能。

/*
 * SavingPostionThread 用于每隔100毫秒记录当前的位置信息到location.txt中,
 * 记录数据的时候用到了数据输出流可以方便的保存多个整数
 * 接着在TestGUI设计一个静态内部类 Point用于保存x和y。
 * 
 */
public class SavingPositionThread extends Thread {

    private JFrame f;
    File file = new File("location.txt");

    public SavingPositionThread(JFrame f) {
        this.f = f;
    }

    public void run() {
        //因为要动态获取界面的位置,所以要写一个死循环不停获取位置
        while(true) {
            //下面这两行要放在while里面才行,不然每次run都归零了
            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) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }

            try {
                Thread.sleep(100);
            }catch(InterruptedException e){
                e.printStackTrace();
            }

        }
    }
}

测试:

public class TestGUI {
    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 SavingPositionThread(f).start();

    }

    static class Point {
        int x;
        int y;
    }

    public static Point getPointFromLocationFile() {
        File file = new File("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 (FileNotFoundException e) {
            //第一次运行,并没有生成位置文件,所以会出现FileNotFoundException

        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return p;  

    }
}

二、事件监听

按钮监听

猜你喜欢

转载自blog.csdn.net/Jae_Peng/article/details/79939390