Add a picture to a JFrame

孤者浪人 提交于 2019-12-02 13:45:07

The biggest issues I can see are...

  • Extending from JFrame, but not actually using it...
  • Reliance on static when not really required...
  • Calling setVisible before anything has actually begin added. In fact, generally trying to manipulate the frame properties before anything was added to it and after it was made visible...

    public class Main {

     public static void main(String[] args){
    
         EventQueue.invokeLater(new Runnable() {
             public void run() {
    
                 JFrame xF = new JFrame("xFrame");
                 xF.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                 xF.add(new JLabel(new ImageIcon("/Clicker/xS/cow.png")));
                 xF.setResizable(false);
                 xF.setSize(WIDTH*SCALE,HEIGHT*SCALE);
                 xF.setLocationRelativeTo(null);
                 xF.setVisible(true);
    
              }
         }
     }
    

    }

But since you never actually described what problems you were having, these are all guesses...

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
     */
    }
}

You can use xF.setContentPane(new JLabel(new ImageIcon(image_path)));

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!