我在使用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的五倍甚至更多,并且当对象大量增加时执行窗口不能流畅运行(swing还可以)。 我有什么方法可以优化它吗?
最佳答案
考虑对每个数据片段使用虚拟化控件而不是节点
30,000 个按钮很多。一般来说,我不建议向场景添加数千个节点。相反,我建议您使用虚拟化控件,该控件仅创建节点来表示屏幕上可见的数据,而不是您拥有的所有可能的数据。这就是 TableView 和 ListView 等内置控件的工作原理。它们具有单元工厂并呈现动态单元,这些单元提供了支持数据的 View ,并随着支持数据的变化而不断更新(例如,当用户在 ListView 中上下滚动时)。这种策略允许 TableView 有效地表示包含数十万项的数据结构。
当您的实现基于 GridPane 时,与 GridPane 功能类似的虚拟化控件是 ControlsFX GridView 。我建议您看一下,看看它是否适合您的需要。
关于JavaFX占用内存并不断增加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36001545/