Swing結(jié)構(gòu)圖
window我認為可以理解為容器,Jcomponent可以理解為組件,JPanel為面板,組件放在面板上,面板移動的時候,組件隨之移動

swing組件間結(jié)構(gòu)
創(chuàng)建一個居中面板
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;
//創(chuàng)建一個居中面板
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();
// 如果入?yún)⒂斜壤?,那么就乘以比例,設(shè)置大小
if(strech)
c.setSize((int)(containerSize.width * rate),(int)(containerSize.height * rate));
else
// 如果沒有比例就設(shè)置推薦大小
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方法是獲取頁面的元素,然后將他們移除,然后添加,
// 在重繪制,重新繪制會調(diào)用repanint()方法,這時候會調(diào)整控件的大小
this.c = p ;
Component[] cs = getComponents();//container
for (Component c: cs){
remove(c);
}
add(p);
this.updateUI();
//Overrides: updateUI() in JComponent,調(diào)用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中一共有三種線程,暫時先了解下,以后來深入研究:
- 初始化線程
用于創(chuàng)建容器,組件,并顯示,一旦創(chuàng)建并顯示,初始化線程結(jié)束 - 事件調(diào)度線程
所有和事件相關(guān)的操作都是在事件調(diào)度線程中完成的,比如點擊一個按鈕,對應(yīng)的ActionListener.actionPerformed 方法中的代碼 - 長耗時任務(wù)線程
有一些長時間的操作,不能放在事件調(diào)度線程中,不然會讓用戶覺得頁面很卡頓