/**
* 关于getPreferredSize
* 对于组件的首选尺寸,最大尺寸和最小尺寸,并不决定组件的实际尺寸。
* 只是尺寸请求,在确定组件尺寸时,该请求可能被考虑也可能不考虑。
* getXxxSize返回尺寸的过程:
* 1.如果显示地使用setXxxSize设置了组件的尺寸,则该尺寸值从getXxxSize返回
* 2.如果没有,不过组件有一个UI代表,则调用这个UI代表来计算尺寸
* 3.如果都没有,则调用超类来计算组件尺寸,JComponent是AWT容器,会委托组件的布局管理器来计算首选尺寸
*
* UI代表
*/
import java.awt.*;
import javax.swing.*;
public class ShowMsgComponentTest {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable(){
public void run() {
MsgFrame f=new MsgFrame();
}
});
}
}
class MsgFrame extends JFrame{
MsgFrame(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置点X的关闭操作
//JFrame添加组件,getContentPane()是获取内容窗格,再在窗格上添加组件。1.4后可以直接使用add
getContentPane().add(new MsgComponent("hello world"));
//pack是以组件的首选大小来确定窗体的大小
pack();
setVisible(true);//设置窗体可见
}
}
class MsgComponent extends JComponent{
public static final int MSG_X=75;
public static final int MSG_Y=50;
public static final int DEFAULT_W=300;
public static final int DEFAULT_H=200;
private String msg;
MsgComponent(String msg){
setPreferredSize(new Dimension(DEFAULT_W,DEFAULT_H));
this.msg=msg;
}
//窗口需要重新绘图时,事件处理器通告所有组件,所有组件都调用paintComponent方法重新绘图。
public void paintComponent(Graphics g){
g.drawString(msg, MSG_X, MSG_Y);
}
//public Dimension getPreferredSize(){ return new Dimension(DEFAULT_W,DEFAULT_H); }
}
150611 add:
文本消息位置的纵坐标是按照基线来设置的。不是左上角的坐标位置