How to add ImageIcon to JToolBar


Islam Akira

I'm trying to add an icon to a toolbar, but what's the best place to put it? My desktop, or should I create a new file in the project file or add all the pictures, because it's not showing, so here is my code:

 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]);
    }
Paul Samsota

I would use one Action. this is the AbstractActionconstructor

  • public AbstractAction(String name, Icon icon)- Create an action with the specified name and small icon.

    Parameters:
    name - the action name (Action.NAME); the icon with a value of null
    will be ignored - the small icon of the action (Action.SMALL_ICON); a null value will be ignored

The benefit of using an Actionis that it can be reused for a component with a similar purpose. So, say, you want to have an icon button in the toolbar that opens a file, and also have an icon button JMenuItemin JMenuthat that also opens a file. They can share the same action, and thus the same icon, action command, and action to perform.

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

toolbar.add(action);

The code above will automatically show you the icon, but not the String. It JMenuItemwill place both the string and the icon in it.

Then just add Actionto the toolbar.


See more in " How to Use Actions"


To answer your real question, as @MadProgrammer pointed out, you should load your images as embedded resources , using

 ImageIcon icon = new ImageIcon(MyClass.class.getResource("/resources/images/image.png"));

in a /resources/imagesdirectory src, and getResource()returns a URL. After building, the IDE should copy the files to your classpath.

 ProjectRoot
           src
               resources
                       images
                             image.png

You will find that when using files from the file system, it will not be available after deployment


Here is an example where the same action is shared JMenuItemwith JToolBarthe button. Note that after JToolBar all I had to do was add it Action, I didn't need to create a button for it. This JToolBarautomatically makes it a button with no action command

I use "open.gif" in the following file structure and use

ImageIcon icon = new ImageIcon(
            ActionTest.class.getResource("/resources/image/open.gif"));

enter image description here

this is the result

enter image description here

Here is the code. enjoy your meal!

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();
            }
        });
    }
}

Related


How to add ImageIcon to object?

