如何从源文件夹添加和映像到JFrame?

时间:2014-02-13 15:19:52

标签: java swing

我尝试了很多方法将Jpg图像添加到Jframe中但没有成功,代码将编译但图像不会出现。图像存储在项目的源文件中!谢谢你的帮助。

public class GordonsWindow extends JFrame {
    public GordonsWindow() {
        JMenuBar menuBar = new JMenuBar();
        JMenu menuFile = new JMenu();
        JMenu menuStores = new JMenu();
        JMenuItem menuFileExit = new JMenuItem();

        JMenuItem menuStoresArmagh = new JMenuItem();

        JPanel paneStores = new JPanel(new FlowLayout());
        paneStores = new JPanel();
        paneStores.setPreferredSize(new Dimension(500,300));
        paneStores.setBackground(Color.blue);
        JButton ArmaghButton = new JButton();
        ImageIcon icon = new ImageIcon("Gordons.jpg"); 
        JLabel label = new JLabel(); 
        label.setIcon(icon);        

        ArmaghButton.setText("Armagh");

        paneStores.add(ArmaghButton);
        paneStores.add(label);

        add(paneStores);

        menuFile.setText("File");
        menuFileExit.setText("Exit");

        menuStores.setText("Stores");
        menuStoresArmagh.setText("Armagh");

        ArmaghButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Armagh.windowActivated();
            }
        });

        menuFileExit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                GordonsWindow.this.windowClosed();
            }
        });

        menuFile.add(menuFileExit);
        menuBar.add(menuFile);

        menuBar.add(menuStores);
        menuStores.add(menuStoresArmagh);

        setTitle("Gordons Chemists Application");
        setJMenuBar(menuBar);
        setSize(new Dimension(800, 800));

        //Add Window Listener
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                GordonsWindow.this.windowClosed();
            }
        });
    }

    protected void windowClosed() {
        System.exit(0);
    }
}

2 个答案:

答案 0 :(得分:2)

您想通过类路径加载它。简单地

ImageIcon icon = new ImageIcon(GordonsWindow.class.getResource("/images/Gordons.jpg");

images直接位于src

ProjectRoot
         src
            images
                 Gordons.jpg

答案 1 :(得分:0)

抱歉;错过了label.seticon()示例中不需要的其他代码。

下次使用SSCCE

然后你需要以某种方式在组件上绘制它;

我使用的方法是:

JPanel imageholder=new JPanel()
        {
            protected void paintComponent(Graphics g)
            {
                super.paintComponent( g)
                g.drawImage(ImageVariable,0,0);
            }
        };
        j.setBounds(<insert size here>);