How do I add an image to a JButton in Java Swing?

Aled

New member
This is the line of code that I'm not sure is valid or not: JButton button1 = new JButton(new ImageIcon("Pictures/smiley.png"));

I am using GridBagLayout so I'm not sure whether it has anything to do with that.

What happens is it just causes the button to become thinner in height, and the image isn't displayed, some suggestion to what I'm doing wrong?

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

public class window{
public static void main(String[] args){

JFrame frame = new JFrame("Cartoon Maker");
frame.setVisible(true);
frame.setSize(800,500);

JToolBar toolbar = new JToolBar("Toolbar", JToolBar.HORIZONTAL);

JButton exit = new JButton("Exit");
toolbar.add(exit);

JButton load = new JButton("Load");
toolbar.add(load);

JButton save = new JButton("Save");
toolbar.add(save);

JButton about = new JButton("About");
toolbar.add(about);

frame.getContentPane().add(toolbar, BorderLayout.SOUTH);

JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(100,100,100,100);
frame.add(panel);

JButton button1 = new JButton(new ImageIcon("Pictures/smiley.png"));
c.gridx = 0;
c.gridy = 0;
panel.add(button1, c);


JButton button2 = new JButton("2");
c.gridx = 2;
c.gridy = 0;
panel.add(button2, c);

JButton button3 = new JButton("3");
c.gridx = 4;
c.gridy = 0;
panel.add(button3, c);

JButton button4 = new JButton("4");
c.gridx = 6;
c.gridy = 0;
panel.add(button4, c);

JButton button5 = new JButton("5");
c.gridx = 0;
c.gridy = 5;
panel.add(button5, c);

JButton button6 = new JButton("6");
c.gridx = 2;
c.gridy = 5;
panel.add(button6, c);

JButton button7 = new JButton("7");
c.gridx = 4;
c.gridy = 5;
panel.add(button7, c);

JButton button8 = new JButton("8");
c.gridx = 6;
c.gridy = 5;
panel.add(button8, c);

class exitaction implements ActionListener{
public void actionPerformed(ActionEvent e){
System.exit(0);
}
}

class aboutaction implements ActionListener{
public void actionPerformed(ActionEvent e){
JFrame frame2 = new JFrame("About Cartoon Maker");
frame2.setVisible(true);
frame2.setSize(800,500);
JTextArea jt = new JTextArea ("About");
frame2.add(jt);
}
}

exit.addActionListener(new exitaction());
about.addActionListener(new aboutaction());
}
}

I've just started programming the programme so it isn't much at all yet.
 
Back
Top