ITEEDU

12-6-2:在JToolBar组件中加入ToolTip:

相信大多数人都有使用过Word文书编辑软件的经验,当我们在使用Word的工具栏时会发现到有一些功能是比较不常用的,而且光 看工具栏上的图标文件也无法立刻得知该图标文件代表什么功能.这时候,我们通常会把鼠标指针移到该图标文件上,稍等待1-2秒后 就会出现一个小提示让我们知道这个图标文件是代表什么意义.这个小提示就是ToolTip.

那么我们在JToolBar中该如何使用这种功能呢?我们来看下面这个范例.这个范例延伸自JToolBar1.java.因此我们只列出 buildToolBar()方法的部份,其他部份的程序都没有改变.

	public JToolBar buildToolBar() {
	  
	  JToolBar toolBar = new JToolBar();
      toolBar.setFloatable(true);
    
	  ToolBarAction tba_new   = new ToolBarAction("new",new ImageIcon("icons/new24.gif"));
	  ToolBarAction tba_open  = new ToolBarAction("open",new ImageIcon("icons/open24.gif"));
	  ToolBarAction tba_close = new ToolBarAction("close",new ImageIcon("icons/close24.gif"));
    
	  JButton JB;
	  JB = toolBar.add(tba_new);
      //只需要利用setToolTipText()这个方法即可,利用getValue()方法取得各个ToolBarAction类的名称来当作ToolTip显示的字
      //符串.
	  JB.setActionCommand("#TooBar_NEW performed!");
	  JB.setToolTipText((String)tba_new.getValue(Action.NAME));
	  JB = toolBar.add(tba_open);
	  JB.setActionCommand("#ToolBar_OPEN performed!");
	  JB.setToolTipText((String)tba_open.getValue(Action.NAME));
	  JB = toolBar.add(tba_close);
	  JB.setActionCommand("#ToolBar_CLOSE performed!");
	  JB.setToolTipText((String)tba_close.getValue(Action.NAME));
    
	  toolBar.addSeparator();
        
	  ToolBarAction tba_B  = new ToolBarAction("bold",new ImageIcon("icons/bold24.gif"));
	  ToolBarAction tba_I  = new ToolBarAction("italic",new ImageIcon("icons/italic24.gif"));
	  ToolBarAction tba_U  = new ToolBarAction("underline",new ImageIcon("icons/underline24.gif")); 
	  JB = toolBar.add(tba_B);
	  JB.setActionCommand("#ToolBar_Bold performed!");
	  JB.setToolTipText((String)tba_B.getValue(Action.NAME));
	  JB = toolBar.add(tba_I);
	  JB.setActionCommand("#ToolBar_Italic performed!");
	  JB.setToolTipText((String)tba_I.getValue(Action.NAME));    
	  JB = toolBar.add(tba_U);
	  JB.setActionCommand("#ToolBar_Underline performed!");
	  JB.setToolTipText((String)tba_U.getValue(Action.NAME));
   
	  toolBar.addSeparator();    
	  JLabel JLfont = new JLabel("Font Type");
	  toolBar.add(JLfont);
	  toolBar.addSeparator();
	  JComboBox jcb = new JComboBox(ComboStr);
	  jcb.addActionListener(new ActionListener() {
	                    	  public void actionPerformed(ActionEvent e) {
			   	                theArea.append("*Combobox "+((JComboBox)e.getSource()).getSelectedItem()+" performed!\n");
	                   	    }});
	  toolBar.add(jcb);
	
	  return toolBar;
	}//end of buildToolBar()