0

I made a button in java but when I want to add an icon to the button it show a blank button.

public class T36 {

    public static void main(String[] args) {

        JFrame f = new JFrame("test 36");

        JTextField tf = new JTextField();
        tf.setBounds(40, 40, 80, 30);

        JButton b = new JButton(new ImageIcon("C:\\Java\\Test\\src\\test\\calculator1600.gif"));
        b.setBounds(40, 100, 200, 30);

        b.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                tf.setText("hello");
            }
        });
        f.add(tf);
        f.add(b);
        f.setLayout(null);
        f.setSize(400, 300);
        f.setVisible(true);
    }

}
Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60
Sara
  • 1
  • 1
  • Here's how to create and show a swing gui: https://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html. Here's how to use layout managers: https://docs.oracle.com/javase/tutorial/uiswing/layout/index.html. Don't use a null layout. And check that the image file indeed exists. – JB Nizet Sep 02 '17 at 10:47
  • when i resize the image it will show in the button but is there another way other than resizing? – Sara Sep 02 '17 at 11:36
  • Sure. Use layout managers. Here's how to use layout managers: https://docs.oracle.com/javase/tutorial/uiswing/layout/index.html. Don't use a null layout. – JB Nizet Sep 02 '17 at 11:36
  • `I want to add an icon to the button it show a blank button.` - then that means your program can't file the image file. Don't hardcode a full path name like that. It is not very flexible if you ever move the image. Instead read the section from the Swing tutorial on [How to Use Icons](http://docs.oracle.com/javase/tutorial/uiswing/components/icon.html) for a better way to load the image by treating it as a resource file. – camickr Sep 02 '17 at 13:25
  • If this is not a duplicate, please [edit] your question to include a [mcve] that shows your revised approach. – trashgod Sep 02 '17 at 18:31

0 Answers0