Java 无法在工具栏中的按钮上查看图像

Java 无法在工具栏中的按钮上查看图像,java,swing,toolbar,imagebutton,Java,Swing,Toolbar,Imagebutton,几天以来,我一直在学习开发gui应用程序的swing 下面的代码旨在创建一个带有退出按钮(包括图像“exit.png”)的工具栏。问题是我无法看到图像,尽管出现了工具栏。使用java中的borderlayout管理器定位NORTH JMenuBar menubar = new JMenuBar(); JMenu file = new JMenu("File"); menubar.add(file); setJMenuBar(menubar); JToo

几天以来,我一直在学习开发gui应用程序的
swing

下面的代码旨在创建一个带有退出按钮(包括图像“exit.png”)的工具栏。问题是我无法看到图像,尽管出现了工具栏。使用java中的borderlayout管理器定位
NORTH

    JMenuBar menubar = new JMenuBar();
    JMenu file = new JMenu("File");

    menubar.add(file);
    setJMenuBar(menubar);

    JToolBar toolbar = new JToolBar();
    toolbar.setFloatable(false);

    ImageIcon exit = new ImageIcon("exit.png");
    JButton bexit = new JButton(exit);
    bexit.setBorder(new EmptyBorder(0, 0, 0, 0));
    toolbar.add(bexit);
    //Default layout manager for JFrame is BorderLayout Manager
    add(toolbar, BorderLayout.NORTH);
代码写在类构造函数中,类在其中扩展了
JFrame
swing类

请注意,我已经导入了所需的类。也没有编译错误。映像保存在创建.class的目录中。gui的其他元素显示时不会出现错误


请帮我找出问题所在。提前感谢。

首先创建您的图像图标

ImageIcon myIcon = createImageIcon("exit.png", "");
以及Oracle网站上的createImageIcon()方法的代码:

private ImageIcon createImageIcon(String path, String description) {
        URL imgURL = getClass().getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL, description);
       } else {
          System.err.println("Couldn't find file: " + path);
          return null;
       }
    }
然后将按钮的图标设置为:

bexit.setIcon(myIcon);

首先创建图像图标

ImageIcon myIcon = createImageIcon("exit.png", "");
以及Oracle网站上的createImageIcon()方法的代码:

private ImageIcon createImageIcon(String path, String description) {
        URL imgURL = getClass().getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL, description);
       } else {
          System.err.println("Couldn't find file: " + path);
          return null;
       }
    }
然后将按钮的图标设置为:

bexit.setIcon(myIcon);

该方法属于哪个类?与JFrame属于同一个类。还可以看看Oracle网站上的教程:找到答案了!!新的图像图标(getClass().getResource(“exit.png”);好答案+1。但是我总是在按钮上放置一个图标,JButton be=new JButton(new-ImageIcon(“exit.png”);并且可以工作。我认为PVB提供的代码段可以工作的原因是使用了ImageIcon的构造函数,只传递类型字符串(文件名),并将其用作按钮中匿名类的初始值设定项。-->+1,因为您为提出此问题的人做了很好的工作。但他仍然忘记单击右标记。关于此方法属于哪个类?与JFrame的类相同。还可以查看Oracle网站上的教程:获得答案!!new ImageIcon(getClass().getResource(“exit.png”);回答很好+1。但是我总是在按钮上放置一个图标,并使用JButton be=new JButton(new ImageIcon(“exit.png”);并且可以工作。我认为PVB提供的代码段工作的原因是使用了ImageIcon的构造函数,只传递类型字符串(文件名),并将其用作按钮中匿名类的初始值设定项。-->+1,因为您为请求它的人做了很好的工作。但他仍然忘记单击正确的标记。问候