虽然在学习java开发中,我们基本上都是写的后端,但是有些时候还是需要学习gui开发的部分同学就学习了swing,但是swing组件在布局后就固定了,一些初学者为了好看会把窗口禁止改变大小,这篇就说一下另外一种解决方式 ——自适配
首先导入对应包
import javax.swing.*;
import java.awt.event.*;
创建我们的布局类,写上属性
class Gui{
int root_w = 500;
int root_h = 500;
int but_w = 50;
int but_h = 50;
int but_x = (root_w-but_w)/2;
int but_y = (root_h-but_h)/2;
JButton but = new JButton("测试");
JPanel p1 = new JPanel();
构造方法里面写窗口情况
public Gui(){ JFrame root = new JFrame("自适配思路");
root.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
root.setSize(root_w,root_w); root.setLocationRelativeTo(null); root.setVisible(true); root.setContentPane(p1);
p1.setLayout(null); but.setBounds(but_x,but_y,but_w,but_h); p1.add(but);
监听窗口大小事件
root.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
窗口事件发生后执行的代码
int root_w =root.getWidth();
int root_h =root.getHeight();
int but_w = 50;
int but_h = 50;
int but_x = (root_w-but_w)/2;
int but_y = (root_h-but_h)/2;
重新布局
but.setBounds(but_x,but_y,but_w,but_h);
}
});
}}
主类
public class mains {
//main
public static void main(String[] args) {
新建对象调用构造方法
new Gui();
}
}
原文始发于微信公众号(隼目安全):【相关分享】关于java_swing的组件位置自适配
- 左青龙
- 微信扫一扫
-
- 右白虎
- 微信扫一扫
-
评论