我真的不明白这一点。当我在Eclipse中运行我的程序时,它看起来非常好。它出现在下面:
Chemistry program when run from Eclipse
(请注意,我拖了一些东西来掩盖我的全名,因为这个程序是为学校项目编写的。请忽略它)。 请注意,一切都显示
然而,当我在eclipse之外运行程序时......
Chemistry program when run from outside of Eclipse
正如您所看到的,任何与PaintComponent相关的对象都不会显示,但JText和JButton的所有其他对象都会显示出来。 JOptionPane消息框也会显示出来。值得注意的是,一切看起来都不是全部来自一个JPanel,它不包含任何显示的内容。
以下是未出现的Panel代码:
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);
}
}
答案 0 :(得分:4)
请勿尝试使用paintComponent()
方法读取图片!
更重要的是,到部署时,这些资源可能会成为embedded-resource。在这种情况下,必须由URL
而不是File
访问资源。有关标记的info page,请参阅URL
。
g.drawImage(image, 45, -10, null);
最好是g.drawImage(image, 45, -10, this);
catch (Exception e) { ..
的代码更改为catch (Exception e) { e.printStackTrace(); // very informative! ..
pack()
。