开发者

Why is there no Picture in my Panel/Window?

开发者 https://www.devze.com 2023-03-11 02:37 出处:网络
whats wrong with my code? I just want to have a Picture in my Window... //class ImagePanel: public class ImagePanel extends JPanel {

whats wrong with my code? I just want to have a Picture in my Window...

//class ImagePanel:

public class ImagePanel extends JPanel {

    private static final long serialVersionUID = -7664761101121497912L;

    public Image i;

    public ImagePanel(Image i) {
        this.i = i;
    }

    @Override
    public void paintComponents(Graphics g) {
        super.paintComponent(g);        
        g.drawImage(this.i, 0, 0, null);
    }
}

//class Main

public class Main extends JFrame {

    public static void main(String[] args) {

    JFrame frame = new JFrame();
        frame.setSize(1024, 768);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        ImagePanel panel = null;

        try {
            panel = new ImagePanel(ImageIO.read(new File("D:/test.JPG")));
        } catch (IOException e) {
            e.printStackTrace();
        }

        frame.getContentPane().add(panel);
        frame开发者_JAVA技巧.setVisible(true);
    }
}

There is just a Window without a picture :( Whats the problem? And is there an easy way to set size of the window == picture size?

Thank you!


You must override paintComponent(Graphics g) instead of paintComponents(Graphics g).


The best solution is to use a JLabel. Don't reinvent wheel. There is no need for you to do custom painting.

But if you do custom painting then you need to override the getPreferredSize() method to be the size of the image so the layout manager can do their job.


please read this tutorials about Icon in Swing and your Image would by placed to the JLabel but with same way/funcioanlities as to the JPanel


I not at all familiar with Java panes, but don't you need to set the size of ImagePanel before you add it to the content pane.

0

精彩评论

暂无评论...
验证码 换一张
取 消