1

我真的不明白这个。当我在 Eclipse 中运行我的程序时,它看起来非常好。它出现在下面:

从 Eclipse 运行时的化学程序

(请注意,我拖了一些东西来掩盖我的全名,因为这个程序是为学校项目编写的。请忽略这一点)。请注意,一切都会显示

但是,当我在 Eclipse 之外运行程序时...

从 Eclipse 外部运行时的化学程序

如您所见,任何与 PaintComponent 相关的对象都不会显示,但其他所有 JText 和 JButton) 都会显示。JOptionPane 消息框也会出现。值得注意的是,没有出现的所有内容都来自一个 JPanel,它不包含任何出现的内容。

以下是未出现的面板代码:

package gui;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JPanel;

public class TopPane extends JPanel {
    public TopPane(){
        setLayout(new FlowLayout());
    }

    public void paintComponent(Graphics g){
        try{
        String filename = "logo.jpg";
        Image image = ImageIO.read(new File(filename));
        g.drawImage(image, 45, -10, null);

        String intro = "Program by XXXXXXX XXXX\n";
        String intro2 = "The purpose of this program is to make the process of creating a solution";
        String intro3 = "less painful by performing the calculations for how much solute needs to be\n";
        String intro4 = "added to the solvent.  Miscellanious additional information will also be provided.\n";
        String intro5 = "\n";
        String intro6 = "Please enter infromation in the following format:\n";
        String intro7 = "<volume> <molarity> <compound>\n";
        String intro8 = "For example:";
        String intro9 = "5mL 5M H2SO4";
        g.drawString(intro, 30, 70);
        g.drawString(intro2, 30, 95);
        g.drawString(intro3, 30, 110);
        g.drawString(intro4, 30, 125);
        g.drawString(intro5, 30, 140);
        g.drawString(intro6, 30, 155);
        g.drawString(intro7, 30, 170);
        g.drawString(intro8, 30, 195);
        g.drawString(intro9, 30, 210);
        }catch(Exception ex){System.out.println("Failed");}
    }
}

这是运行在 Eclipse 之外运行时不起作用的类的类的代码示例:

package gui;
import java.awt.BorderLayout;
import javax.swing.JFrame;

public class MainFrame extends JFrame{
    public MainFrame(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Chemistry Lab Assistant");
        setSize(550, 300);

        //Top Frame
        TopPane topPane = new TopPane();
        add(topPane);

        //Input Pane
        InputPane inputPane = new InputPane();
        add(inputPane, BorderLayout.SOUTH);
    }
}
4

1 回答 1

4

不要试图在paintComponent()方法中读取图像!

更重要的是,到部署时,这些资源很可能会变成。在这种情况下,资源必须由URL而不是访问File。请参阅标签的信息页面,了解形成URL.

更多提示:

  • g.drawImage(image, 45, -10, null);最好是g.drawImage(image, 45, -10, this);
  • 将表单的代码更改catch (Exception e) { ..catch (Exception e) { e.printStackTrace(); // very informative! ..
  • 不要设置顶级容器的大小。而是布局内容并调用pack()
于 2013-05-12T17:30:44.923 回答