2012年3月1日星期四

Java 窗体布局

实现窗口有好种方式

一是直接在代码里面创建窗口再进行相应的添加控件

import javax.swing.*;

import java.util.concurrent.*;

public class HelloLabel{

public static void main(String[] args) throws Exception

{

JFrame frame=new JFrame("Hello Swing");

JLabel label=new JLabel("A label");

frame.add(label);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭的事件

frame.setSize(300,100);//设置大小

frame.setVisible(true);//使窗口可视

TimeUnit.SECONDS.sleep(1);//计时器,停顿一秒

label.setText("Hey! This is Different!");

}

}

二、是继承JFrame接口然后在用构造方法进行布局

import javax.swing.*;

import java.util.concurrent.*;

public class SubmitSwingProgram extends JFrame{

JLabel label;

public SubmitSwingProgram(){

super("Hello Swing");

label=new JLabel("A Label");

add(label);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setSize(300,100);

setVisible(true);

}

static SubmitSwingProgram ssp;

public static void main(String[] args) throws Exception

{

SwingUtilities.invokeLater(new Runnable(){

public void run(){ssp=new SubmitSwingProgram();}

});

TimeUnit.SECONDS.sleep(1);

SwingUtilities.invokeLater(new Runnable(){

public void run(){

ssp.label.setText("Hey! This is Different!");

}

});

}

}

布局方式:

BorderLayout将整个区域划分为一个部分,分别四个边框区域和一个中央区域,直接利用重载add来进行添加

clip_image002

package Gui;

import javax.swing.*;

import java.awt.*;

import static net.mindview.util.SwingConsole.*;

public class BorderLayout1 extends JFrame{

public BorderLayout1(){

add(BorderLayout.NORTH,new JButton("North"));

add(BorderLayout.SOUTH,new JButton("SOUTH"));

add(BorderLayout.EAST,new JButton("EAST"));

add(BorderLayout.WEST,new JButton("WEST"));

add(BorderLayout.CENTER,new JButton("CENTER"));

}

public static void main(String[] args) {

run(new BorderLayout1(),300,250);

}

}

clip_image003

FlowLayout(流动)布局:

这个布局也是很好理解的,当你在添加控件的时候假设你当前的控件的大小超过可容纳的区域大小会自动添加到下一行当中。

package Gui;

import javax.swing.*;

import java.awt.*;

import static net.mindview.util.SwingConsole.*;

public class FlowLayout1 extends JFrame{

public FlowLayout1(){

setLayout(new FlowLayout());

for(int i=0;i<20;i++)

add(new JButton("Button "+i));

}

public static void main(String[] args) {

run(new FlowLayout1(), 300, 300);

}

}

clip_image004

GridLayotu(表格)布局:

把当前的区域划分为N*M的表格,然后每一个控制占有一个单元格

package Gui;

import javax.swing.JButton;

import javax.swing.JFrame;

import java.awt.*;

import static net.mindview.util.SwingConsole.*;

public class GridLayout1 extends JFrame{

public GridLayout1(){

setLayout(new GridLayout(7,3));

for(int i=0;i<20;i++)

add(new JButton("Button "+i));

}

public static void main(String[] args) {

run(new GridLayout1(),300,300);

}

}

clip_image005


Java 窗体布局

TAG: