我使用 Swing 开发 Java 开发软件,我的代码有问题,我想使用 LoadingFrame 类显示图像,这是它的主要工作,但是当我在 main 中调用构造函数和 start() 方法时类,框架打开但图像不显示(我没有异常(exception))。 为什么它不适用于我的主类?
public class LoadingFrame
{
private JFrame frame;
public LoadingFrame()
{
frame = new JFrame();
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.setUndecorated(true);
frame.setContentPane(new Panneau());
}
public void start()
{
frame.setVisible(true);
}
public void stop()
{
frame.setVisible(false);
}
public static void main(String[] args)
{
LoadingFrame l = new LoadingFrame();
l.start();
try
{
Thread.sleep(3000);
}
catch(Exception e)
{
e.printStackTrace();
}
l.stop();
}
}
public class Panneau extends JPanel
{
public void paintComponent(Graphics g)
{
System.out.println("hello");
try
{
Image img = ImageIO.read(new File("Images/loading.png"));
//g.drawImage(img, 0, 0, this);
//Pour une image de fond
g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
App 类是我的主类:
public class App {
//Attributes used to display the application
private JFrame frame;
//Attribute which display a waiting frame
private static LoadingFrame loadingFrame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
loadingFrame = new LoadingFrame();
loadingFrame.start();
App window = new App();
loadingFrame.stop();
window.frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public App()
{
initialize();
synchronizeScriptReferenceList();
synchronizeTests();
}
[...]
}
最佳答案
我能够从 App.java
让它工作。由于某种原因,使用 EventQueue
并不能解决问题。我也尝试使用 SwingUtilities
,但这也不起作用。最后,我尝试直接在主线程中运行它,从而摆脱 App.main 中的 Thready-stuff 。出于某种原因,当其他方法不起作用时,这种方法有效!这是我的代码:
// In the App class:
public static void main(String[] args) {
try {
loadingFrame = new LoadingFrame();
loadingFrame.start();
App window = new App();
loadingFrame.stop();
window.frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
当我使用这段代码时,我让它工作了! (出于某种我不知道的原因),这是 Panneau
类的额外重写:
class Panneau extends JPanel
{
Image img;
public Panneau() {
try
{
img = ImageIO.read(new File("Images/loading.png"));
}
catch (IOException e)
{
e.printStackTrace();
}
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
}
这个类有两个主要区别;我解决的问题。它们在这里:
- 我将
super.paintComponent
称为我们自己的paintComponent
中的第一个方法 - 我只在构造函数中加载一次加载图像,而不是每次我想绘制时,这都会使一切变得更加平滑。 (您不希望加载屏幕占用大量 CPU 资源,是吗?)
希望通过这些改进,您可以使您的程序正常运行!它对我很有效,所以我祝你好运。
附注不要调用frame.pack(),这是我的一个错误。出于某种原因,我认为它不适用于未装饰的 window 。
关于java - JFrame 中的图像不想与另一个类中的调用一起显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37300184/