標籤:java 布局
java-布局及補充組件
基本布局方式
一 卡片布局-CardLayou
二 邊界布局-BorderLayout東南西北中的方式
三 網格袋布局-GridBagLayout
四 分割面板-JSplitPanel只能分割兩個組件,類型不限
相應的方法可以API中查詢,前面的文章提供了API的下載連結
補充組件
五 索引標籤群組件-JTabbedPane
六 案頭組件-JDesktopPane
七 內部表單組件-JInternalFrame
實現一個小程式,利用卡片布局
基本思想
建立3個面板
->建立一個卡片
->在其中一個面板上添加卡片
->將另外兩個面板添加到卡片上,將面板設定不同的顏色
->在卡片上的兩個面板上分別建立兩個按鈕
->為按鈕添加事件處理機制,點擊其中一個面板上的按鈕,顯示另外一個面板的顏色
面板上添加卡片
卡片上添加面板
面板上在添加兩個按鈕
按鈕設定事件處理機制
點擊按鈕實現面板轉換
eg:package com.chengzhi.pkg1;import java.awt.CardLayout;import java.awt.Color;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JPanel;public class TestGui extends JFrame implements ActionListener{ JPanel p1, p2, p3; JButton b1, b2; CardLayout cardlayout;public TestGui(){p1 = new JPanel();p2 = new JPanel();p3 = new JPanel();b1 = new JButton("顯示紅色按鈕");b2 = new JButton("顯示綠色按鈕");cardlayout = new CardLayout();p1.setLayout(cardlayout);p2.setBackground(Color.red);p3.setBackground(Color.green);p1.add("panel2", p2);p1.add("panel3", p3);p2.add(b2);p3.add(b1);this.getContentPane().add(p1);this.setSize(300, 300);this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//cardlayout.last(p1);//cardlayout.first(p1);//cardlayout.show(p1, "panel2");b1.addActionListener(this);b2.addActionListener(this);}public static void main(String[] args) { new TestGui();}@Overridepublic void actionPerformed(ActionEvent e) { JButton b = (JButton)e.getSource(); if (b == b1){ //cardlayout.show(p1, "panel2"); cardlayout.next(p1); } if (b == b2) { //cardlayout.show(p1, "panel3"); cardlayout.next(p1); }}}
java-布局及補充組件