名词解释
什么是GUI ?
图形用户界面
什么是AWT
基本的程序设计类库,抽象接口工具箱。将处理界面的的任务下派给每一个平台(windows等)
什么是swing
与AWT不同在不同平台显示的界面是一样的。建立在AWT之上
Swing的优势
- Swing拥有丰富的、便捷的、用户界面元素集合
- Swing对底层平台依赖极少
- Swing对于不同平台一致的观感
- 基本事件采用AWT
框架创建和定位
写一个显示空框架的简单程序
package SimpeFrame;
import javax.swing.*;
import java.awt.*;
public class SimpeFrameTest {
public static void main(String[] args){
EventQueue.invokeLater(()->{
SimpleFrame frame = new SimpleFrame();
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setVisible(true);
});
}
}
class SimpleFrame extends JFrame{
private static final int DEAULT_WIDTH = 300;
private static final int DEAULT_Height = 200;
public SimpleFrame(){
setSize(DEAULT_WIDTH,DEAULT_Height);
}
}
所有的Swing组件必须由时间分派线程(EventQueue.invokeLater)配置
调整框架的大小
package SimpeFrame;
import javax.swing.*;
import java.awt.*;
public class SizeFrameTest {
public static void main(String[] args){
EventQueue.invokeLater(() -> {
JFrame frame = new SizeFrame();
frame.setTitle("SizedFrame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
class SizeFrame extends JFrame{
public SizeFrame(){
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screenSize = kit.getScreenSize();
int screenWidth = screenSize.width;
int screenHeight = screenSize.height;
setSize(screenWidth/2,screenHeight/2);
setLocationByPlatform(true) ;
// set frame icon
Image img = new ImageIcon("snail.png").getImage() ;
setIconImage(img) ;
}
}
JFrame内部层级.png
显示文字组件
package SimpeFrame;
import javax.swing.*;
import java.awt.*;
import static com.sun.tools.internal.xjc.reader.Ring.add;
public class SizeFrameTest {
public static void main(String[] args){
EventQueue.invokeLater(() -> {
JFrame frame = new NotHelloWordFrame();
frame.setTitle("NotHelloWord");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
class NotHelloWordFrame extends JFrame{
public NotHelloWordFrame(){
add(new NotHelloWorldComponent());
pack();
}
}
class NotHelloWorldComponent extends JComponent{
public static final int MESSAGE_X = 75;
public static final int MESSAGE_Y = 100;
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200;
public void paintComponent(Graphics g){
g.drawString("Not a Hello, World program", MESSAGE_X, MESSAGE_Y) ;
}
public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); }
}
网友评论