how2j.cn


工具版本兼容问题
GUI-Graphic User Interface 图形用户界面


本视频是解读性视频,所以希望您已经看过了本知识点的内容,并且编写了相应的代码之后,带着疑问来观看,这样收获才多。 不建议一开始就观看视频



6分39秒
本视频采用html5方式播放,如无法正常播放,请将浏览器升级至最新版本,推荐火狐,chrome,360浏览器。 如果装有迅雷,播放视频呈现直接下载状态,请调整 迅雷系统设置-基本设置-启动-监视全部浏览器 (去掉这个选项)。 chrome 的 视频下载插件会影响播放,如 IDM 等,请关闭或者切换其他浏览器



步骤 1 : 简单的例子   
步骤 2 : 练习-在上次关闭位置启动窗口   
步骤 3 : 答案-在上次关闭位置启动窗口   

JFrame是GUI中的容器
JButton是最常见的组件- 按钮
注意:f.setVisible(true); 会对所有的组件进行渲染,所以一定要放在最后面
简单的例子
package gui; import javax.swing.JButton; import javax.swing.JFrame; public class TestGUI { public static void main(String[] args) { // 主窗体 JFrame f = new JFrame("LoL"); // 主窗体设置大小 f.setSize(400, 300); // 主窗体设置位置 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); } }
步骤 2 :

练习-在上次关闭位置启动窗口

edit  姿势不对,事倍功半! 点击查看做练习的正确姿势
比如这次使用这个窗口,导致窗口被移动到了右下角。 关闭这个窗口,下一次再启动的时候,就会自动出现在右下角。

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

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

答案-在上次关闭位置启动窗口

edit
在查看答案前,尽量先自己完成,碰到问题再来查看答案,收获会更多
在查看答案前,尽量先自己完成,碰到问题再来查看答案,收获会更多
在查看答案前,尽量先自己完成,碰到问题再来查看答案,收获会更多
查看本答案会花费4个积分,您目前总共有点积分。查看相同答案不会花费额外积分。 积分增加办法 或者一次性购买JAVA 中级总计0个答案 (总共需要0积分)
查看本答案会花费4个积分,您目前总共有点积分。查看相同答案不会花费额外积分。 积分增加办法 或者一次性购买JAVA 中级总计0个答案 (总共需要0积分)
账号未激活 账号未激活,功能受限。 请点击激活
本视频是解读性视频,所以希望您已经看过了本答案的内容,带着疑问来观看,这样收获才多。 不建议一开始就观看视频

5分10秒 本视频采用html5方式播放,如无法正常播放,请将浏览器升级至最新版本,推荐火狐,chrome,360浏览器。 如果装有迅雷,播放视频呈现直接下载状态,请调整 迅雷系统设置-基本设置-启动-监视全部浏览器 (去掉这个选项)。 chrome 的 视频下载插件会影响播放,如 IDM 等,请关闭或者切换其他浏览器


SavingPostionThread 用于每隔100毫秒记录当前的位置信息到location.txt中,记录数据的时候用到了数据输出流可以方便的保存多个整数

接着在TestGUI设计一个静态内部类 Point用于保存x和y。

然后在TestGUI中设计一个方法getPointFromLocationFile,通过数据输入流读取坐标x和y,放在一个Point对象中,并返回。

注意: 第一次读取的时候,是没有文件的,所以会返回null,需要进行专门处理。
package gui; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import javax.swing.JFrame; class SavingPostionThread extends Thread { private JFrame f; File file = new File("e:/project/j2se/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 Auto-generated catch block e.printStackTrace(); } } } }
package gui; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import javax.swing.JButton; import javax.swing.JFrame; 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 SavingPostionThread(f).start(); } static class Point { int x; int y; } public static Point getPointFromLocationFile() { File file = new File("e:/project/j2se/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; } }


HOW2J公众号,关注后实时获知最新的教程和优惠活动,谢谢。


问答区域    
2024-01-29 练习 - 在上次关闭位置启动窗口
莫諾




比如这次使用这个窗口,导致窗口被移动到了右下角。 关闭这个窗口,下一次再启动的时候,就会自动出现在右下角
static File fi = new File("***");
// 
static JFrame f = new JFrame("LoL");
// 
static int width = 400;		static int heighth = 250;

// main
TestGUI tg = new TestGUI();
		
frame(fi);
int n = 50;
// 
Thread[] addThreads = new Thread[n];
for (int i = 0; i < n; i++) {
	taskThread t = tg.new taskThread();
	t.start();
	addThreads[i] = t;
	try {
		t.join();
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
}

// **************
//
class taskThread extends Thread {
	public taskThread(String name) {
		super(name);
	}	
	
	public taskThread() {}

	public void run() {
		System.out.println("启动: " + this.getName() + "读取当前窗体实时位置信息!");
		try {
			// 
			int x = f.getX();
			int y = f.getY();
			// 
			sav(fi, x, y);	
			Thread.sleep(100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}	
}

// 
public static String[] readTem(File f) {
	int l = 0;int i = 0;
	try (
			FileReader fr = new FileReader(f);
			BufferedReader br = new BufferedReader(fr);
	) {
		while (true) {
			String line = br.readLine();
			if (null == line)
				break;
			l++;
		}
		br.close();
		fr.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
	String[] s0 = new String[l];
	try (
			FileReader fr = new FileReader(f);
			BufferedReader br = new BufferedReader(fr);
	) {
		while (true) {
			String line = br.readLine();
			if (null == line)
				break;
			s0[i] = line;
			i++;
		}
		br.close();
		fr.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
	return s0;
}

// 
public static void frame(File fi) {
	int x; int y;
	if (fi.exists() == false) {
		x = 5; y = 5;
	} else {
		x = Integer.parseInt(redl(fi).split(",")[0]);
		y = Integer.parseInt(redl(fi).split(",")[1]);
	}
	// 
	f.setSize(width, heighth);
	f.setLocation(x, y);
	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);	
}

// 读取位置文件信息
static String redl(File fi) {
	String ss = "";
	String[] rt = readTem(fi);
	if(rt.length != 0) {
		ss = rt[rt.length - 1];
	}
	return ss;	
}

// 保存
void sav(File fi, int x, int y) {
	if (fi.exists() == false) {
		fi.getParentFile().mkdirs();
		try {
			fi.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
	} 
	String ss = x + "," + y;
	String[] rt = readTem(fi);
	if(rt.length == 0) {
		rt = new String[rt.length + 1];
		rt[rt.length - 1] = ss;
		write(rt, fi);
	} else {
		String[] rtt = new String[rt.length + 1];
		for(int i = 0; i < rt.length; i++) {
			rtt[i] = rt[i];
		}
		rtt[rtt.length - 1] = ss; 
		rt = rtt;
		write(rt, fi);
	}	
}

// 
void write(String[] s,File f) {
	try (
			FileWriter fw = new FileWriter(f);
			PrintWriter pw = new PrintWriter(fw);
	) {
		for (int i = 0; i < s.length; i++) {
			pw.println(s[i]);
		}
		pw.close();
		fw.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
}

							





回答已经提交成功,正在审核。 请于 我的回答 处查看回答记录,谢谢
答案 或者 代码至少填写一项, 如果是自己有问题,请重新提问,否则站长有可能看不到





2023-09-02 练习-在上次关闭位置启动窗口
旧时亭台阁




启动一个守护线程,记录位置
import javax.swing.*;
import java.io.*;

public class App {

    public static void main(String[] args) throws Exception {

        // 读取文件
        int defaultX, defaultY;
        File file = new File("location");
        try (DataInputStream dis = new DataInputStream(new FileInputStream(file))) {
            defaultX = dis.readInt();
            defaultY = dis.readInt();
        } catch (Exception exception) {
            defaultX = 200;
            defaultY = 200;
        }


        JFrame frame = new JFrame("LOL");
        frame.setSize(400, 300);
        frame.setLocation(defaultX, defaultY);
        frame.setLayout(null);

        JButton button = new JButton("一键秒对方基地挂");
        button.setBounds(50, 50, 280, 30);

        frame.add(button);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        // 守护线程,记录窗口的位置
        Thread thread1 = new Thread(() -> {
            while (true) {
                DataOutputStream dos = null;
                try {
                    dos = new DataOutputStream(new FileOutputStream(file));
                    int x = frame.getX(), y = frame.getY();
                    dos.writeInt(x);
                    dos.writeInt(y);
                    dos.close();
                    Thread.sleep(100L);
                } catch (IOException | InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        thread1.setDaemon(true);
        thread1.start();
    }


}

							





回答已经提交成功,正在审核。 请于 我的回答 处查看回答记录,谢谢
答案 或者 代码至少填写一项, 如果是自己有问题,请重新提问,否则站长有可能看不到





2022-05-08 阿夜来打卡
2022-04-11 请问现在有公司用这个技术吗
2022-01-13 比站长给的答案更简洁的答案


提问太多,页面渲染太慢,为了加快渲染速度,本页最多只显示几条提问。还有 40 条以前的提问,请 点击查看

提问之前请登陆
提问已经提交成功,正在审核。 请于 我的提问 处查看提问记录,谢谢
关于 JAVA 中级-图形界面-Hello Swing 的提问

尽量提供截图代码异常信息,有助于分析和解决问题。 也可进本站QQ群交流: 578362961
提问尽量提供完整的代码,环境描述,越是有利于问题的重现,您的问题越能更快得到解答。
对教程中代码有疑问,请提供是哪个步骤,哪一行有疑问,这样便于快速定位问题,提高问题得到解答的速度
在已经存在的几千个提问里,有相当大的比例,是因为使用了和站长不同版本的开发环境导致的,比如 jdk, eclpise, idea, mysql,tomcat 等等软件的版本不一致。
请使用和站长一样的版本,可以节约自己大量的学习时间。 站长把教学中用的软件版本整理了,都统一放在了这里, 方便大家下载: https://how2j.cn/k/helloworld/helloworld-version/1718.html

上传截图