gpt4 book ai didi

java - JFrame 内存泄漏

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:50:49 26 4
gpt4 key购买 nike

我用这个简单的代码在 java 中创建了一个新项目:

    public static void main(String[] args)
{
JFrame frame;
frame = new JFrame("Empty");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

我注意到移动 JFrame 会导致进程使用的内存增加。

  1. 这是为什么?
  2. 有没有办法使用上面相同的代码但添加一些内容来避免这种情况?
  3. 是否有更好的方法来简单地显示 JFrame?

最佳答案

看到内存使用量增加并不意味着存在内存泄漏。该程序可能会使用更多内存,因为它必须为事件分派(dispatch)或重绘创建临时对象。这些临时对象是短暂的,会在短时间内被垃圾收集器移除;因此它们使用的内存再次可供程序使用。

你不会用进程监控工具看到这一点,因为内存没有返回给操作系统; JVM 保留它以备将来使用。您可以使用 VisualVM 等工具监控程序的实际内存使用情况。

Are there any better ways to simply display a JFrame?

您发布的代码实际上是不正确的;您不应该从程序的主线程创建和操作 GUI 对象。这是显示 JFrame 的正确示例 from the Java Tutorial :

import javax.swing.*;        

public class HelloWorldSwing {
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Add the ubiquitous "Hello World" label.
JLabel label = new JLabel("Hello World");
frame.getContentPane().add(label);

//Display the window.
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

关于java - JFrame 内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18947627/

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