如何将ImageIcon添加到JToolBar

iss*_*lah 2 java swing jtoolbar imageicon

我正在尝试在工具栏中添加一个图标,但最好放在哪个位置?我的桌面或应该在项目文件中创建一个新文件或添加所有图片,因为它没有显示,这是我的代码:

 JToolBar toolBar = new JToolBar();
     String[] iconFiles = {"pen-icon","",""};
     String[] buttonLabels = {"New","Open","Save"};
     icon = new ImageIcon[iconFiles.length];
     Obutton = new JButton[buttonLabels.length];

     for (int i = 0; i < buttonLabels.length; ++i) {
      icon[i] = new ImageIcon(iconFiles[i]);
      Obutton[i] = new JButton(icon[i]);
      Obutton[i].setToolTipText(buttonLabels[i]);
      if (i == 3)
        toolBar.addSeparator();
         toolBar.add(Obutton[i]);
    }
Run Code Online (Sandbox Code Playgroud)

Pau*_*tha 6

我会用一个Action.这是AbstractAction构造函数

  • public AbstractAction(String name, Icon icon) - 使用指定的名称和小图标创建一个Action.

    参数:
    name - 操作的名称(Action.NAME); 忽略null值
    图标 - 动作的小图标(Action.SMALL_ICON); 忽略null值

使用a的好处Action是可以重用于具有类似用途的组件.所以说你想在工具栏中有一个图标按钮来打开一个文件,并且还有JMenuItem一个JMenu也可以打开一个文件.他们可以共享相同的操作,从而共享相同的图标,操作命令和要执行的操作.

Action action = new AbstractAction("someActionCommand", someIcon) {
    @Override
    public void actionPerformed(ActionEvent e) {
        // do something.
    }
};

toolbar.add(action);
Run Code Online (Sandbox Code Playgroud)

以上将自动为您设置图标,但不会为字符串.在JMenuItem它中它会放置字符串和图标.

然后只需添加Action到工具栏.


请参阅如何使用操作


要回答你真正的问题,正如@MadProgrammer所说,你应该将你的图像作为嵌入式资源加载,使用

 ImageIcon icon = new ImageIcon(MyClass.class.getResource("/resources/images/image.png"));
Run Code Online (Sandbox Code Playgroud)

/resources/images目录中src,并getResource()返回一个URL.在构建时,IDE应该将文件复制到类路径中.

 ProjectRoot
           src
               resources
                       images
                             image.png
Run Code Online (Sandbox Code Playgroud)

您会发现在使用文件系统中的文件时,部署时无法正常工作


这是一个例子,其中JMenuItemJToolBar按钮共享相同的动作.请注意,在JToolBar 所有我需要做的就是添加了Action,我不需要为它创建一个按钮.在没有 action命令的情况下JToolBar自动将其设为按钮

我从下面的文件结构中使用这个"open.gif"并使用

ImageIcon icon = new ImageIcon(
            ActionTest.class.getResource("/resources/image/open.gif"));
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

这是结果

在此输入图像描述

这是代码.请享用!

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;

public class ActionTest {

    public ActionTest() {
        ImageIcon openIcon = new ImageIcon(
                ActionTest.class.getResource("/resources/image/open.gif"));
        ImageIcon saveIcon = new ImageIcon(
                ActionTest.class.getResource("/resources/image/save.gif"));
        ImageIcon newIcon = new ImageIcon(
                ActionTest.class.getResource("/resources/image/new.gif"));

        Action openAction = new AbstractAction("Open", openIcon) {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Open File");
            }
        };
        Action saveAction = new AbstractAction("Save", saveIcon) {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Save File");
            }
        };
        Action newAction = new AbstractAction("New", newIcon) {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("New File");
            }
        };

        JMenuItem openMenuItem = new JMenuItem(openAction);
        JMenuItem saveMenuItem = new JMenuItem(saveAction);
        JMenuItem newMenuItem = new JMenuItem(newAction);

        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");
        fileMenu.add(openMenuItem);
        fileMenu.add(saveMenuItem);
        fileMenu.add(newMenuItem);
        menuBar.add(fileMenu);

        JToolBar toolBar = new JToolBar();
        toolBar.add(Box.createHorizontalGlue());
        toolBar.setBorder(new LineBorder(Color.LIGHT_GRAY, 1));
        toolBar.add(newAction);
        toolBar.add(openAction);
        toolBar.add(saveAction);

        JFrame frame = new JFrame("Toolbar and Menu Test");
        frame.setJMenuBar(menuBar);
        frame.add(toolBar, BorderLayout.PAGE_START);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationByPlatform(true);
        frame.setVisible(true);

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ActionTest();
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @AndrewThompson欢迎乘坐.虽然标题与问题不符,但总是很好:D (2认同)

Mad*_*mer 5

此类资源通常最好包含在应用程序上下文中(例如jar文件).这减少了有人篡改它的机会,因为解压缩,修改和重新打包jar文件然后简单地替换文件要花费更多时间.它还可以减少您需要分发的内容,因为它变得独立.

这些被称为嵌入式资源.

你将它们放在这个上下文中的位置是很多,很多人使用"资源"文件夹来存储这些类型的文件,但有时候,你可能想要一些与类的上下文相关的东西.由你决定.

这会引发加载这些资源的问题,因为您无法再使用类似的东西来引用它们File.

通常你可以使用Class#getResource(String),返回一个URLClass#getResourceAsStream(String)返回一个InputStream.这为您提供了加载这些嵌入资源所需的一切.

ImageIcon(String)期望该值是一个文件引用,这意味着它不适用于嵌入式资源,但ImageIcon提供了一个构造函数,它将URL一个引用作为参考,这意味着您需要使用

icon[i] = new ImageIcon(getClass().getResource(iconFiles[i]));
Run Code Online (Sandbox Code Playgroud)

加载图片.

根据您的示例,图像需要相对于类(即在与包结构相同的目录结构中).如何实现这一点取决于您的开发环境.

请记住,您还可以getResource在某些上下文中指定相对路径,甚至是绝对路径.绝对路径basic在搜索资源时将类路径的元素添加到指定路径的前缀.