【问题标题】:JavaFX occupy memory and increasing?JavaFX占用内存越来越大?
【发布时间】:2016-03-15 02:17:59
【问题描述】:

我在使用javaFX GUI时遇到了一些问题,下面的代码是执行时的性能测试,我在javaFX和swing中创建了三万个按钮对象。当我执行程序时,javaFX写的已经占用了700MB内存,并且随着时间的推移而增加,但是swing写的另一个示例只使用了120MB内存并且没有增加。

这是使用 javaFX 的代码

public class ManyButtons_JavaFX extends Application{
private static final int ROWS = 300;
private static final int COLS = 100;

public void start( Stage stage ){
    stage.setTitle("Many Buttons JavaFX");
    stage.setWidth(600);
    stage.setHeight(400);

    GridPane grid = new GridPane() ;
    grid.setHgap(10);
    grid.setVgap(10) ;

    for( int y = 0 ; y < ROWS ; y++ ){
        for( int x = 0 ; x < COLS ; x ++ ) {
            grid.add(new Button("Button " + x + "," + y ) , x , y ) ;
        }
    }
    ScrollPane scroll = new ScrollPane(grid) ;
    stage.setScene(new Scene(scroll) ) ;
    stage.show() ;
}

public static void main( String[] args ){
    launch(ManyButtons_JavaFX.class , args) ;
}

那是用swing写的

public class ManyButtons_Swing extends JFrame{
private static final int ROWS = 300;
private static final int COLS = 100;

ManyButtons_Swing(){
    this.setTitle("Many Buttons Swing");
    this.setSize(600,400) ;

    JPanel grid = new JPanel(new GridLayout(ROWS , COLS , 10 , 10 )) ;
    for( int y = 0 ; y < ROWS ; y++ ){
        for( int x = 0 ; x < COLS ; x ++ ) {
            grid.add(new JButton("Button " + x + "," + y ) ) ;
        }
    }
    JScrollPane sc = new JScrollPane(grid) ;

    this.setContentPane(sc);
    this.setVisible(true);
}

public static void main( String[] args ){
    new ManyButtons_Swing() ;
}

用javaFX编写的程序总是使用swing的5倍或更多,并且当对象大幅增加(swing可以)时,执行窗口无法流畅运行。 有什么办法可以优化吗?

【问题讨论】:

标签: java performance swing memory javafx


【解决方案1】:

考虑为每个数据块使用虚拟化控件而不是一个节点

30,000 个按钮很多。一般来说,我不建议在场景中添加数千个节点。相反,我建议您使用虚拟化控件,该控件仅创建节点来表示屏幕上可见的数据,而不是您拥有的所有可能数据。这就是 TableView 和 ListView 等内置控件的工作方式。它们具有单元工厂,并呈现动态单元格,这些单元格提供支持数据的视图,并随着支持数据的变化而不断更新(例如,当用户在 ListView 中上下滚动时)。这样的策略允许 TableView 有效地表示包含数十万个项目的数据结构。

由于您的实现基于 GridPane,因此类似于 GridPane 功能的虚拟化控件是 ControlsFX GridView。我建议你看看它,看看它是否适合你的需要。

【讨论】:

  • 谢谢你,这是一个很好的解决方案,但如果我想同时显示所有节点,javaFX 无法忍受。
  • 是的,用户无论如何都看不到所有这些节点,因为几乎所有节点都不在滚动窗格的可见区域内。
猜你喜欢
  • 1970-01-01
  • 2012-09-15
  • 2017-01-28
  • 2022-11-02
  • 2014-05-02
  • 1970-01-01
  • 1970-01-01
  • 2017-10-15
  • 2019-07-01
相关资源
最近更新 更多