gpt4 book ai didi

java - Paint Component 在 Eclipse 之外不工作

转载 作者:行者123 更新时间:2023-11-29 03:33:56 24 4
gpt4 key购买 nike

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

Chemistry program when run from Eclipse

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

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

Chemistry program when run from outside of 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);
}
}

最佳答案

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

更重要的是,到部署时,这些资源可能会变成 .在这种情况下,必须通过 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();//信息量很大! ..
  • 不要设置顶级容器的大小。而是布局内容并调用 pack()

关于java - Paint Component 在 Eclipse 之外不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16509986/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com