`

Swing选项卡

阅读更多

选项卡是SWING开发中用的比较多的组件之一,SWING中的选项卡通过JTabbedPane来实现。

它允许用户通过单击具有给定标题和/或图标的选项卡,在一组组件之间进行切换。

通过使用 addTabinsertTab 方法将选项卡/组件添加到 TabbedPane 对象中。选项卡通过对应于添加位置的索引来表示,其中第一个选项卡的索引为 0,最后一个选项卡的索引为选项卡数减 1。

TabbedPane 使用SingleSelectionModel 来表示选项卡索引集和当前所选择的索引。如果选项卡数大于 0,则总会有一个被选定的索引,此索引默认被初始化为第一个选项卡。如果选项卡数为 0,则所选择的索引为 -1。

 

构造方法:

JTabbedPane()
创建一个具有默认的 JTabbedPane.TOP 选项卡布局的空 TabbedPane。


JTabbedPane(int tabPlacement)
创建一个空的 TabbedPane,使其具有以下指定选项卡布局中的一种:JTabbedPane.TOP、JTabbedPane.BOTTOM、JTabbedPane.LEFT 或 JTabbedPane.RIGHT。

 

public JTabbedPane(int tabPlacement,
int tabLayoutPolicy)
创建一个空的 TabbedPane,使其具有指定的选项卡布局和选项卡布局策略。布局可以是以下几种之一:JTabbedPane.TOP、JTabbedPane.BOTTOM、JTabbedPane.LEFT 或 JTabbedPane.RIGHT。布局策略可以是以下两种之一:JTabbedPane.WRAP_TAB_LAYOUT 或 JTabbedPane.SCROLL_TAB_LAYOUT。

 

通过addTab()方法添加选项卡:

void addTab(String title, Component component)
添加一个由 title 表示,且没有图标的 component。
void addTab(String title, Icon icon, Component component)
添加一个由 title 和/或 icon 表示的 component,其任意一个都可以为 null。
void addTab(String title, Icon icon, Component component, String tip)
添加由 title 和/或 icon 表示的 component 和 tip,其中任意一个都可以为 null。

 

删除选项卡:

void remove(Component component)
从 JTabbedPane 中移除指定 Component。
void remove(int index)
移除对应于指定索引的选项卡和组件。
void removeAll()
从 tabbedpane 中移除所有选项卡及其相应组件。
void removeTabAt(int index)
移除 index 位置的选项卡。

 

这是比较常用的方法,还有一些其他的方法,可以通过API了解,说的都比较清楚。

 

一个简单的例子:

import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

public class SkinSetFrame extends JFrame {
	public static int SkinSetFrameWidth = 500;
	public static int SkinSetFrameHeight = 400;

	public void initComponents() {
		JPanel panel = (JPanel) getContentPane();
		JTabbedPane tab = new JTabbedPane(JTabbedPane.TOP);
		panel.add(tab);

		JPanel systemPicsPanel = new JPanel();
		systemPicsPanel.add(new JLabel("abc"));
		tab.addTab("内置图片", systemPicsPanel);

		JPanel pcPicsPanel = new JPanel();
		pcPicsPanel.setLayout(new FlowLayout(FlowLayout.LEADING, 5, 5));
		pcPicsPanel.add(new JLabel("选择本地图片:"));
		pcPicsPanel.add(new JButton("选择"));
		tab.addTab("本地图片", pcPicsPanel);
	}

	public SkinSetFrame() {
		setTitle("皮肤设置");
		setSize(SkinSetFrameWidth, SkinSetFrameHeight);
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setLocationRelativeTo(null);

		initComponents();
	}

	public static void main(String[] args) {
		SkinSetFrame ssf = new SkinSetFrame();
		ssf.setVisible(true);
	}
}


效果就是这样子:

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics