Java 窗體佈局 – 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

摘自 夜風雪

發佈留言