There is a class

public class AddOpenButtons extends JButton { public AddOpenButtons() { JButton buttonAdd = new JButton("New Button"); ImageIcon icon1 = createIcon("images/edit-add.png"); buttonAdd.setIcon(icon1); buttonAdd.setHorizontalTextPosition(SwingConstants.LEFT); buttonAdd.setSize(new Dimension(300, 100)); } protected ImageIcon createIcon(String path) { URL imgURL = AddOpenButtons.class.getResource(path); if (imgURL != null) { return new ImageIcon(imgURL); } else { System.err.println("File not found " + path); return null; } } } 

Then in the frame class I create a new button.

 public class MainFrame extends JFrame{ private AddOpenButtons button1; public final int width = 400; public final int height = 400; //Конструктор public MainFrame(){ setSize(width, height); //Создаём панель для отображения кнопок panel = new JPanel(); // Добавляем button к панели button1 = new AddOpenButtons(); panel.add(button1); // Добавляем панель к фрейму add(panel); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); } 

The button is displayed without a name and a picture + writes that the picture was not found, the picture lies in a subpackage of the class images. I create everything in eclipse ... Something stupid a little, tell me what I'm doing wrong ??

  • one
    ImageIcon icon1 = createIcon ("images / edit-add.png"); And if you set the absolute path to the picture, it also does not work? - Valeriy Karchov
  • no ... - Kobayashi_Maru
  • Or maybe such that when creating a button in a frame, the default JButton constructor is defined in my place and therefore an empty button is created ?? (45 minutes ago) AleXpi - Kobayashi_Maru

1 answer 1

The images folder should be in the same folder as the src folder.
UPD : What is bad option ImageIcon icon = new ImageIcon("images/middle.gif") ?

  • Or maybe such that when creating a button in a frame, the default JButton constructor is defined and therefore an empty button is created ?? - Kobayashi_Maru