3

我是 Java 新手。我只是想将图像加载为背景JFrame。我想做的是从 C 驱动器(那不是我的工作区)获取图像,所以我做了什么Board.java

   ImageIcon i = new ImageIcon("C:/image.png");
   img =i.getImage();

并尝试将它画成这样:

    public void paint(Graphics g )
    { 
    super.paint(g);
    Graphics2D  g2d= (Graphics2D) g;
    g2d.drawImage(img, 0, 100, null);
    }

然后我像这样打电话给我的主班

   public static void main(String[] args) 
   {
    JFrame frame= new JFrame(" Game") ;
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(1200, 365);
    frame.setVisible(true);
    frame.add(new Board());

   }

但是我没有显示任何图像,所以添加是合法的方式Image吗?

4

4 回答 4

5
  • 不要paint()覆盖JFrame
  • setSize()在设置为可见之前不要调用JFrame宁可使用JFrame#pack()
  • 养成使用/的习惯,不管平台是否支持。

这是我做的一个例子:

在此处输入图像描述

  • 创建JPanel/JLabel实例
  • paintComponent(..)JPanel/中覆盖JLabel
  • 覆盖getPreferredSize()以返回尺寸正确的尺寸/组件Image
  • 添加JPanel/JlabelJFrame实例
  • 打包JFrame_JFrame#pack()
  • 设置JFrame可见

测试.java:

//necessary imports
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    static String filename = "c:/test.jpg";//your file path and name here use / as it will work on linux platforms too so get into the habbit

    /**
     * Default constructor
     */
    public Test() throws Exception {
        initComponents();
    }

    /**
     * Initialize GUI and components (including ActionListeners etc)
     */
    private void initComponents() throws Exception {
        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final Image background = ImageIO.read(new File(filename));
        final Dimension jpanelDimensions = new Dimension(new ImageIcon(background).getIconWidth(), new ImageIcon(background).getIconHeight());

        frame.add(new JPanel() {
            @Override
            protected void paintComponent(Graphics grphcs) {
                super.paintComponent(grphcs);
                grphcs.drawImage(background, 0, 0, null);
            }

            //return a JPanel that matches images size
            @Override
            public Dimension getPreferredSize() {
                return jpanelDimensions;
            }
        });

        frame.setResizable(false);

        //pack frame (size JFrame to match preferred sizes of added components and set visible
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {

        /**
         * Create GUI and components on Event-Dispatch-Thread
         */
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    //set nimbus look and feel
                    for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                        if ("Nimbus".equals(info.getName())) {
                            UIManager.setLookAndFeel(info.getClassName());
                            break;
                        }
                    }
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
                    e.printStackTrace();
                }
                try {
                    //create GUI instance
                    Test test = new Test();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    }
}
于 2012-11-05T18:54:17.323 回答
0

使用 Swing,您必须使用paintComponent() 来代替paint()。

于 2012-11-05T18:20:53.763 回答
0

改用此格式位置

C:\\1.png
于 2012-11-05T18:17:15.703 回答
0

在您的代码中:

移到frame.add(new Board());之前frame.setVisible(true);,即:

另外,添加frame.pack();

public static void main(String[] args) 
{
    JFrame frame= new JFrame("Game") ;
    frame.add(new Board());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(1200, 365);
    frame.pack();
    frame.setVisible(true);
}

一旦 JFrame 设置为可见,就应该只有事件调度线程才能触摸它。

作为旁注,除非您确切知道自己在做什么,否则请覆盖paintComponent()而不是:http: //docs.oracle.com/javase/tutorial/uiswing/painting/closer.htmlpaint()

要点是它paint()实际上负责调用以下内容:paintComponent()paintBorder()paintChildren()。因此,如果您只是paint()盲目地覆盖,它将以您可能不希望的方式改变您的组件的行为。

于 2012-11-05T18:24:34.970 回答