only I have object "team" which contains some score variables, name (string) and logo. The logo is of type ImageIcon: public class Team { public String name; public ImageIcon logo; public int points; public int plusGoals; public int minGoa

How to add gap between two buttons in JToolBar?

username I need to add a simple gap/spacer/margin to allow space between these two buttons. Unfortunately, I can't get it to work. Can someone give me some advice? It's based on BorderLayout, the button is located atJToolBar Andrew Thompson See which:JToolBar.

How to auto hide JToolBar?

arrogance I want to do auto-hide JToolBarand only show when the mouse is near/over JToolBar. I have added JToolBarin JPanel. There is no mouseover listener in JToolBar. How to do this? MartinZ: MouseMotionListenerAdd one to JFrameor JDialog. addMouseMotionList

How to disable dragging of JToolbar?

Philip Morris How to disable dragging of JToolbar? I put it in a BorderLayout. I am trying to find a way. Is there such a way? thanks Carmichael I think you are looking for: toolBar.setFloatable( false);

How to disable dragging of JToolbar?

Philip Morris How to disable dragging of JToolbar? I place it in a BorderLayout. I am trying to find a way. Is there such a way? thanks Carmichael I think you are looking for: toolBar.setFloatable( false);

How to auto hide JToolBar?

arrogance I want to do auto-hide JToolBarand only show when the mouse is near/over JToolBar. I have added JToolBarin JPanel. There is no mouseover listener in JToolBar. How to do this? MartinZ: MouseMotionListenerAdd one to JFrameor JDialog. addMouseMotionList

How to disable dragging of JToolbar?

Philip Morris How to disable dragging of JToolbar? I put it in a BorderLayout. I am trying to find a way. Is there such a way? thanks Carmichael I think you are looking for: toolBar.setFloatable( false);

How to disable dragging of JToolbar?

Philip Morris How to disable dragging of JToolbar? I place it in a BorderLayout. I am trying to find a way. Is there such a way? thanks Carmichael I think you are looking for: toolBar.setFloatable( false);

How to auto hide JToolBar?

arrogance I want to do auto-hide JToolBarand only show when the mouse is near/over JToolBar. I have added JToolBarin JPanel. There is no mouseover listener in JToolBar. How to do this? MartinZ: MouseMotionListenerAdd one to JFrameor JDialog. addMouseMotionList

How to disable dragging of JToolbar?

Philip Morris How to disable dragging of JToolbar? I put it in a BorderLayout. I am trying to find a way. Is there such a way? thanks Carmichael I think you are looking for: toolBar.setFloatable( false);

How to display ImageIcon in JButton?

Yang Weiye: public ImageIcon getIcon(){ return button.getIcon(); } public void moveTo(Square j){ JButton current = new JButton(); current = button; button.setIcon(j.getIcon()); button.setIcon(current.getIcon()); } Here is the problem. The Butt

How to resize JLabel ImageIcon?

Marcos Roriz Junior: I'm making a Java Swing application with the following layout ( ) :MigLayout [icon][icon][icon][....] where icon = jlabel and the user can add more icons As the user adds or removes icons, other icons should shrink or grow. My question is

How to rotate imageIcon in Java

Faliz I am creating a dominoes game in Java. I have the following code to load, resize, and then display a domino image on the screen: ImageIcon imageIcon = new ImageIcon("images\\4-4.png"); Image image = imageIcon.getImage(); Image newimg = image.getScaledIn

How to display ImageIcon in JButton?

Yang Weiye: public ImageIcon getIcon(){ return button.getIcon(); } public void moveTo(Square j){ JButton current = new JButton(); current = button; button.setIcon(j.getIcon()); button.setIcon(current.getIcon()); } Here is the problem. The Butt

How to display ImageIcon in JButton?

Yang Weiye: public ImageIcon getIcon(){ return button.getIcon(); } public void moveTo(Square j){ JButton current = new JButton(); current = button; button.setIcon(j.getIcon()); button.setIcon(current.getIcon()); } Here is the problem. The Butt

How to display ImageIcon in JButton?

Yang Weiye: public ImageIcon getIcon(){ return button.getIcon(); } public void moveTo(Square j){ JButton current = new JButton(); current = button; button.setIcon(j.getIcon()); button.setIcon(current.getIcon()); } Here is the problem. The Butt

How to resize JLabel ImageIcon?

Marcos Roriz Junior: I'm making a Java Swing application with the following layout ( ) :MigLayout [icon][icon][icon][....] where icon = jlabel and the user can add more icons As the user adds or removes icons, other icons should shrink or grow. My question is

How to display ImageIcon in JButton?

Yang Weiye: public ImageIcon getIcon(){ return button.getIcon(); } public void moveTo(Square j){ JButton current = new JButton(); current = button; button.setIcon(j.getIcon()); button.setIcon(current.getIcon()); } Here is the problem. The Butt

How to display ImageIcon in JButton?

Yang Weiye: public ImageIcon getIcon(){ return button.getIcon(); } public void moveTo(Square j){ JButton current = new JButton(); current = button; button.setIcon(j.getIcon()); button.setIcon(current.getIcon()); } Here is the problem. The Butt

How to rotate imageIcon in Java

Faliz I am creating a dominoes game in Java. I have the following code to load, resize, and then display a domino image on the screen: ImageIcon imageIcon = new ImageIcon("images\\4-4.png"); Image image = imageIcon.getImage(); Image newimg = image.getScaledIn

How to store ImageIcon in Java

pioupiou1211 I have a matrix of n*n JButton, in JPanel. Currently, I'm setting ImageIconevery content that changes over time JButton. It's not a simple ImageIcon, but 2 images overlapping the function: public ImageIcon DoubleImage(BufferedImage eau, BufferedIm

Click a button to add an ImageIcon to an already visible GUI

Wagner I'm a little confused as to why my program is not working. I am trying to add an image to the frame when the button is clicked. I have verified in Java that the file exists and the photo can be found. I also verified that the button works. But when I co

Unable to add image to jTable cell using ImageIcon

Molybdenum 35 I'm trying to add an image to a cell using a ImageIconclass , but I'm in the code I'm trying in the cell where it should display the image:jTablesun.awt.image.ToolkitImage@196a4632 JTable jTable; String[] columns={"Page No","Chapter","Image

Java Swing: How does JToolbar change the appearance of buttons?

Paranoia 25: When a JButton is added to a JToolbar, the button has a specific appearance (unlike when it is added to a Jpanel). I have created some components similar to JToolbar and I want the same behavior. Problem: I checked the JToolbar class to find some

Java Swing: How does JToolbar change the appearance of buttons?

Paranoia 25: When a JButton is added to a JToolbar, the button has a specific appearance (unlike when it is added to a Jpanel). I have created some components similar to JToolbar and I want the same behavior. Problem: I checked the JToolbar class to find some

Java Swing: How does JToolbar change the appearance of buttons?

Paranoia 25: When a JButton is added to a JToolbar, the button has a specific appearance (unlike when it is added to a Jpanel). I have created some components similar to JToolbar and I want the same behavior. Problem: I checked the JToolbar class to find some

Convert ImageIcon to BufferedImage (how to set image type)

grandson What I'm doing is a very simple image editing program, but I'm running into a problem. I save the image in DB and convert it ImageIconso that it can go through server socket etc (serializable). So with VO I get the ImageIconGUI and convert it to Buffe