How to Add an Image to a Jbutton

How do I add an image to a JButton

I think that your problem is in the location of the image. You shall place it in your source, and then use it like this:

  JButton button = new JButton();
try {
Image img = ImageIO.read(getClass().getResource("resources/water.bmp"));
button.setIcon(new ImageIcon(img));
} catch (Exception ex) {
System.out.println(ex);
}

In this example, it is assumed that image is in src/resources/ folder.

How to put an image on a JButton?

While using Eclipse, you don't keep your images into src folder instead you create a Source Folder for this purpose. Please refer to this link regarding how to add images to resource folder in Eclipse.

I can't add Image to a JButton in Java

You cannot load external files like 'C:\test\image\b.jpg' by using getClass().getResource(...).

But ImageIcon as a nice constructor that loads an image from is path.
Use something like this instead:

Icon b = new ImageIcon("C:\\temp\\image\\b.jpg");

How to Add a url Image to a JButton

Just use the JButton Icon constructor, and pass it an ImageIcon.

E.g. instead of

JButton button = new JButton("want picture here");

do

JButton button = new JButton(new ImageIcon(new URL("http://i68.tinypic.com/2itmno6.jpg")));

Since the URL constructor throws a MalformedURLException, you'll also need to wrap this in a try-catch block (and put your button use statements in there as well). To scale it, you also need some extra calls. Additionally, you can remove the visible parts of the button completely, by removing border and content. Since you have a JPanel behind the button, you'll need to set that to be transparent as well. The full code is below:

try {
JButton button = new JButton(new ImageIcon(((new ImageIcon(
new URL("http://i68.tinypic.com/2itmno6.jpg"))
.getImage()
.getScaledInstance(64, 64, java.awt.Image.SCALE_SMOOTH)))));
button.setBorder(BorderFactory.createEmptyBorder());
button.setContentAreaFilled(false);
panel.setOpaque(false);
panel.add(button);

button.addActionListener(new Action7());
}
catch (MalformedURLException e) {
// exception handler code here
// ...
}

64x64 are the image dimensions here, simply change them to the desired dimensions for your image.

Adding image to JButton

Two things

  1. The path looks wrong
  2. Java doesn't, natively, support the ico format

Take a look at the path, there is quote mark in the path

C:\\Users\\Aksi\\Documents\\NetBeansProjects\\test'\\src\\test\\Black_B.ico

Just be sure it's suppose to be there or not

How to set a image icon to JButton?

The issue can be resolved by prefixing the resource path with a slash:

Image play = ImageIO.read(getClass().getResource("/images/play.png"));

This denotes that the image folder is at the root location of all resources and not relative to the current class location.

Credits partially go to Andrew Thompson's comment.

Adding an image to a frame by button press

The problem is that you are creating a new JLabel and trying to add it to the frame, once the button is pressed. Instead, you should just change the Icon of the label that is already added to the frame (i.e., piclabel), using piclabel.setIcon(icon);. So, you should declare picLabel at the start of your code, so that it can be accessible in the actionPerformed method of your button.

public class Mainframe {

private JFrame frmOceanlife;
JLabel piclabel;
...

Then, instantiate the label in the initialize() method as below:

...
panel.setBounds(70, 75, 600, 450);
panel.setLayout(new FlowLayout());
piclabel = new JLabel(new ImageIcon("underwater-600x450.png"));
...

Finally, your actionPerformed method for btnNewButton_5 (please consider using descriptive names instead) should look like this:

btnNewButton_5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ImageIcon icon = new ImageIcon("Stone.png");
piclabel.setIcon(icon);

}
});

Update

If, however, what you want is to add a new JLabel each time, and not change the icon of the existing one, you could use Box object with BoxLayout added to a ScrollPane. Then add the ScrollPane to your JFrame. Working example is shown below, based on the code you provided (again, please consider using descriptive names and removing unecessary code):

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.*;
import javax.swing.*;

public class Mainframe {

private JFrame frmOceanlife;
Box box;
JScrollPane scrollPane;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Mainframe mf = new Mainframe();
mf.initialize();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Initialize the contents of the frame.
*/
private void initialize() {

JButton insertBtn = new JButton("Einfügen");
insertBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ImageIcon icon = new ImageIcon("Stone.png");
JLabel label = new JLabel(icon);
box.add(Box.createRigidArea(new Dimension(0, 5)));// creates space between the JLabels
box.add(label);
frmOceanlife.repaint();
frmOceanlife.revalidate();
Rectangle bounds = label.getBounds();
scrollPane.getViewport().scrollRectToVisible(bounds);// scroll to the new image

}
});

JButton quitBtn = new JButton("Quit");
quitBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});

box = new Box(BoxLayout.Y_AXIS);
JLabel piclabel = new JLabel(new ImageIcon("underwater-600x450.png"));
box.add(piclabel);

scrollPane = new JScrollPane(box);
Dimension dim = new Dimension(box.getComponent(0).getPreferredSize());
scrollPane.getViewport().setPreferredSize(dim);
scrollPane.getVerticalScrollBar().setUnitIncrement(dim.height);
scrollPane.getViewport().setBackground(Color.WHITE);

JPanel controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
controlPanel.add(insertBtn);
controlPanel.add(quitBtn);

JLabel titleLbl = new JLabel("Welcome to Oceanlife - Your Ocean size is 600x450!", SwingConstants.CENTER);

frmOceanlife = new JFrame();
frmOceanlife.getContentPane().add(titleLbl, BorderLayout.NORTH);
frmOceanlife.getContentPane().add(scrollPane, BorderLayout.CENTER);
frmOceanlife.getContentPane().add(controlPanel, BorderLayout.SOUTH);
frmOceanlife.setTitle("OceanLife");
frmOceanlife.pack();
frmOceanlife.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmOceanlife.setLocationRelativeTo(null);
frmOceanlife.setVisible(true);

}
}

How to put a JButton with an image on top of another JButton with an image?

The simplest solution is this

JButton j1=new JButton("a");
j1.setLayout(new BorderLayout());
j1.setBackground(Color.red);
add(j1);
JButton j2=new JButton("b");
j2.setBackground(Color.yellow);
j1.add("Center", j2);

--

Although generally not to be used, the null layout is a solution here if you want to specify specific location and size:

JButton j1=new JButton("a");
j1.setLayout(null);
j1.setBackground(Color.red);
JButton j2=new JButton("b");
j2.setBackground(Color.yellow);
j2.setBounds(100, 100, 50, 50);
j1.add(j2);
add(j1);


Related Topics



Leave a reply



Submit