GUI编程【一】

来源:互联网 发布:js删除节点本身 编辑:程序博客网 时间:2024/06/09 20:49

GUI 编程【一】

            ——创建框架,使框架在任意位置,添加组件,布局管理器(FlowLayout)

javaGUI使用的类的结构图:


 

创建框架:

package javaCUI1;import javax.swing.JFrame;public class gui1 {public static void main(String[] args) {JFrame frame=new JFrame("test");//名称frame.setSize(400,300);//宽高像素frame.setVisible(true);//显示frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口,若无此句windows按Ctrl+C关闭。}}

效果图:


框架任意位置显示及居中:

package javaCUI1;import java.awt.Dimension;import java.awt.Toolkit;import javax.swing.JFrame;public class gui1 {public static void main(String[] args) {JFrame frame=new JFrame("test");//名称frame.setSize(400,300);//宽高像素//获取屏幕宽高Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();int screenWidth=screenSize.width;int screenHeight=screenSize.height;//获取框架宽高Dimension frameSize=frame.getSize();//设定显示位置int x=(screenWidth-frameSize.width)/2;int y=(screenHeight-frameSize.height)/2;frame.setLocation(x, y);frame.setVisible(true);//显示frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口,若无此句windows按Ctrl+C关闭。}}

添加组件:

package javaCUI1;import java.awt.Container;import javax.swing.JButton;import javax.swing.JFrame;public class gui1 {public static void main(String[] args) {JFrame frame=new JFrame("test");//名称frame.setSize(400,300);//宽高像素Container container=frame.getContentPane();//返回框架的内容面板container.add(new JButton("OK"));//在返回的内容面板中添加组件//一句话写法:frame.getContentPane().add(new JButton("OK");frame.setVisible(true);//显示frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口,若无此句windows按Ctrl+C关闭。}}

效果显示

布局管理器:

五个基本布局管理器:FlowerLayout,GridLayout,BorderLayout,CardLayout,GridBagLayout。

基本语法:

container.setLayout(new SpecificLayout());

JButton jbtOK=new JButton("OK");

container.remove(jbtOK);

FlowLayout:

public FlowerLayout(int align,int hGap,int vGao)  指定排列,水平间距,垂直间距

package javaCUI1;import java.awt.Container;import java.awt.FlowLayout;import javax.swing.JButton;import javax.swing.JFrame;public class ShowFlowLayout extends JFrame{//扩展了类JFrame,直接使用JFrame中相关属性。    public ShowFlowLayout()    {    Container container=getContentPane();    //定义容器    container.setLayout(new FlowLayout(FlowLayout.LEFT,10,20));        //等价于:        //FlowLayout layout=new FlowLayout(FlowLayout.LEFT,10,20);        //container.setLayout(layout);        //布局方式    for(int i=1;i<=10;i++)    {    container.add(new JButton("Component"+i));    }    }public static void main(String[] args) {ShowFlowLayout frame=new ShowFlowLayout();frame.setTitle("show FlowLayout");frame.setSize(200,200);frame.setVisible(true);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}}

效果图:



0 0