Add a picture to a JFrame

前端 未结 3 1118
北恋
北恋 2021-01-29 17:02

All I am trying to do is add a picture to a JFrame.

I am really confused and don\'t really understand... I have looked up every possible question on this s

3条回答
  •  耶瑟儿~
    2021-01-29 17:32

    I have a couple of tips for you:

    • If you know your frame size then there is no need to over-complicate it
    • Try using frame as the JFrame's name rather than xF so it is easier to look at.
    • Rearrange your methods so that setVisible(true); is at the end.

    Now, as for your code I suggest you use two classes: One for the frame and one for the panel.

    The frame class

    import javax.swing.JFrame;
    
    public class Apollo
    {
        public static void main(String[] args)
        {
        Jframe frame = new JFrame("xFrame");
        frame.setSize(800,600);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(new Poseidon());
        frame.setVisible(true);
        }
    }
    

    The panel class

    import javax.swing.*;
    import java.awt.*;
    
    public class Poseidon extends JPanel
    {
        public void paintComponent(Graphics g)
        {
        g.setColor(Color.WHITE);
        g.fillRect(0,0,800,600);
    
        ImageIcon clicker = new ImageIcon("/Clicker/xS/cow.png");
        /*The following are two methods for image sizing,
         *Use the one that best fits your code:
         *
         *g.drawImage(clicker.getImage(), x, y, null); 
         *Fill in the arguments for x and y to locate your upper left corner
         *The image will be in it's original size
         *
         *g.drawImage(clicker.getImage(), x, y, w, h, null);
         *Fill in the arguments for w and h to set the width and height of your image
         *The image will be in it's scaled size
         */
        }
    }
    

提交回复
热议问题