本文主要是介绍GUI布局:边界布局、流式布局、网格布局、卡片布局,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
边界布局
package guiTest;
//JFrame默认的是边界布局BorderLayout
import java.awt.BorderLayout;import javax.swing.JButton;
import javax.swing.JFrame;public class BorderLayoutDemo {public static void main(String[] args) {JFrame f = new JFrame("边界布局BorderLayout");//JFrame的默认LayoutManager为BorderLayout// f.setLayout(new BorderLayout());//可以不写,默认的就是流式布局JButton btn = new JButton("北");f.add(btn,BorderLayout.NORTH);btn=new JButton("南");f.add(btn,BorderLayout.SOUTH);btn=new JButton("东");f.add(btn,BorderLayout.EAST);btn=new JButton("西");f.add(btn,BorderLayout.WEST);btn=new JButton("中");f.add(btn,BorderLayout.CENTER);f.pack();//也可以用f.setSize(222,222);来进行设置f.setVisible(true);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}}
流式布局
package guiTest;import java.awt.FlowLayout;import javax.swing.JButton;
import javax.swing.JFrame;public class FlowLayoutDemo {public static void main(String[] args) {// TODO Auto-generated method stubJFrame f = new JFrame("流式布局FlowLayout");f.setLayout(new FlowLayout());for(int i=0;i<7;i++){JButton btn=new JButton("Button"+i);f.add(btn);}f.setSize(300,250);//f.pack();默认边框设置宽度和长度刚刚好的样子f.setVisible(true);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}}
网格布局
<pre name="code" class="java">package guiTest;import java.awt.GridLayout;import javax.swing.JButton;
import javax.swing.JFrame;public class GirdLayoutDemo {public static void main(String[] args) {JFrame f = new JFrame("网格布局GirdLayout");//设置f的布局管理器为3行3列的GirdLayout组件间水平与垂直间距为5f.setLayout(new GridLayout(3,3,5,5));for(int i=1;i<10;++i){JButton btn = new JButton(String.valueOf(i));f.add(btn);}f.pack();f.setVisible(true);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}}
卡片布局
<pre name="code" class="java">package guiTest;import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;public class CardLayoutDemo {private static JPanel p;public static void main(String[] args) {JFrame f = new JFrame("卡片布局CardLayout");p=new JPanel();//设置p的布局管理器为卡片布局CardLayoutp.setLayout(new CardLayout());//新建两个JPanelJPanel p1 = new JPanel();JPanel p2 = new JPanel();JLabel lb = new JLabel("第一个面板");p1.add(lb);//面板里面加标签lb=new JLabel("第二个面板");p2.add(lb);//面板里面加标签//将新建的两个JPanel面板添加到p中p.add(p1,"first");p.add(p2,"second");//设置默认显示first所对应的JPanel p1((CardLayout)p.getLayout()).show(p,"first");JButton btn = new JButton("改变面板");btn.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stub//当点击'改变面板'时,显示second对应的JPanel p2((CardLayout)p.getLayout()).show(p,"second");}});f.add(btn,BorderLayout.NORTH);f.add(p,BorderLayout.CENTER);f.setSize(400,150);//f.pack();f.setVisible(true);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}}
这篇关于GUI布局:边界布局、流式布局、网格布局、卡片布局的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!