Java JToolBar类(工具栏)

简介

具栏中提供了快速执行常用命令的按钮,可以将它随意拖拽到窗体的四周,JToolBar 工具栏相当于一个组件的容器,可以添加按钮,微调控制器等组件到工具栏中。每个添加的组件会被分配一个整数的索引,来确定这个组件的显示顺序。另外,组件可以位于窗体的任何一个边框,也可以成为一个单独的窗体。

注意:如果希望工具栏可以随意拖动,窗体一定要采用默认的边界布局方式,并且不能在边界布局的四周添加任何组件。

工具栏默认是可以随意拖动的。

常用构造方法

JToolBar():建立一个新的JToolBar,位置为默认的水平方向.

JToolBar(int orientation):建立一个指定的JToolBar.

JToolBar(String name):建立一个指定名称的JToolBar.

JToolBar(String name,int orientation):建立一个指定名称和位置的JToolBar.

入口参数代表的意思:

name:工具栏名称,悬浮显示时为悬浮窗口的标题。

orientation:工具栏的方向,值为HORIZONTAL (水平方向,默认值)或 VERTICAL(垂直方向)

注意:在使用JToolBar时一般都采用水平方向的位置,因此我们在构造时多是采用上表中的第一种构造方式来建立JToolBar,如果需要改变方向时再用JToolBar内的setOrientation()方法来改变设置,或是以鼠标拉动的方式来改变JToolBar的位置。

常用方法

public JButton add(Action a) : 向工具栏中添加一个指派动作的新的Button

public void addSeparator() : 将默认大小的分隔符添加到工具栏的末尾

public Component getComponentAtIndex(int i) : 返回指定索引位置的组件

public int getComponentIndex(Component c) : 返回指定组件的索引

public int getOrientation() : 返回工具栏的当前方向

public boolean isFloatable() : 获取Floatable 属性,以确定工具栏是否能拖动,如果可以则返回true,否则返回false

public boolean isRollover () : 获取rollover 状态,以确定当鼠标经过工具栏按钮时,是否绘制按钮的边框,如果需要绘制则返回true,否则返回false

public void setFloatable(boolean b) : 设置Floatable 属性,如果要移动工具栏,此属性必须设置为true

import java.util.*;
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class t3 extends JFrame{
	
	public t3() {
		setTitle("选项卡面板");
		setBounds(400, 400, 400, 400);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		final JToolBar toolBar = new JToolBar("工具栏");// 创建工具栏对象
		toolBar.setFloatable(false);// 设置为不允许拖动
		
		final JButton newButton = new JButton("新建");// 创建按钮对象
		newButton.addActionListener(new ButtonListener());// 添加动作事件监听器
		toolBar.add(newButton);// 添加到工具栏中
		toolBar.addSeparator();// 添加默认大小的分隔符
		
		final JButton saveButton = new JButton("保存");// 创建按钮对象
		saveButton.addActionListener(new ButtonListener());// 添加动作事件监听器
		toolBar.add(saveButton);// 添加到工具栏中
		toolBar.addSeparator(new Dimension(20, 0));// 添加指定大小的分隔符
		
		final JButton exitButton = new JButton("退出");// 创建按钮对象
		exitButton.addActionListener(new ButtonListener());// 添加动作事件监听器
		toolBar.add(exitButton);// 添加到工具栏中
		
		add(toolBar, BorderLayout.NORTH);
		setVisible(true);
	}
	
	private class ButtonListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			JButton button = (JButton) e.getSource();
			System.out.println("您单击的是:" + button.getText());
		}
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		t3 test = new t3();

	}

}

猜你喜欢

转载自blog.csdn.net/qq_36761831/article/details/81485380