JavaFX和SwingNode:getLocationOnScreen错误

最后发布: 2015-08-28 11:44:30


问题

我已将JComboBox放入SwingNode。 第一次单击时,组合框会正确打开,在我将其从场景中删除并放回原处后,组合框弹出窗口被破坏了。 经过一些调试后,我找到了罪魁祸首:getLocationOnScreen第二次返回错误的坐标。

这是复制器:

import java.awt.Point;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;

import javafx.application.Application;
import javafx.embed.swing.SwingNode;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

/**
 * 1. Start with -Djavafx.embed.singleThread=true
 * 2. Click on "position" button
 * 3. Click on combobox
 * 4. Click on "show/hide" button
 * 5. Click on "show/hide" button
 * 6. Click on "position" button. Compare with previous position
 * 7. Click on combobox. Popup is not positioned correctly.
 */
public class SwingNodePopup extends Application
{
   private SwingNode swingNode = new SwingNode();
   private BorderPane borderPane;
   private JComboBox<String> comboBox;

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

   @Override
   public void start(Stage primaryStage) throws Exception
   {
      borderPane = new BorderPane();
      borderPane.setStyle("-fx-padding: 20px;");

      swingNode = new SwingNode();

      comboBox = new JComboBox<>();
      comboBox.setModel(new DefaultComboBoxModel<>(new String[]{"1", "2", "3"}));

      swingNode.setContent(comboBox);

      HBox buttonBar = new HBox();

      Button showHideButton = new Button("Show / Hide");
      showHideButton.setOnAction(this::onShowHideButtonClick);

      Button positionButton = new Button("Position");
      positionButton.setOnAction(this::onPositionButtonClick);

      buttonBar.getChildren().add(showHideButton);
      buttonBar.getChildren().add(positionButton);

      borderPane.setCenter(new StackPane(swingNode));
      borderPane.setBottom(buttonBar);

      Scene scene = new Scene(borderPane);

      primaryStage.setScene(scene);
      primaryStage.setWidth(800);
      primaryStage.setHeight(600);
      primaryStage.show();
   }

   private void onPositionButtonClick(ActionEvent actionEvent)
   {
      Point locationOnScreen = comboBox.getLocationOnScreen();

      System.out.println(locationOnScreen);
   }

   private void onShowHideButtonClick(ActionEvent actionEvent)
   {
      if (borderPane.getCenter() == null) {
         borderPane.setCenter(swingNode);
      } else {
         borderPane.setCenter(null);
      }
   }
}

还有其他人遇到过这个问题吗?

java swing javafx