SwingNode doesn't respond to Swing component resize?
Brian Bolstad
bbolstad at ikonscience.com
Mon Apr 18 20:08:10 UTC 2016
Hello everyone,
In the SwingNode#resize(double, double) documentation, it states:
"Applications should not invoke this method directly. If an application needs to directly set the size of the SwingNode, it should set the Swing component's minimum/preferred/maximum size constraints which will be propagated correspondingly to the SwingNode and it's parent will honor those settings during layout."
However, I'm not seeing this behavior-the SwingNode doesn't resize for me unless I remove and re-add the Swing component to the SwingNode after resizing.
In the implementation, the private class SwingNodeContent has methods like preferredSizeChanged that I assume should be called when the Swing component size constraints are modified. However, it looks to me like JLightweightFrame only installs pref/max/min size property change listeners on components added after the first one. So, SwingNode never gets notified of the size changes and never updates it's cached values for the swing component's sizes and never updates its layoutBounds.
Below is a sample that demonstrates the problem I'm seeing; if you click the button, it will double its size, but the enclosing SwingNode doesn't change size. I'm running JavaFX 8u66 on Windows 10.
I'm very new to JavaFX, so what am I doing wrong?
Thanks,
BB
import javafx.application.Application;
import javafx.embed.swing.SwingNode;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javax.swing.*;
import java.awt.*;
public class SwingNodeResize extends Application
{
@Override
public void start(Stage primaryStage)
{
SwingNode swingNode = new SwingNode();
init(swingNode);
StackPane root = new StackPane(new Rectangle(500, 500, Color.RED), swingNode);
Scene scene = new Scene(root);
primaryStage.setTitle("SwingNode Resize");
primaryStage.setScene(scene);
primaryStage.show();
}
private void init(final SwingNode node)
{
SwingUtilities.invokeLater(() ->
{
JButton button = new JButton("Click me!");
button.addActionListener(event ->
{
Dimension buttonSize = button.getSize();
buttonSize.setSize(buttonSize.getWidth() * 2, buttonSize.getHeight() * 2);
button.setPreferredSize(buttonSize);
button.setMinimumSize(buttonSize);
button.setMaximumSize(buttonSize);
button.setSize(buttonSize);
System.out.println("Button size: " + button.getPreferredSize() + "; " +
"SwingNode size: " + new Dimension((int) node.prefWidth(-1), (int) node.prefHeight(-1)));
});
node.setContent(button);
});
}
public static void main(String[] args)
{
launch(args);
}
}
More information about the openjfx-dev
mailing list