简体   繁体   English

向JFrame添加图像时出现问题

[英]problem in adding image to JFrame

I'm having problems in adding a picture into JFrame, something is missing probebly or written wrong. 我在将图片添加到JFrame时遇到问题,有些东西遗漏或写错了。 here are the classes: 这是课程:

main class: 主类:

public class Tester

    {
        public static void main(String args[])
        {
            BorderLayoutFrame borderLayoutFrame = new BorderLayoutFrame();
            borderLayoutFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            borderLayoutFrame.setSize(600,600);
            borderLayoutFrame.setVisible(true);
        }
    }

public class BorderLayoutFrame extends JFrame implements ActionListener 
 {
     private JButton buttons[]; // array of buttons to hide portions
     private final String names[] = { "North", "South", "East", "West", "Center" };
     private BorderLayout layout; // borderlayout object
     private PicPanel picture = new PicPanel();

     // set up GUI and event handling

     public BorderLayoutFrame()
     {
         super( "Philosofic Problem" );
         layout = new BorderLayout( 5, 5 ); // 5 pixel gaps
         setLayout( layout ); // set frame layout
         buttons = new JButton[ names.length ]; // set size of array

         // create JButtons and register listeners for them

         for ( int count = 0; count < names.length; count++ ) 
         {
             buttons[ count ] = new JButton( names[ count ] );
             buttons[ count ].addActionListener( this );
         }
         add( buttons[ 0 ], BorderLayout.NORTH ); // add button to north
         add( buttons[ 1 ], BorderLayout.SOUTH ); // add button to south
         add( buttons[ 2 ], BorderLayout.EAST ); // add button to east
         add( buttons[ 3 ], BorderLayout.WEST ); // add button to west
         add( picture, BorderLayout.CENTER ); // add button to center
    }

    // handle button events

    public void actionPerformed( ActionEvent event )
    {

    } 

  }

I'v tried to add the image into the center of layout. 我试图将图像添加到布局的中心。

here is the image class: 这是图像类:

public class PicPanel extends JPanel
{
    Image img;
    private int width = 0;
    private int height = 0;

    public PicPanel()
    {
        super();
        img = Toolkit.getDefaultToolkit().getImage("table.jpg");
    }
    public void paintComponent(Graphics g)
    {
         super.paintComponents(g);
         if ((width <= 0) || (height <= 0))
         {
             width = img.getWidth(this);
             height = img.getHeight(this);
         }
         g.drawImage(img,0,0,width,height,this);
    }
}

Please your help, what is the problem? 请您的帮助,什么问题? thanks 谢谢

BTW: i'm using eclipse, which directory the image suppose to be in? 顺便说一句:我正在使用eclipse,图像应该位于哪个目录?

There's several issues with the code you've posted: 您发布的代码存在几个问题:

  • You should use getContentPane().add() instead of simply add() in your BorderLayoutFrame class. 您应该在BorderLayoutFrame类中使用getContentPane().add()而不是简单的add()
  • You should really use SwingUtilities.invokeLater() to launch your JFrame from the tester class. 您实际上应该使用SwingUtilities.invokeLater()从测试器类启动JFrame。 Something like this: 像这样:

 SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        System.setProperty("DEBUG_UI", "true");

        BorderLayoutFrame blf = new BorderLayoutFrame();
        blf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        blf.setSize(600,600);
        blf.setVisible(true);
    }
});
  • Don't use Toolkit to load images! 不要使用工具包加载图像! In the following code, if "Table.jpg" is in the same package as PicPanel, the image will correctly load. 在下面的代码中,如果“ Table.jpg”与PicPanel位于同一程序包中,则将正确加载图像。

public PicPanel() {
    super();
    try {
        rUrl = getClass().getResource("Table.jpg");
        if (rUrl != null) {
            img = ImageIO.read(rUrl);
        }
    } catch (IOException ex) {
        Logger.getLogger(PicPanel.class.getName()).log(Level.SEVERE, null, ex);
    }
}
  • In PicPanel.PaintComponent() you call super.paintComponents() is the 's' a typeo? PicPanel.PaintComponent()您称super.paintComponents()是's'是typeo吗?
  • In PicPanel.PaintComponent() , you don't need all the width/height stuff, just do this: PicPanel.PaintComponent()并不需要所有的宽度/高度的东西,只是这样做:

    g.drawImage(img, 0, 0, getWidth(), getHeight(), this);

And avoid the call to super.paintComponent all together because you're painting an image, why do you want the panel to paint at all? 并避免一起调用super.paintComponent,因为您正在绘制图像,为什么要让面板完全绘制?

My final implementation of your stuff: 我对您的东西的最终实现:

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                System.setProperty("DEBUG_UI", "true");

                BorderLayoutFrame blf = new BorderLayoutFrame();
                blf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                blf.setSize(600,600);
                blf.setVisible(true);
            }
        });
    }

}

class BorderLayoutFrame extends JFrame implements ActionListener
{
    private final BorderLayout layout;
    private final JButton[] buttons;
    private final String names[] = {"North", "South", "East", "West", "Center"};

    public BorderLayoutFrame() {
        super( "Philosofic Problem" );
        layout = new BorderLayout( 5, 5 );
        getContentPane().setLayout( layout );
        buttons = new JButton[ names.length ];

        for (int i=0; i<names.length; i++)
        {
            buttons[i] = new JButton(names[i]);
            buttons[i].addActionListener(this);
        }

        getContentPane().add(buttons[0], BorderLayout.NORTH);
        getContentPane().add(buttons[1], BorderLayout.SOUTH);
        getContentPane().add(buttons[2], BorderLayout.EAST);
        getContentPane().add(buttons[3], BorderLayout.WEST);
        getContentPane().add(new PicPanel(), BorderLayout.CENTER);
    }

    public void actionPerformed(ActionEvent e) {
        // ignore
    }

}

class PicPanel extends JPanel
{
    private URL rUrl;
    private BufferedImage img;



    public PicPanel() {
        super();
        try {
            rUrl = getClass().getResource("UtilBtn.png");
            if (rUrl != null) {
                img = ImageIO.read(rUrl);
            }
        } catch (IOException ex) {
            Logger.getLogger(PicPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        //super.paintComponent(g);

        g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
    }

}

In Eclipse, if you are using the path "table.jpg" then you need that image to be at the top level of the project. 在Eclipse中,如果您使用路径"table.jpg"则需要将该图像置于项目的顶层。

For a bit more info on the Eclipse project structure see this Stack Overflow question. 有关Eclipse项目结构的更多信息,请参见此Stack Overflow问题。

You may want to try using an ImageIcon to display the image instead of drawing it on the panel. 您可能要尝试使用ImageIcon来显示图像,而不是在面板上绘制图像。

The following code will create an ImageIcon that you can just add to the JPanel . 以下代码将创建一个ImageIcon ,您可以将其添加到JPanel

ImageIcon pic = new ImageIcon(getClass().getResource("myimage.jpeg");

This uses a fancy way to load the pic so that it will work when put into a Jar file. 这使用一种奇特的方式来加载图片,以便将其放入Jar文件时可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM