工具栏(JToolBar)

来源:互联网 发布:变形相机是什么软件 编辑:程序博客网 时间:2024/06/08 08:11

JToolBar 工具栏相当于一个组件的容器,可以添加按钮,微调控制器等组件到工具栏中。每个添加的组件会被分配一个整数的索引,来确定这个组件的显示顺序。另外,组件可以位于窗体的任何一个边框,也可以成为一个单独的窗体

一般来说,工具栏主要是用图标来表示,位于菜单栏的下方,也可以成为浮动的工具栏,形式很灵活JToolBar构造函数:

JToolBar():建立一个新的JToolBar,位置为默认的水平方向.
JToolBar(int orientation):建立一个指定的JToolBar.
JToolBar(String name):建立一个指定名称的JToolBar.
JToolBar(String name,int orientation):建立一个指定名称和位置的JToolBar.

注意:在工具栏为浮动工具栏时才会显示指定的标题,指定的方向一般用静态常量HORIZONTAL和VERTICAL,分别表示水平和垂直方向
构造JToolBar组件:
在使用JToolBar时一般都采用水平方向的位置,因此我们在构造时多是采用上表中的第一种构造方式来建立JToolBar.如果需要 改变方向时再用JToolBar内的setOrientation()方法来改变设置,或是以鼠标拉动的方式来改变JToolBar的位置.

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

package ch10;import java.awt.BorderLayout;import java.awt.event.*;import javax.swing.*;public class ToolBarTest extends JFrame implements ActionListener{    JButton leftbutton = new JButton("左对齐",new ImageIcon("D:/1.png"));    JButton middlebutton = new JButton("居中",new ImageIcon("D:/1.png"));    JButton rightbutton = new JButton("左居中",new ImageIcon("D:/1.png"));    private JButton[] buttonArray = new JButton[]{leftbutton,middlebutton,rightbutton};    private JToolBar toolbar = new JToolBar("简易工具栏");    private JLabel jl = new JLabel("请点击工具栏,选择对齐方式!");    public ToolBarTest()    {    for(int i=0;i<buttonArray.length;i++)    {    toolbar.add(buttonArray[i]);    //为按钮设置工具提示信息,当把鼠标放在其上时显示提示信息    buttonArray[i].setToolTipText(buttonArray[i].getText());    buttonArray[i].addActionListener(this);    }    toolbar.setFloatable(true);  //设置工具栏,true为可以成为浮动工具栏    this.add(toolbar,BorderLayout.NORTH);    this.add(jl);    this.setTitle("工具栏测试窗口");    this.setVisible(true);    this.setBounds(200,200,300,200);    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    }    public void actionPerformed(ActionEvent a)    {    if(a.getSource()==buttonArray[0])    {    jl.setHorizontalAlignment(JLabel.LEFT);    jl.setText("你选择的对齐方式为:"+buttonArray[0].getText()+"!");    }    if(a.getSource()==buttonArray[1])    {    jl.setHorizontalAlignment(JLabel.CENTER);    jl.setText("你选择的对齐方式为:"+buttonArray[1].getText()+"!");    }    if(a.getSource()==buttonArray[2])    {    jl.setHorizontalAlignment(JLabel.RIGHT);    jl.setText("你选择的对齐方式为:"+buttonArray[2].getText()+"!");    }    }    public static void main(String args[])    {    new ToolBarTest();    }}



1 0