swing

Swing结构图

window我认为可以理解为容器,Jcomponent可以理解为组件,JPanel为面板,组件放在面板上,面板移动的时候,组件随之移动


swing组件间结构

创建一个居中面板

package util;

import java.awt.Component;
import java.awt.Dimension;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;

//创建一个居中面板
public class CenterPanel extends JPanel{
    private double rate;
    private JComponent c;
    private boolean strech;
    
    public CenterPanel(double rate,boolean strech){
        this.setLayout(null); //Container
        this.rate = rate;
        this.strech = strech;
    }
    
    public CenterPanel(double rate){
        this(rate,true);
    }
    
    public void repaint(){
        //Overrides: repaint() in Component
        if(null != c){
            //如果c不为空,那么获取
            Dimension containerSize = this.getSize(); //Component
            Dimension componentSize = c.getPreferredSize();
//          如果入参有比例,那么就乘以比例,设置大小
            if(strech)
                c.setSize((int)(containerSize.width * rate),(int)(containerSize.height * rate));
            else 
//              如果没有比例就设置推荐大小
                c.setSize(componentSize);
            c.setLocation(containerSize.width / 2 - c.getSize().width / 2 , containerSize.height / 2 - c.getSize().height/ 2);
        }
        super.repaint();
    }
    
    public void show(JComponent p){
//      show方法是获取页面的元素,然后将他们移除,然后添加,
//         在重绘制,重新绘制会调用repanint()方法,这时候会调整控件的大小
        this.c = p ;
        Component[] cs = getComponents();//container
        for (Component c: cs){
            remove(c);
        }
        add(p);
        this.updateUI();
        //Overrides: updateUI() in JComponent,调用repaint()方法
    }
    
    public static void main(String[] args){
        JFrame f = new JFrame();
        f.setSize(200, 200);
        f.setLocationRelativeTo(null);
        CenterPanel cp = new CenterPanel(0.85 ,true);
        f.setContentPane(cp);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
        JButton b = new JButton("abc");
        cp.show(b);
    }
}

swing中的线程

swing中一共有三种线程,暂时先了解下,以后来深入研究:

  1. 初始化线程
    用于创建容器,组件,并显示,一旦创建并显示,初始化线程结束
  2. 事件调度线程
    所有和事件相关的操作都是在事件调度线程中完成的,比如点击一个按钮,对应的ActionListener.actionPerformed 方法中的代码
  3. 长耗时任务线程
    有一些长时间的操作,不能放在事件调度线程中,不然会让用户觉得页面很卡顿
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容