相关代码如下:
class ExitAction  extends AbstractAction{
   public ExitAction(){
     super("退出",new ImageIcon(this.getClass().getResource("exit.gif")));
   }
   public void actionPerformed(ActionEvent e){
     jMenuFileExit_actionPerformed(e);
   }
}
jToolBar1.add(new ExitAction());只能显示图标,而没有显示“退出”的文字,而如果将传进去的图标设为null就显示出来了,这是为什么?

解决方案 »

  1.   


    class OpenAction extends AbstractAction{
        public OpenAction(){
            super("打开",new ImageIcon("open.jpg"));
        }    public void actionPerformed(ActionEvent e){
            ...
        }
    }JToolBar toolbar = new JToolBar();
    toolbar.add(new OpenAction());
    ???
      

  2.   

    加到 JToolbar的 action 有图标不显示文字。加个 JButton试试
      

  3.   

    图标会覆盖文字的,如果你要既显示文字又显示图片,你可以给AbstractAction添加一个描述,把文字显示在描述里,图标显示在按钮上描述的显示方法是:把鼠标移动到该图标上,过一会儿你就会看到一行字显示出来
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;public class ToolBarFrameTest extends JFrame
    {
    public ToolBarFrameTest()
    {
    this.setPreferredSize(new Dimension(300, 200));

    JToolBar toolBar = new JToolBar();
    toolBar.add(new ExitAction());
    add(toolBar, BorderLayout.NORTH);
    }

    private class ExitAction extends AbstractAction
    {
    public ExitAction()
    {
    super("退出", new ImageIcon("d:\\exit.jpg"));
    putValue(Action.SHORT_DESCRIPTION, "退出"); //这里添加描述
    }

    public void actionPerformed(ActionEvent event)
    {

    }
    }

    public static void main(String[] args)
    {
    EventQueue.invokeLater(new Runnable()
    {
    public void run()
    {
    JFrame frame = new ToolBarFrameTest();
    frame.pack();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    });
    }
    }
      

  4.   

    用JButton的话确实可以实现,只是我的用的图标太多有时同一功能的图标有好几个,这样写简洁一点.刚才在一个论坛看到说:
    JToolBar的createActionComponent方法中
                                有一句
    if (icon !=null) {
       b.putClientProperty("hideActionText", Boolean.TRUE);
    }
    这句导致文字不显示!
    这样决定可能是因为一般默认的工具栏不显示文字的"
    可能是原因吧!